[Tex/LaTex] Expansion of macros within chemmacros’ \ch{} macro

chemmacrosexpansionmacros

I have some chemical formulae throughout my whole text that are changed from time to time. So I defined a macro \compound with the approporiate content for usage in chemmacros' \ch macro.

Compiling the document (see MWE) shows that the direct entry works as expected (is typeset as a formula), while the second version is typeset as normal text.

\documentclass{minimal}
\usepackage{chemmacros}
\newcommand{\compound}{H2O}

\begin{document}
Works: \ch{H2O}
Does not work: \ch{\compound}
\end{document}

Do I miss (or misunderstand) something?

Any help is very appreciated. Thanks in advance.

Best Answer

\ch is not provided by chemmacros but by the chemformula package.

As you've noticed it doesn't expand its argument. As a consequence when it sees \compound (unaware of its definition) it does nothing with it and just inputs it. Only afterwards \compound expands to its definition but then it is too late.

That means you either need to do that manually by adding the appropriate number of \expandafters or you can define a \chX (say) which expands its argument once before parsing it:

\documentclass{article}
\usepackage{chemformula}

\ExplSyntaxOn
\NewDocumentCommand \chX { O{}m }
  { \chemformula_ch:no {#1} {#2} }
\cs_generate_variant:Nn \chemformula_ch:nn {no}
\ExplSyntaxOff

\newcommand{\compound}{H2O}

\begin{document}

\ch{H2O} \par
\expandafter\ch\expandafter{\compound} \par
\chX{\compound}

\end{document}

If you choose the \chX way together with chemmacros you either should also load chemformula explicitly (\usepackage{chemmacros}\usepackage{chemformula}) or tell chemformula to do it for you (\chemsetup{formula = chemformula}) before defining the variant.

Related Question