[Tex/LaTex] wrong with \ch{CaO$_{(s)} + H2O$_{(l)}->Ca$^{2+}_{(aq)} + 2 OH$^-_{(aq)}}

chemmacros

In the interest of providing a complete question, I have the following code:

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{chemmacros}
\begin{document}
    \ch{CaO$_{(s)} + H2O$_{(l)}->Ca$^{2+}_{(aq)} + 2 OH$^-_{(aq)}}
\end{document}

When compiled does it produces lots of error messages (it does still compile though) how can I fix this?

Best Answer

You're misunderstanding the purpose of $. In TeX, $ means "switch between math mode and text mode". So with your original expression, you have the text CaO, the math expression _{(s)} + H2O, the text expression _{(l)}->Ca, math ^{2+}_{(aq)} + 2 OH and text ^-_{(aq)}. (You can tell because the math characters are italicized.) This all gets confused because ^ and _ normally aren't allowed in text mode (which causes an error and forces you into math mode), but chemmacros changes that.

Because we're using chemmacros, we can use ^ and _ within \ch without bothering with $, and everything works out fine (but we need spaces around the ->).

But chemmacros already knows about phases, and wants to help us out (see "The phases Module" in the documentation). We can simply have

\documentclass{article}
\usepackage{chemmacros}
\chemsetup[phases]{pos=sub}
\begin{document}
    \ch{CaO\sld{} + H2O\lqd{} -> Ca^{2+}\aq{} + 2 OH^-\aq{}}
\end{document}

output

Related Question