[Tex/LaTex] Why does LaTeX make a distinction between commands and environments

environmentsmacros

Why does LaTeX make a distinction between commands and environments?
Or also: why do we need environments?

I ask this because I am defining a number of custom commands (like \question{} and \answer{}) and I am not entirely sure whether to use the \newcommand-way or the \newenvironment-way (both work). The difference seems to be in supporting Tables and Figures and other 'complicated' stuff in my custom command.

(If I compare to HTML/CSS, all things are tags (or CSS classes or IDs), and they can be specified (or default to) to be inline or not. But apart from that, there is not a real difference among them. It seems to be that the underlying model of HTML/CSS formatting is simpler and therefor easier to understand and use.)

Best Answer

As Phillippe has already said, environments are usually best for this. To understand why, you need to follow how TeX works in reading arguments. For a command

\foo{<stuff>}

TeX reads all of <stuff> before expanding \foo. This can be an issue if <stuff> is very big. Also, once TeX has read an argument it can be difficult or impossible to change the category codes (these are important in TeX!). In particular, verbatim material is difficult to handle reliably in an arbitrary argument.

With environments, LaTeX does not read everything in one go. At \begin{foo} the set up is done, but the environment is then typeset normally without everything being read in one go. This makes it possible to include verbatim and avoids filling up TeX's memory with too much. I'd also point out that LaTeX makes each environment a group, which is why things like

\begin{center}
  \bfseries
  Text
\end{center}

keep the font changes local.

(The comparison to HTML/CSS is made a lot, which ignores the fact that the HTML model came long after the LaTeX one, and also the fact that the requirements for a typesetting model are different to those for on-screen display using HTML.)

Related Question