[Tex/LaTex] How to make a macro require math mode

macrosmath-mode

I have defined a macro that I would like to be used exclusively in math mode. In order to enforce this, I would like the macro to throw an error message whenever it is used outside of math mode. What is the easiest way of making a macro math-mode-only?

Best Answer

You can use \ifmmode to check if you are in math mode, and trigger an error if not. An attempt to use it outside of math mode yields:

Attempt to use \MyMathModeMacro outside of math mode.

See my preamble documentation for explanation.

Type H for immediate help.

l.16 \MyMathModeMacro % <--- This will produce an error ?

Notes:

Code:

\documentclass{article}
\makeatletter
\DeclareRobustCommand{\MyMathModeMacro}{%
    \ifmmode
         E = m c^2
    \else
        \GenericError{\space\space\space\space}
            {Attempt to use \@backslashchar MyMathModeMacro outside of math mode}
            {See my preamble documentation for explanation.}
            {Need to use either use inline or display math.}%
    \fi
}
\makeatother

\begin{document}
$\MyMathModeMacro$

\MyMathModeMacro% <--- This will produce an error
\end{document}
Related Question