I'm trying to develop a macro that gives two different outputs depending on whether it is in math mode (i.e. $ $
or \begin{equation} ... \end{equation}
) or anywhere else. The reason is that I use a lot of physical variables and molecule names such as e.g.
$^{12}$CO(1-0)
and use macros to be able to have them typeset uniformly troughout the text. I use them in normal text as well as math environment. Right now I have two macros one for text:
\newcommand{\twCO}{%
$^{12}$CO(1-0)\xspace%
}%
and one for math with out the math signs:
\newcommand{\twCO}{%
^{12}CO(1-0)%
}% .
I would like to come up with something more generic:
\newcommand{\twCO}{%
\ifinmathmode%
^{12}CO(1-0)%
\else%
$^{12}$CO(1-0)\xspace%
}
Searching quite some time on TeX and a prominent search provider, I could not find a satisfying answer to this, only more complex constructions to do the check. But I'd like to ask if someone is aware of a straightforward check to see which environment one is in?
EDIT:
After trying out the options given in the answer and comments below, I found that the
easiest and best setup for my situation in which I also want the new commands to respect boldface and italic (which I figured out after I asked...) from the environment is to use text
from amsmath
which was pointed out by @egreg in the comments to his answer. Thus the best solution to my question is to use something like:
\usepackage{amsmath}
\newcommand{\twCO}{\text{\textsuperscript{12}CO}}
To set Isotopes however mhchem
, which was pointed out in the comments, is really usefull.
However for someone that want to test for math mode, the second answer is working well. Or one could use \ensuremath
, also mentioned in the comments. This however does not respect boldface or italics from the environment.