When to use \protected

ε-TeX introduced the idea of ‘protected’ macros over ten years ago, but many experienced (La)TeX users struggle with the concept. The idea of the \protected primitive is that it will prevent a macro being expanded inside an \edef or \write, so that


will give

->\example .

Why would you want to do this? Well, there are some things that do not work properly inside an \edef. The classic one is an assignment: the following does not work


This will give an undefined control sequence error for \fails, rather than carrying out in ‘inner’ \def. So as part of a general strategy I would recommend always making any macro that performs an assignment protected. That also applies if you know that one macro will use another that is itself protected. This is exactly what we’ve been doing in the work on LaTeX3, where the aim is that all macros are either protected or will expand safely inside an \edef. However, the idea applies more widely: making things protected is a lot more reliable than using LaTeX’s ‘robust’ mechanism, and avoids some nasty errors. ε-TeX has been around long enough that there is no real excuse not to make use of this mechanism.

4 thoughts on “When to use \protected

  1. Wow, how great! Having only read the TeXbook a long time ago, I had no idea of this thing! *Very* useful.

    I guess that the time has come to read source3.pdf…

  2. Remember this is an e-TeX primitive: something that Knuth did not include in TeX82 that the NTS team decided was useful.

  3. Yes, I know. But nowadays I think I can safely assume that e-TeX primitives are available in LaTeX (although I know a few people with really old TeX installations).

  4. I always assume e-TeX is available: I was simply pointing out that this wouldn’t be in The TeXbook (or indeed TeX by Topic).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.