6

I have a CSV file with a list of chemical compounds I would like to have parsed through the \ce{} from the mhchem which converts them to nice chemical notation. While using the raw string as an argument for \ce{} works, when the same string is given as a command, the macro does nothing.

\documentclass{scrartcl}
\begin{filecontents*}{foo.csv}
Molecule
CH4
\end{filecontents*}
\usepackage{datatool}
\usepackage{mhchem}
\DTLloaddb{foo}{foo.csv}
\DTLgetvalue{\methane}{foo}{1}{1}
\begin{document}

CH4

\methane

\ce{CH4}

\ce{\methane}

\end{document}

Yields

Screenshot of result

So \ce{\methane} is not doing anything (it should be putting 4 as a subscript).

4
  • 2
    Untested but try \expandafter\ce\expandafter{\methane} Jan 26, 2017 at 14:02
  • Tested, Nicolas suggestion seems to work.
    – daleif
    Jan 26, 2017 at 14:03
  • I've converted my comment into an answer, and welcome to TeX.se! Jan 26, 2017 at 15:26
  • 1
    You are using mhchem without a version option. Please read your warnings.
    – mhchem
    Jan 26, 2017 at 17:05

1 Answer 1

8

It seems that \ce requires its argument to be expanded (presumably because \ce parses it) so you need to use \expandafter to ensure the argument is in the correct format:

\expandafter\ce\expandafter{\methane}

Explanation

Inside \ce, active characters (like ^, _ and {) have a different meaning. An intuitive meaning, but technically very different from standard LaTeX. Therefore, \ce has to parse the unexpanded input.

In this particular case, \ce found \methane, then it did the chemical formatting. Because it doesn't look chemical, it is just copied over and later expanded to CH4.

\expandafter\ce\expandafter{\methane} makes sure that \methane is expanded to CH4 before \ce takes a look at it.

Tip

You can create an own command for that.

\newcommand*\myce[1]{\expandafter\ce\expandafter{#1}}

So that you could simply write

\myce{\methane}
1
  • @mhchem Thank you for adding the explanation. Jan 26, 2017 at 17:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .