[Tex/LaTex] Why can’t TeX show us the actual “undefined control sequence”

tex-core

This is a question on the internals of the TeX system rather than on how to use it. Every time an undefined control sequence is used in a document, TeX prints the message

undefined control sequence [<code>]

where <code> is usually an excerpt from the code that contains the actual control sequence that caused the error.

Many times, however, it seems TeX cannot give us a precise error messages. It often happens in beamer presentations, for example, where all we get is

undefined control sequence [\end{frame}]

Of course, in this example, \end is defined, and the problem lies in some piece of code inside the environment. This often happens also with undefined control sequences expanded from complicated macros.

I understand that this behavior probably comes from the intricacies of how tokens get expanded in the frame environment, but since TeX itself is expanding the tokens, how hard can it be to print the name of the actual undefined control sequence? This could be immensely useful for debugging purposes.

So is there a technical reason why TeX does not print which is the control sequence which is actually undefined, or is it like this on purpose?

Best Answer

Generally you can find the undefined control sequence if you look in the right place. Here's a simple beamer document:

\documentclass{beamer}
\begin{document}
\begin{frame}
\frametitle{A title}
\foo
\end{frame}
\end{document}

And the error it generates:

./undefined.tex:6: Undefined control sequence.
\beamer@doifinframe ...\frametitle {A title} \foo 
                                                  \end {beamer@frameslide}
l.6 \end{frame}

The undefined control sequence is the last control sequence in the first line of code reported by the error. This is in fact fairly consistent, and if you ask TeX for help on the error (by entering h in the console), this is exactly what it tells you:

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

So you can tell the actual offending undefined control sequence, you just need to know where to look. Unfortunately many editing environments hide or otherwise filter the console output, so perhaps this is why it appears not to report the offending command.

This is not to say that all errors are as easy to diagnose in TeX; they're not, because often the line that the error gets noticed is after the line that causes the error. But for undefined control sequences, this is not the case.