3
\documentclass{article}
\usepackage{listings}
\usepackage{hyperref}

\begin{document}
\lstlistoflistings
\section{Section}\label{section}
\begin{lstlisting}[caption={Sample from \hyperref[section]{this Section}}]
a = b;
\end{lstlisting}
\end{document}

When I compile the above mwe (twice) I get the following error.

! Argument of \Hy@babelnormalise has an extra }.
<inserted text> 
\par 
l.1 ...ple from \hyperref [section}{1}{lstlisting.1}

I've run across a `}' that doesn't seem to match anything.
For example, `\def\a#1{...}' and `\a}' would produce
this error. If you simply proceed now, the `\par' that
I've just inserted will cause me to report a runaway
argument that might be the root of the problem. But if
your `}' was spurious, just type `2' and it will go away.

I think this is caused by the square brackets of the \hyperrefcommand. These are probably interpreted as the begin of the short caption. How can I use commands with these kinds of arguments in a caption?

Adding curly braces or \unexpanded around the \hyperrefas suggested by this question does not work.

Benjamin
  • 499
  • 7
  • 17
  • 1
    You can use \texorpdfstring{\hyperref[section]{this Section}}{this Section}. – Peter Grill Sep 27 '16 at 09:09
  • This seems to work. However \texorpdfstring{\hyperref[section]{this Section}}{blub} seems to produce the same output. If you'd elaborate or link resources on this command I will accept this as an answer. – Benjamin Sep 27 '16 at 09:37
  • @PeterGrill especially the \section{\texorpdfstring{\textcolor{red}}{}{Red} Mars} example from the hyperref documentation confuses me. – Benjamin Sep 27 '16 at 09:50
  • WIth the above see the the bookmakrs that are made. The section heading will disaplay Red in red, but the bookmaks won't. I find that way of writng macros very confusing, but I think the above is equivalent to \section{\texorpdfstring{\textcolor{red}{Red}}{Red} Mars} which requires duplication of the text (but avoids the confusion). I used the duplicated text method in the MWE below. – Peter Grill Sep 27 '16 at 09:57

1 Answers1

5

You can use

\texorpdfstring{\hyperref[section]{this Section}}{this Section}

from the hyperref package, which defines separate strings to be used by TeX and in the PDF bookmarks. In your case you don't have the listing caption book marked so there is no visual difference. To see the difference try using the above in the \section{} macro and see how the bookmarks use the second parameter passed to the \texorpdfstring macro.

result

Notes:

  • I used the [colorlinks=true] option to hyperref so as to make it easier to see that the links were actually made.

Code:

\documentclass{article}
\usepackage{listings}
\usepackage[colorlinks=true]{hyperref}

\begin{document} \lstlistoflistings \section{Section}\label{section} \begin{lstlisting}[caption={Sample from \texorpdfstring{\hyperref[section]{this Section}}{xxxx}}] a = b; \end{lstlisting} \end{document}

Peter Grill
  • 223,288