2

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.

3

\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.

  • Thank you very much for your detailed answer! It solved the problem. – Buchstree Mar 16 '17 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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