[Tex/LaTex] How to highlight characters both in text and math environments in a flexible way

colorhighlightingmath-modesoul

I would like to color the background of characters (word, sentences or math variables) with the same command in text paragraphs and in equations.
The command \colorbox{color}{some text} doesn't do the job because it is not able to break lines, and it is not usable with math content.

Then I tried to use the soul package as given here. This is very close to what I want except it doesn't work within math environment.

Here is a MWE (the problematic part is commented and marked by a red dot on image):

\documentclass{article}
\usepackage{xcolor}
\usepackage{soul}

\sethlcolor{gray} 

\begin{document}
This is a long text without highlighting. \hl{This is a long text with highlighting over the line break.} This is a long text without highlighting.

This is an equation with highlighted variable:
$
1+x^2+ %\hl{x^3}
$
\end{document}

Compiled code with red dot

Thank you for your help.

Best Answer

Don't, please. ;-)

\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}
\usepackage{soul}

\sethlcolor{gray}

\DeclareRobustCommand{\mhl}[1]{%
  \text{\hl{$#1$}}%
}

\begin{document}
This is a long text without highlighting. \hl{This is a long
text $x^3$ with highlighting over the line break.} This is a long
text without highlighting.

This is an equation with highlighted variable:
$
1+x_{\mhl{zz}}^2+\mhl{x^3}
$
\end{document}

One might think to make a command that works both in text and in math:

\DeclareRobustCommand{\mhl}[1]{%
  \ifmmode\text{\hl{$#1$}}\else\hl{#1}\fi
}

enter image description here

The example shows that the gray background doesn't fully cover the exponent also in the standard version, so it's a soul problem.

Related Question