Incorrect spacing when placing binary operator in macro

colormacrosmath-modespacing

I have macros of the form

\newcommand{\typo}[1]{{\color{red}#1}}% for pointing out that there is a typo

When I use this command in mathmode though, it creates incorrect spacing with binary operators ($A\otimes B$ versus $A\typo{\otimes}B$).

I suspect this is a consequence of writing \otimes within {...} (see Make sure the spacing of a macro for a binary operator), but {...} is necessary to keep the color contained. I could fix this issue by replacing $A\typo{\otimes}B$ with $A\mathbin{\typo{\otimes}}B$.

But is there a way to fix the definition of the macro \typo, so that $A\typo{\otimes}B$ will produce the same spacing as $A\otimes B$?

Here is a MWE:

\documentclass{article} 
\usepackage{xcolor}
\newcommand{\typo}[1]{{\color{red}#1}}% for pointing out that there is a typo

\begin{document} 

Compare $A\otimes B$ with $A\typo{\otimes}B$ with $A\mathbin{\typo{\otimes}}B$.

The first and third have correct spacing; the middle does not.

\end{document}

Best Answer

enter image description here

a \begingroup group does not affect spacing in the same way.

\documentclass{article} 
\usepackage{xcolor}
\newcommand{\typo}[1]{\begingroup\color{red}#1\endgroup}% for pointing out that there is a typo

\begin{document} 

Compare $A\otimes B$ with $A\typo{\otimes}B$ with $A\mathbin{\typo{\otimes}}B$.

The first and third have correct spacing; the middle does not.

\end{document}

Of if you use the next version of (x)color already available if you use pdflatex-dev rather than pdflatex in texlive you can use \mathcolor which uses a definition based on this idea (but handling superscripts in a better way)

\documentclass{article} 
\usepackage{color}
\usepackage{xcolor}
\newcommand{\typo}[1]{\mathcolor{red}{#1}}% for pointing out that there is a typo

\begin{document} 

Compare $A\otimes B$ with $A\typo{\otimes}B$ with $A\mathbin{\typo{\otimes}}B$.

The first and third have correct spacing; the middle does not.

\end{document}
Related Question