# Highlighting subscripts/superscripts in math mode

This is an extension of Highlight terms in equation mode,

The problem is, with

\newcommand{\highlight}[1]{%
\colorbox{red!50}{$\displaystyle#1$}}


In, $x^{\highlight{\alpha}}$, \alpha is enlarged abnormally, unlike a proper superscript.

Is there a way to highlight specific variables within math-mode whilst maintaining subscripts and superscripts?

• Does \scriptsize\alpha work for you?
– user193767
May 8 '20 at 12:06
\setlength{\fboxsep}{.5pt}        %% <- set (smaller) framebox margins
\sbox2{\hspace{-.5pt}%            %% <- create box 2, undo margin
\colorbox{#1}{\usebox0}%        %% <- print the contents of box 0 in a \colorbox
}%
\dp2=\dp0 \ht2=\ht0 \wd2=\wd0     %% <- set dimensions of box 2 to match box 0
\box2                             %% <- print box 2
\endgroup                           %% <- revert old definitions of the boxes and \fboxsep
}

\begin{document}

$a^{\highlight{\alpha}} + \highlight{\sum_{k=1}^\infty \frac{\fbox{1}}{\color{blue}k!}} + \frac{\highlight[green]{x}}{2}$
$a^{\alpha} + \sum_{k=1}^\infty \frac{\fbox{1}}{\color{blue}k!} + \frac{x}{2}$

\end{document}


I've tried to explain what each of these lines do in the comments, except for \mathsurround. Setting \mathsurround to 0pt does nothing here, but it would matter if your document uses non-standard spacing around inline equations (which is unlikely).

• I've added an improved version of \highlight` that allows you to choose a colour and shouldn't affect spacing in most circumstances. May 10 '20 at 10:44