45

I have a PNG plot with a couple of black patches in it, and I'd like to refer to it in the \caption of the figure. According to the TikZ manual, I'd have to

\tikz \fill[black] (1ex,1ex) circle (1ex);

which works perfectly outside a \caption. Using this inside a \caption, though, leaves me with the compile error

! Use of \use@pgflibrary doesn't match its definition.
\pgfutil@ifnextchar ...1\def \pgfutil@reserved@a {
                                              #2}\def \pgfutil@reserved@...
l.375 ...blah blah.}

?

The following produces the compile error

\documentclass{article}
\usepackage{tikz}

\begin{document}
\tikz \fill[orange] (1ex,1ex) circle (1ex);
\begin{figure}
\caption{\tikz \fill[orange] (1ex,1ex) circle (1ex);}
\end{figure}
\end{document}

Any hints here?

53

The argument of \caption is a moving argument, i.e. it can also be displayed in the list of figures. It is therefore written into an external file. This does not work with fragile macros. See e.g. What is the difference between Fragile and Robust commands? for more details.

You can fix this by one of the following ways:

  1. Use the optional argument of \caption:

    \caption["Short" caption without tikz code]{Long caption with tikz code}
    

    In this case only the short version is placed in the external file and the list of figures.

  2. Add \protect for every macro:

    \caption{Some caption with tikz code: \protect\tikz \protect\fill[black] (1ex,1ex) circle (1ex);}
    
  3. Define a robust macro for the TikZ code:

    % At best in the preamble:
    \DeclareRobustCommand\mytikzdot{\tikz \fill[black] (1ex,1ex) circle (1ex);}
    
    % later
    \caption{Some caption with tikz code: \mytikzdot}
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.