I've been using a macro X similar to


to format certain words that may contain an underscore, without having to escape with \_. This worked until I used it in a \caption. This results in an error with both pdflatex and lualatex (! Missing $ inserted.). Consider this MWE:



  \caption{One \X{a_b} Two}

Do I have to use a different / more elaborate solution for X or should I just escape the underscores generally? I am more interested in the best practices instead of a very clever hack.

1 Answer 1


You need the command to be robust, otherwise the annotation in the .lof file becomes

\contentsline {figure}{\numberline {1}{\ignorespaces One \texttt {a_b} Two}}{1}%

(I changed the syntax from {\ttfamily...} to \texttt{...}, which is better). As you see, the \detokenize has been applied and disappeared.

On the other hand, if you do

\newcommand{\X}{}% for safety

the annotation would be

\contentsline {figure}{\numberline {1}{\ignorespaces One \X {a_b} Two}}{1}%

and the problem would not show.

Alternatively, use \protect\X when in a moving argument.

  • As a follow-up: 1. Would you personally use \DeclareRobustCommand and \detokenize or simply escape the underscores? 2. Is there a situation where \newcommand should be used instead of \DeclareRobustCommand?
    – apriori
    Sep 10, 2020 at 13:50
  • @apriori I'd use \_, to be honest, but I don't know your document that might have hundreds of these. When to use \DeclareRobustCommand? Well whenever the command is expected to be found in section titles or captions.
    – egreg
    Sep 10, 2020 at 13:56
  • As for when NOT to use \DeclareRobustCommand or \protect, you cannot use protected macros in \edef or \ifnum. See the refcount package as an example of overcoming the restrictions on \ref. Sep 10, 2020 at 14:33

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.