# Macro Substitution/Expansion in Environment Names

I've noticed that you can use macros for substitution into environment names:

\def\itmz{itemize}
\begin\itmz
\item Item the first
\item Item the second
\end\itmz             % works


It also works with \newcommand in place of \def.

However, this doesn't work (\end\itmz replaced by \end{itemize}),

\def\itmz{itemize}
\begin\itmz
\item Item the first
\item Item the second
\end{itemize}         % doesn't work


and I get the following somewhat cryptic error message:

! Latex Error: \begin{itemize} (...) ended by \end{itemize}


What is the difference here, behind the scenes, for the tex compiler?

BTW: I'm not asking because I want to save keystrokes in typing itemize; I'm trying to understand how tex's macro substitution/expansion model works.

• Funny error message, isn't it? I also know how to make LaTeX stop with “Missing \begin{document}” at \begin{document}. ;-) – egreg Jul 3 '18 at 15:32

At a TeX level, \begin takes one argument (<name>), which is then used to look for a macro which is the expansion of <name> to 'characters'. So here, we are looking for \itemize. That exists, so we start a list. The <name> is also saved as given: that's going to be important. (The data is saved in \@currenvir.)

At the end of the environment, \end also grabs one argument. It then does a check that the argument it's grabbed matches the current environment name. However, there is no expansion done: we are doing the same as

\def\name{itemize}
\def\tempa{\name}
\def\tempb{itemize}
\ifx\tempa\tempb
% TRUE
\else
% FALSE
\fi


As you'll find if you run the example, that's FALSE: the definitions are not the same (although they expand to the same thing).

You get an 'interesting' message as printing the message does do expansion. So what you see is what you probably thought you were doing!

One could argue that the LaTeX kernel could \edef (exhaustively expand) the name of the environment at both ends, in which case the issue would vanish. However, the formal LaTeX doesn't support giving environment names as macros: that's a technical detail. (It would be valid to detokenize the arguments and use them as-is, for example.)