[Tex/LaTex] How to reliably switch the highlighting color with soul

pdftexsoul

In my document I need to use different colors for highlighting text. The soul package provides yellow coloring by default. The color can be switched with the \sethlcolor command. However, this does not properly work within a figure caption.

Example code:

\documentclass[]{article}
\usepackage{soul}
\usepackage{color}

\newcommand{\hlcyan}[1]{{\sethlcolor{cyan}\hl{#1}}}

\begin{document}
An example of \hlcyan{highlighted words with hlcyan} in a normal paragraph.

\begin{figure}
\caption{A minimal caption in a figure environment with some
\hlcyan{highlighted text via the newly defined hlcyan command}
and a few remaining words.}
\end{figure}
\end{document}

The \sethlcolor-based method works in the normal paragraph. It also "works" in the figure caption in the sense that the resulting PDF has the correct highlighting (see below for an image). However, pdflatex throws the following error messages:

[...]
(c:/texlive/2014/texmf-dist/tex/context/base/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
)
! Argument of \@textcolor has an extra }.
<inserted text>
                \par
l.11 ...lcyan command} and a few remaining words.}

Runaway argument?
! Paragraph ended before \@textcolor was complete.
<to be read again>
                   \par
l.11 ...lcyan command} and a few remaining words.}

[1{c:/texlive/2014/texmf-var/fonts/map/pdftex/updmap/pdftex.map}] (./doc.aux) )
(see the transcript file for additional information)<c:/texlive/2014/texmf-dist
/fonts/type1/public/amsfonts/cm/cmr10.pfb>
Output written on doc.pdf (1 page, 16490 bytes).
[...]

Screenshot of the resulting PDF file:
enter image description here

Additional notes:

  • Using plain hl{...} in the figure caption does not yield errors.
  • Directly using {\sethlcolor{cyan}\hl{...}} in the figure caption throws the same error. That is, the error is not related to the definition of the new command.
  • I actually do want to define my own commands for different colors, which is why I included this in the example.

I would be grateful for any pointers. There should be a way to make soul use a different color w/o changing its behavior.

Best Answer

The command you defined is fragile and will break in moving arguments. You can either \protect it in moving arguments or, better, declare it robust from the beginning:

\documentclass[]{article}
\usepackage{soul}
\usepackage{color}

\DeclareRobustCommand{\hlcyan}[1]{{\sethlcolor{cyan}\hl{#1}}}

\begin{document}
An example of \hlcyan{highlighted words with hlcyan} in a normal paragraph.

\begin{figure}
\caption{A minimal caption in a figure environment with some
\hlcyan{highlighted text via the newly defined hlcyan command}
and a few remaining words.}
\end{figure}
\end{document}

enter image description here