Labels – Using LaTeX Label with & Symbol

labels

I need to write a label that contains a '&'. This is a strange need, but it is for use in a \keyword macro, which also adds a string to the aux file, which I can later parse (e.g., with an external program). Names in English apparently can contain an &, as in S&P~500.

\documentclass{article}

\NewDocumentCommand{\keyword}{ m }{%
  \label{KW:\thesection:\thepage:#1}%
  \textbf{#1}
}

\begin{document}

\keyword{abc}
\keyword{def}
\label{i\&j}
\keyword{s\&p500}

\end{document}

Error is of course

! Missing \endcsname inserted.
<to be read again> 
\&
l.4 \newlabel{i\&j}{{}{1}}

How would I ask latex to just consider the & a viable character in a string for the aux file?

advice appreciated.

Best Answer

You're abusing \label just to write something to the .aux file: no such created \label can be used in a \ref, because you don't know where it will eventually be typeset.

I'd not use \newlabel in the .aux file, but a different marker.

\documentclass{article}

\ExplSyntaxOn
\NewDocumentCommand{\fakelabel}{m}{} % for the .aux file

\NewDocumentCommand{\keyword}{ m }
  {
    \group_begin:
    \cs_set:Npx \& { \token_to_str:N \& }
    \iow_shipout:cx { @auxout }
      {
        \token_to_str:N \fakelabel { KW : \thesection : \thepage : #1 }
      }
    \group_end:
    \textbf{#1}
  }
\ExplSyntaxOff

\begin{document}

\keyword{abc}
\keyword{def}
\keyword{s\&p500}

\end{document}

About \label{i\&j}, just avoid it or use \label{i&j} which works.

The contents of the aux file will be

\relax
\fakelabel{KW:0:1:abc}
\fakelabel{KW:0:1:def}
\fakelabel{KW:0:1:s\&p500}
\gdef \@abspage@last{1}

Your external program will be able to look for \fakelabel and use the supplied data.

Related Question