[Tex/LaTex] “Argument of \@caption has extra }” error using \makemathbox inside caption

captionsmathtools

I have a math expression which I seem to be unable to use inside a caption. Here's what I want to compile:

\documentclass{article}

\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{MnSymbol}

\begin{document}
\begin{figure}
\caption{$\mathrel{\xleftarrow{\mathmakebox[0.55em]{}}\hspace*{-0.4em}\smallsquare}$}
\end{figure}
\end{document}

If I move the math out of the caption, it compiles fine.

(The example is slightly less than minimal; I thought it would be useful to show what the expression does. I can reproduce the problem with the following:

\documentclass{article}

\usepackage{mathtools}

\begin{document}
\begin{figure}
\caption{$\mathmakebox[0.55em]{}$}
\end{figure}
\end{document}

but it doesn't produce any output.)

Best Answer

That error message is evidence for a fragile command in a moving argument; in this case it's \mathmakebox; when in a caption, use \protect in front of it.

Better, define a new command for complicated constructions:

\DeclareRobustCommand\leftarrowbox{%
  \mathrel{\xleftarrow{\mathmakebox[0.55em]{}}\hspace*{-0.4em}\smallsquare}%
}

and in your document type \leftarrowbox.

I hope you're not loading MnSymbol just to get \smallsquare. See Importing a Single Symbol From a Different Font for a workaround. With the standard fonts you can get away with

\DeclareRobustCommand{\leftarrowbox}{%
  \leftarrow\mathrel{\mkern-2.5mu\xsmallsquare}
}
\newcommand{\xsmallsquare}{{\vcenter{\hbox{$\scriptscriptstyle\square$}}}}