I'd like to have a function that I can use like a highlighter, both in text and in math mode. I wrote something that works but it's really slow and still causes problems in some situations. Here is the function:
%-------------------------Highligh-------------------------%
\newif\ifhighlight
\highlighttrue
\definecolor{colorA}{rgb}{1,1,0.5}
\definecolor{colorB}{rgb}{0.85,0.85,1}
\newlength{\fboxseptemp}
\newcommand{\hl}[2][colorA]{%
\ifhighlight%
\setlength{\fboxseptemp}{\the\fboxsep}%
\setlength{\fboxsep}{0pt}%
\ifmmode%
\text{\hl[#1]{$#2$}}%
\else%
$\mathrlap{\text{\smash{\colorbox{#1}{\phantom{#2\vphantom{\strut}}}}}}$%
\setlength{\fboxseptemp}{\fboxseptemp}%
#2%
\fi%
\else%
#2%
\fi}
%-------------------------Highligh-------------------------%
I can use it like this:
For sets $A$ and $B$ let $\hl{B^A}$ denote the \hl{set of all mappings} from $A$ to $B$.
It works fine in many situations but it's not perfect. First of all it compiles really slowly. In some situations the colored background boxes are to wide. This happens if latex shrinks a text to fit it in a line. The box is then as long as the original (not shrunk) text and thus a little bit longer than the text that is displayed. Also it cannot deal with line breaks. Another problem are ligatures if they are before the highlighting.
\hl{empty}.
is formated exactly as
empty.
The dot is moved towards the y and overlaps with the colored box a little bit as it should. But
f\hl{inite}
produces a different result than
finite
The f and the i are not merged correctly and the colored box covers the f a little bit. Does anybody know a more elegant, fast and stable solution for that problem?

but none of the solutions there do.
– Mario Jun 17 '15 at 11:08