[Tex/LaTex] rotatebox symbol in caption generates error

captionsrotating

Following minimal example doesn't work and generates an error

\documentclass{article}
\usepackage{graphicx}
\usepackage{amssymb}
\begin{document}
\begin{figure}
  FIGURE
\caption{$\blacksquare$ result of; \rotatebox[origin=c]{45}{$\blacksquare$}}%
\end{figure}
\rotatebox[origin=c]{45}{$\blacksquare$}
\end{document}

The error message says:

rotatebox-in-caption.tex|7| Argument of \@caption has an extra }.
|| <inserted text> 
||                 \par 
|| l.7 ...; \rotatebox[origin=c]{45}{$\blacksquare$}}

Do I have to wrap the \rotatebox in a certain box to make it work?

Best Answer

\rotatebox is fragile, see also: What is the difference between Fragile and Robust commands?

Inside "moving arguments" as in the argument of \caption fragile macros can be protected by prefixing them with \protect:

\documentclass{article}
\usepackage{graphicx}
\usepackage{amssymb}
\begin{document}
\listoffigures
\begin{figure}
  FIGURE
\caption{$\blacksquare$ result of;
 \protect\rotatebox[origin=c]{45}{$\blacksquare$}}%
\end{figure}
Text: \rotatebox[origin=c]{45}{$\blacksquare$}
\end{document}

Result

Making fragile macros robust

  • Package makerobust defines macro \MakeRobustCommand. It adds the LaTeX's protection layer for the macro in the same way as LaTeX's \DeclareRobustCommand:

    \usepackage{graphicx}
    \usepackage{makerobust}
    \MakeRobustCommand\rotatebox
    ...
    \caption{... \rotatebox ...}
    

    \rotatebox is no longer fragile and can be used without \protect.

  • Package etoolbox defines \robustify that redefines a macro with e-TeX's \protected:

    \usepackage{graphicx}
    \usepackage{etoolbox}
    \robustify\rotatebox
    ...
    \caption{... \rotatebox ...}
    

    This also makes \rotatebox robust without the need of \protect for this macro.