# How to adjust the font in a \newcommand math expression to the environment

I'm writing my thesis about the gas NO2. The correct way to write this is $NO_2$. Currently, I have a macro defined to make typing easier:

\newcommand{\notwo}[0]{\chem{NO_2}\xspace}

\chem is a macro defined in the Copernicus package:

\def\testbx{bx}
\DeclareRobustCommand*{\chem}[1]{\ensuremath{%
\mathcode-="0200\mathcode\=="003D% no space around "-" and "="
\ifx\testbx\f@series\mathbf{#1}\else\mathrm{#1}\fi}}


However, I'd like to expand this a bit more. Especially, when I'm in sans-serif, I want \notwo to be sans-serif, and when I'm in sans-serif-bold, I want \notwo to be sans-serif-bold.

I'm using xelatex, and I'm using system-wide installed Myraid Pro font (OTF) via the line

\setsansfont[Mapping=tex-text,ItalicFont={MyriadPro-It},BoldFont={MyriadPro-Bold}]{Myriad Pro}.


How can I achieve this?

-
Look at the mhchem package for a general approach to chemical formulas. –  Joseph Wright Jan 9 '12 at 11:02
thanks - that works like a charm :) mhchem needs to be loaded after amsmath to avoid some package option clash errors, though. –  andreas-h Jan 9 '12 at 12:41
@JosephWright if your comment were an answer, I'd accept it because it circumvents my problem in the most elegant way. –  andreas-h Jan 9 '12 at 12:58

Look at the mhchem package for a general approach to chemical formulas. This allows the simple syntax

\ce{NO2}

-

You need to expand the tests and define a new math alphabet:

\makeatletter
\def\test@bx{bx}
\edef\test@sf{\sfdefault}
\DeclareRobustCommand*{\chem}[1]{\ensuremath{%
\mathcode-="0200 \mathcode\=="003D % no space around "-" and "="
\ifx\f@family\test@sf
\ifx\test@bx\f@series
\let\next\mathsfbf
\else
\let\next\mathsf
\fi
\else
\ifx\test@bx\f@series
\let\next\mathbf
\else
\let\next\mathrm
\fi
\fi
\next{#1}}}

\DeclareMathAlphabet{\mathsfbf}{\encodingdefault}{\sfdefault}{bx}{n}
\makeatother

-
thanks for your answer - it definitelly points into the right direction. However, I have a problem that in a bold-sf heading, \notwo is only bold, and not sf. I'm using xelatex, and I'm using system-wide installed Myraid Pro font (OTF) via the line \setsansfont[Mapping=tex-text,ItalicFont={MyriadPro-It},BoldFont={MyriadPro-Bol‌​d}]{Myriad Pro}. I suppose that's where my problem lies ... –  andreas-h Jan 9 '12 at 12:27
@andreas-h See edited message. However, you should add a MWE to show how you get sans serif headings. –  egreg Jan 9 '12 at 13:09