# What's a reliable way to detect math mode (including align*)?

I thought \ifmmode detected math mode, but clearly it does not:

\documentclass{article}
\usepackage{amsmath}
\begin{document}
$\ifmmode math \else not math \fi$
$\ifmmode math \else not math \fi$
\begin{align*}
\ifmmode math \else not math \fi
\end{align*}
\end{document}


How do I reliably detect math mode, including within align*?

• Strangely enough, if I add \relax before \ifmmode, then it works fine... Oct 5, 2020 at 1:20

Adding \relax, as you noted in the comment, is the solution basically. If you look at the LaTeX sources you'll see that most uses of \ifmmode are preceded by \relax, exactly for that reason:
\def\verb{\relax\ifmmode\hbox\else\leavevmode\null\fi %[...]

At the beginning of a table cell (roughly what align uses) TeX is expanding macros looking for \omit or \noalign, and at this point it's not in math mode, and expands \ifmmode which is then false.
Adding \relax (or any non-expandable token) stops that scanning, and the column template is inserted, effectively starting math mode.
• Hi, I believe you meant \noalign instead of \span (in case this is after a \cr; otherwise, only \omit). cf. TeXbook pp. 240 and 248. :-) Oct 5, 2020 at 9:53
• @frougon Ah, right, thanks! Not sure why I thought of \span Oct 5, 2020 at 10:04