Seems that there is some subtlety in using \ifmmode that I am not aware of. For some reason, using:
\newcommand{\hlcodeA}[1]{\ifmmode\else\small\fi\texttt{\hilight{#1}}}%
is not quite identical to:
\newcommand{\hlcodeB}[1]{\texttt{\hilight{\ifmmode\else\small\fi#1}}}%
where I moved the \ifmmode test to the inner level of the macro from the outer.
Both are ok, except in an alignenvironment where \hlcodeB has no problems, but \hlcodeA yields a warning:
LaTeX Font Warning: Command \small invalid in math mode on input line 26
Notes:
No problems are reported when used in an
equationenvironment.The MWE below yields a warning, but replacing
\hlcodeA{y2}with\hlcodeB{y2}in thealignenvironment, no warnings are reported.This example is not really intended to produce proper output in math mode, but it seems that I am abusing the
alignenvironment in my real example. This is old code for my internal documentation where I now know that I should have usedtabularinstead -- this was not obvious to me in early 2011 when I started this document :-) , and am just now trying to clean up some of the warnings.
Code:
\documentclass{article}
\usepackage{xcolor}
\usepackage{amsmath}
\newcommand{\hilight}[1]{\colorbox{yellow}{#1}}%
\newcommand{\hlcodeA}[1]{%
\ifmmode\else\small\fi\texttt{\hilight{#1}}%
}%
\newcommand{\hlcodeB}[1]{%
\texttt{\hilight{\ifmmode\else\small\fi#1}}%
}%
\begin{document}
\hspace*{5.0cm}\hlcodeA{y} = \hlcodeA{x}% This is ok (no warnings)
\begin{equation}% This is ok (no warnings)
\hlcodeA{y1} = \hlcodeA{x1}
\end{equation}
\begin{align}% This is NOT ok (warnings but only from \hlcodeA)
\hlcodeA{y2} = \hlcodeB{x2}
\end{align}
\end{document}

\newcommand{\hlcodeA}[1]{\relax\ifmmode\else\small\fi\texttt{\hilight{#1}}}yields no errors. So it seems I would have had this problem even with tabular. Hmmm, it appears I can't quite accept this answer yet -- probably need to get more rep to accept answers quicker. – Peter Grill Nov 14 '12 at 00:06\relax\immode? Clearly there must be such a case, otherwise it would have been built into\ifmmode? – Peter Grill Nov 14 '12 at 00:17\relaxwould be a bad idea. – David Carlisle Nov 14 '12 at 00:26\relaxbe a bad idea before a\immode? If it is complicated, I can post another question? – Peter Grill Nov 14 '12 at 00:30\relaxcan have some unwanted affects such as stopping ligatures. Also of course sometimes you need the command to work by expansion only so it can come before\omitand\relaxstops that. – David Carlisle Nov 14 '12 at 00:32