I'd like to highlight particular parts of an amsmath environment. Here's a minimal working example:
\documentclass{article}
\usepackage{amsmath,color}
\newcommand{\abs}[1]{\lvert#1\rvert}
\newcommand{\Abs}[1]{\left\lvert#1\right\rvert}
%\newcommand{\highlight}[1]{\colorbox{yellow}{#1}}
\newcommand{\highlight}[1]{\boxed{#1}}
\begin{document}
\begin{alignat*}{2}
&\lim_{\Delta x \to 0} \frac{\Delta y}{\Delta x} = \ell \\
\iff& \forall \epsilon > 0, \, \exists \delta > 0 \text{ s.t. if }
0 < \abs{\Delta x - 0} < \delta,
\text{ then } \Abs{\frac{\Delta y}{\Delta x} - \ell} < \epsilon \\
\iff& \forall \epsilon > 0, \, \exists \delta > 0 \text{ s.t. if }
0 < \highlight{\abs{x - x_0}} < \delta, \text{ then }
\highlight{\Abs{\frac{f(x) - f(x_0)}{x-x_0} - \ell}} < \epsilon
\end{alignat*}
\end{document}
If I change which version of the \highlight
command is commented out, the compiler starts complaining about Missing $ inserted
.
Best Answer
The problem here is that
\colorbox
reverts it's argument back to text mode. And, since you're using math-related macros (like\left
,\right
,\frac
and\ell
) in text mode, TeX complains about a missing$
. So you need to explicitly state that you're in math mode using:I've added the
\displaystyle
to make sure your fractions and delimiters are expanded as usual. If this behaviour is unwanted, you can modify or remove it.On that topic,
amsmath
provides\dfrac
which is short for\displaystyle\frac
. Such explicit use of display/text style fractions works well to force one's intent, and would eliminate the use of\displaystyle.
It is possible to improve the
\highlight
macro to detect the type of math mode being used. This is possible by using\mathchoice
which provides typesetting choices for 4 different styles:In the updated version of
\highlight
the math mode is detected prior to using\colorbox
, and switched accordingly inside it. Additionally, for generalization, I've added an optional argument to\highlight
that allows you to switch the colour (default isyellow
) as showcased in the MWE: