8

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}

enter image description here

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

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

1 Answer 1

10

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.

2
  • 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. :-)
    – frougon
    Oct 5, 2020 at 9:53
  • @frougon Ah, right, thanks! Not sure why I thought of \span Oct 5, 2020 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.