# Using \detokenize and underscore in combination with \listoffigures

I've been using a macro X similar to

\newcommand{\X}[1]{{\ttfamily{\detokenize{#1}}}}


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:

\documentclass{article}

\newcommand{\X}[1]{{\ttfamily{\detokenize{#1}}}}

\begin{document}
\listoffigures
\begin{figure}
\centering
\caption{One \X{a_b} Two}
\end{figure}
\end{document}


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.

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
\DeclareRobustCommand{\X}[1]{\texttt{\detokenize{#1}}}


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 '20 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 '20 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. – John Kormylo Sep 10 '20 at 14:33