It seems that \hl
command in the soul package can not work with escaped space. A minimal non-working example is
\documentclass{article}
\usepackage{xcolor, soul}
\colorlet{mycolor}{red!30}
\sethlcolor{mycolor}
\begin{document}
\hl{can\ we\ highlight}
\end{document}
The error message is
Package soul Error: Reconstruction failed.
Some posts (for example, here and here) suggest using \mbox
(or \hbox
) to wrap the text or using \protect
. While these methods work, they have some drawbacks:
- If
\mbox
is used, long text will not wrap normally. - If
\protect
is used, the background color for text will disappear.
How to solve this problem more elegantly?
Edit
The solution shared by Skillmon works for English, but not for Chinese. The following MWE will illustrate that.
\documentclass{ctexart}
\usepackage{xcolor, soul}
\usepackage{xparse}
\let\hlORIG\hl
\colorlet{mycolor}{red!30}
\sethlcolor{mycolor}
\ExplSyntaxOn
\tl_new:N \l_jdhao_hlx_tl
\RenewDocumentCommand \hl { +m }
{
\tl_set:Nn \l_jdhao_hlx_tl { #1 }
\tl_replace_all:Nnn \l_jdhao_hlx_tl { \ } { ~ }
\exp_args:NV \hlORIG \l_jdhao_hlx_tl
}
\ExplSyntaxOff
\begin{document}
\hl{test\ test} %% pass!
\hl{测试\ 测试} %% fail!
\end{document}
It is interesting that English test passed, but the Chinese test failed. The error message is the same.