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.
\textnormalcommand and was searching something way to complicated. Just out of curiosity, why would you not use \xspace? – Ascurion Jul 07 '13 at 23:27\twCO{}in text mode. – egreg Jul 07 '13 at 23:32xspacesee Drawbacks of xspace – A.Ellett Jul 07 '13 at 23:36mhchemin this case? At least it is quite good at typesetting isotopes etc. – daleif Jul 08 '13 at 08:22mhchemto do the isotopes and molecule typesetting part and some chemical formulas I wrote by hand. However, my question also included physical units such as, e.g. L$_{\odot}$ wheremhchemcant help. – Ascurion Jul 08 '13 at 19:39\textupinstead of\textnormalor, if you want also to respect italic, just\text(requiresamsmath). – egreg Jul 09 '13 at 11:07\textthis is working as I intend it too. Thanks again! – Ascurion Jul 09 '13 at 17:55