# How to highlight characters both in text and math environments in a flexible way?

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}


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
}


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

• Thank you, that is what I needed! Unfortunately I noticed it doesn't work with a \phantom character (error saying "Incomplete \iffalse"). Do you know why? – Tobard Jan 6 '17 at 13:11
• @Tobard There are too many possible reasons, without an example. – egreg Jan 6 '17 at 13:44
• Sorry, just add \mhl{This is a sentence \phantom{word} containing a phantom word.} in the MWE you gave and you'll have the error. Thanks. – Tobard Jan 6 '17 at 15:31
• @Tobard Does it work with \hl to begin with? I don't think so. – egreg Jan 6 '17 at 15:34
• Oh you're right, this comes directly from the soul package. This may be worth another question, then. – Tobard Jan 6 '17 at 15:38