0

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.

Tobard
  • 1,189

1 Answers1

2

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.

egreg
  • 1,121,712
  • 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 06 '17 at 13:11
  • @Tobard There are too many possible reasons, without an example. – egreg Jan 06 '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 06 '17 at 15:31
  • @Tobard Does it work with \hl to begin with? I don't think so. – egreg Jan 06 '17 at 15:34
  • Oh you're right, this comes directly from the soul package. This may be worth another question, then. – Tobard Jan 06 '17 at 15:38
  • \hl{For the moving state, speeds of \SI{5}{\km\per\hour} and \SI{20}{\km\per\hour} are considered}. Why it is not working when used as above? – Pankaj Singh Sep 23 '21 at 04:41