20

Do you know how LaTeX implements environments? To be more precise, what does

\newenvironment{<env-name>}[<n-args>][<default>]{<begin-code>}{<end-code>}

in terms of TeX commands (i.e., how is the LaTeX command \newenvironment defined in TeX)?

26

The command \newenvironment{<env-name>}[<n-args>][<default>]{<begin-code>}{<end-code>} is equivalent to:

\newcommand{\<env-name>}[<n-args>][<default>]{<begin-code>}
\newcommand{\end<env-name>}{<end-code>}

The reason is that \begin{<env-name>}...\end{<env-name>} is transferred into

<check whether the command \<env-name> exists
\begingroup
\csname <env-name>\endcsname % this is a way to call macro \<env-name> by its name
...
<check whether the inner-most environment is really <env-name>
\csname end<env-name>\endcsname % calls \end<env-name>
\endgroup

The problem is that you cannot do \newcommand{\#1}... so the command \csname...\endcsname is actually used by \newenvironment to overcome this problem.

The exact definition of \newenvironment is very complicated since the presence of * (that indicate the environment to be defined without \long), presence of [<n-args>] and [<default>] has to be tested, which in the terms of LaTeX means a lot of inner macros. To explore the details, you can run the following short source code that shows the macro definitions:

\documentclass{article}
\begin{document}
\parindent0pt
\parskip2ex
\makeatletter
\ttfamily
\meaning\newenvironment   % <-- put any macro name here
\par
\meaning\newcommand   % <-- put any macro name here
\makeatother
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.