[Tex/LaTex] When using the accents package: underaccent greek symbol in caption of a table gives error

accentscaptionserrorsgreek

I am using the accents package to place a bar under math symbols. This works very well when using it in equations, and also in normal text (obviously still in the math environment $…$). However, currently I am creating a table with a caption and it does not want to compile. I preferably do not want to use \underbar.


MWE

\documentclass{article}

\usepackage{accents}
\newcommand{\ubar}[1]{\underaccent{\bar}{#1}}

\begin{document}

\begin{table}
\begin{tabular}{c}
a
\end{tabular}
\caption{$\ubar{\pi}$}
\end{table}

\end{document}

First error when using PDFTeXify in WinEdt 8.0 and MiKTeX 2.9 (I actually receive 100 errors).

! Undefined control sequence.
\underaccent #1#2->\begingroup \def \cc@a
                                           {#2}\cc@palette \cc@underaccent {#...
1.12 \caption{$\ubar{\pi}$}

The control sequence at the end of the top line 
of your error message was never \def'ed. If you have 
misspelled it (e.g. `\hobx'), type `I' and the correct 
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

Best Answer

The accents package defines command that are not robust: for instance we find

\newcommand\underaccent[2]{%
  \begingroup
    \def\cc@a{#2}% Stores the nucleous...
    \cc@palette\cc@underaccent{#1}% ...and the accent is passed
    #2%
  \endgroup}

A command like this will not survive being found in a “moving argument” (the argument to \caption, \chapter, \section and similar commands). Defining \ubar in terms of \underaccent makes \ubar share the same fragility.

The package really ought to do

\DeclareRobustCommand\underaccent[2]{%
  \begingroup
    \def\cc@a{#2}% Stores the nucleous...
    \cc@palette\cc@underaccent{#1}% ...and the accent is passed
    #2%
  \endgroup}

so the problem would disappear.

There are various fixes. The first is putting \protect in front of the command when it appears in a moving argument:

\caption{$\protect\ubar{\pi}$}

A better fix would be providing the protection to your command

\DeclareRobustCommand{\ubar}[1]{\underaccent{\bar}{#1}}

instead of using \newcommand.

An even better fix would be to remedy to the glitch in accents:

\documentclass{article}
\usepackage{fixltx2e}

\usepackage{accents}

\MakeRobust{\underaccent} % make \underaccent not fragile in moving arguments

\newcommand{\ubar}[1]{\underaccent{\bar}{#1}}

\begin{document}
\begin{figure}
\caption{$\ubar{\pi}$}
\end{figure}
\end{document}

Instead of fixltx2e you can use etoolbox:

\usepackage{etoolbox}

\usepackage{accents}
\robustify{\underaccent}

would do the same (in a different way).