Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
    
You can use \ifmmode, or use ensuremath so that it'll be in math mode. –  Peter Grill Nov 7 '12 at 1:44
    
@PeterGrill I would like to forbid the use of my macro outside of math mode. –  Lover of Structure Nov 7 '12 at 1:46
    
add comment

1 Answer

up vote 18 down vote accepted

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}
share|improve this answer
    
@Qrrbrbirlbel: I think you are right (have corrected), but surprisingly PackageError does not issue a PackageError if it does not get 3 parameters?? –  Peter Grill Nov 7 '12 at 1:51
    
@PeterGrill That was fast! I am wondering, is there a way of throwing an error in a way that doesn't make it look package-specific? (I might simply have defined this macro in my preamble.) –  Lover of Structure Nov 7 '12 at 1:55
1  
I normally just use \typeout{message}\QUITHERE, where \QUITHERE is not defined, but thought I would use the official way of reporting errors. Alternatively, you could use my preamble, or some other relevant text as the first parameter to \PackageError. –  Peter Grill Nov 7 '12 at 1:58
2  
@PeterGrill you can use \GenericError (four arguments). –  Gonzalo Medina Nov 7 '12 at 2:01
2  
You'll need to use \DeclareRobustCommand not \newcommand or you will get the wrong answer at the start of array cells. –  David Carlisle Nov 7 '12 at 2:05
show 6 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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