The TeX FAQ

Frequently Asked Question List for TeX

Programming

What’s the reason for “protection”?

Sometimes LaTeX saves data it will reread later. These data are often the argument of some command; they are the so-called moving arguments. (“Moving” because data are moved around.) Candidates are all arguments that may go into table of contents, list of figures, etc.; namely, data that are written to an auxiliary file and read in later. Other places are those data that might appear in head- or footlines. Section headings and figure captions are the most prominent examples; there’s a complete list in Lamport’s book (see TeX-related books).

What’s going on really, behind the scenes? The commands in moving arguments are normally expanded to their internal structure during the process of saving. Sometimes this expansion results in invalid TeX code, which shows either during expansion or when the code is processed again. Protecting a command, using \protect\cmd tells LaTeX to save \cmd as \cmd, without expanding it at all.

So, what is a “fragile command”? — it’s a command that expands into illegal TeX code during the save process.

What is a “robust command”? — it’s a command that expands into legal TeX code during the save process.

Lamport’s book says in its description of every LaTeX command whether it is “robust” or “fragile”; it also says that every command with an optional argument is fragile. The list isn’t reliable, and neither is the assertion about optional arguments; the statements may have been true in early versions of LaTeX2e but are not any longer necessarily so:

Further, simply “hiding” a fragile command in another command, has no effect on fragility. So, if \fred is fragile, and you write:

\newcommand{\jim}{\fred}

then \jim is fragile too. There is, however, the \newcommand-replacement \DeclareRobustCommand, which always creates a robust command (whether or not it has optional arguments). The syntax of \DeclareRobustCommand is substantially identical to that of \newcommand, and if you do the wrapping trick above as:

\DeclareRobustCommand{\jim}{\fred}

then \jim is robust.

Finally, we have the makerobust package, which defines \MakeRobustCommand to convert a command to be robust. With the package, the “wrapping” above can simply be replaced by:

\MakeRobustCommand\fred

Whereafter, \fred is robust. Using the package may be reasonable if you have lots of fragile commands that you need to use in moving arguments.

In short, the situation is confusing. No-one believes this is satisfactory; the LaTeX team have removed the need for protection of some things, but the techniques available in current LaTeX mean that this is an expensive exercise. It remains a long-term aim of the team to remove all need for \protection.

FAQ ID: Q-protect
Tags: latexmacros