# How to protect a fragile command in a moving argument? The case of macro containing \ifthenelse in \caption

This script works as expected:

\documentclass{article}
\usepackage{ifthen}
\usepackage{graphicx}
\newcommand{\foo}[1]{
\newcommand{\capt}{
\ifthenelse{\equal{#1}{ORIG}}
{original}
{optimised}
}

}
\begin{document}
\foo{ORIG}
\end{document}


However, when the macro \capt is inserted into a \caption in a figure environment

\documentclass{article}
\usepackage{ifthen}
\usepackage{graphicx}
\newcommand{\foo}[1]{
\newcommand{\capt}{
\ifthenelse{\equal{#1}{ORIG}}
{original}
{optimised}
}
\begin{figure}
\includegraphics[width=0.5\textwidth]{example-image-a}
\caption{\capt}
\end{figure}
}
\begin{document}
\foo{ORIG}
\end{document}


the error is

! Undefined control sequence.
<argument> \equal


What is the problem?

I am probably observing a symptom of a general feature. Therefore, help is appreciated how to form the title and this question to reflect the more general nature of this issue.

• Does it work with \protect\capt? – user36296 Oct 11 '18 at 14:07
• @samcarter, yes \protect\capt helps. – Viesturs Oct 11 '18 at 14:09
• this is typical "fragile command in moving argument" error (which is what \protect is designed to protect you from) – David Carlisle Oct 11 '18 at 14:14

I'm not sure why you do the intermediate step of defining \capt; however, the problem is that \ifthenelse is a fragile command, so it should be protected when in a caption or other moving argument.

There are better ways that don't require acrobatics.

\documentclass{article}
\usepackage{graphicx}
\usepackage{etoolbox}

\newcommand{\foo}[1]{%
\newcommand{\capt}{%
\ifstrequal{#1}{ORIG}
{original}
{optimised}%
}%
\begin{figure}
\includegraphics[width=0.5\textwidth]{example-image-a}
\caption{\capt}
\end{figure}
}
\begin{document}

\foo{ORIG}

\end{document}


Don't forget to protect the end of lines which could generate spaces in output.