How to make \hl (highlighting) to automatically place incompatible commands in \mbox?
You can (ab)use \soulregister
with the identifier 7
. While this command is meant to be used to register font switching commands (with identifier 0
or 1
), a look in the implementation part of the documentation reveals that it also accepts other numbers: 9
for accents, 8
for \footnote
and, the one that's interesting here, 7
for "\textsuperscript
or similar commands". Obviously, \cite
, \ref
and friends are similar enough.
When a command is registered this way, soul
will first expand it (including the argument), and then feed the result as a whole to its scanner, just like \mbox
would do. Note that while this is good enough for highlighting, striking out and underlining, it also means that it won't work in letterspaced text - there's no error, but no letterspacing either (which, I would guess, is probably the reason why these commands are not registered by default).
\documentclass[12pt]{article}
\usepackage{soul,color}
\soulregister\cite7
\soulregister\ref7
\soulregister\pageref7
\begin{document}
\st{This is a line containing a citation \cite{}.}
\hl{This is a line containing a reference \ref{sec} on page \pageref{sec}.}
\so{This reference: \ref{sec}, is not letterspaced.}
\setcounter{section}{122}
\section{1}\label{sec}
\end{document}
Another option using curly braces {}
around \ref, \cite
or \pageref
commands may be:
\documentclass[12pt]{article}
\usepackage{soul,color}
\begin{document}
\st{This is a line containing a citation {\cite{}}.}
\hl{This is a line containing a reference {\ref{sec}} on page {\pageref{sec}}.}
\so{This reference: {\ref{sec}}, is not letterspaced.}
\setcounter{section}{122}
\section{Section \# 123}\label{sec}
\end{document}