[Tex/LaTex] Undefined control sequence error with mhchem and hyperref, \ce within \section{}

hyperrefmhchempandoc

I get an "undefined control sequence" error when trying to use the mhchem and
hyperref packages together, when \ce is within a \section{} label. A minimum example that demonstrates the problem:

\documentclass{article}
\usepackage[version=3]{mhchem}
\usepackage{hyperref}
\begin{document}
\section{\ce{H2O}}
\end{document}

The error message using pdflatex in MikTeX 2.9 on Windows:

! Undefined control sequence.
\mhchem@ce ...ate {s}\chardef \mhchem@ce@substate
                                                  =0\relax \mhchem@ce@result...
l.5 \section{\ce{H2O}}

I'm very new to mhchem, and latex in general — is this a known problem? Is
there a workaround? (As background, I first encountered this problem trying to use \ce within
a markdown file and then make a pdf with pandoc. The template.latex file for
pandoc adds \usepackage{hyperref} when using pdflatex.)

Best Answer

\ce breaks in the code that tries to convert it to a bookmark string. With \texorpdfstring an alternative can be provided for the bookmarks:

\documentclass{article}
\usepackage[version=3]{mhchem}
\usepackage[pdfencoding=auto]{hyperref}
\usepackage{bookmark}
\begin{document}
\section{\texorpdfstring{\ce{H2O}}{H\texttwoinferior O}}
\end{document}

In this case you are lucky, that there is a subscript 2 in Unicode (enabled by option unicode or pdfencoding=auto).

Also \ce can be disabled for bookmarks to print its argument at least:

\pdfstringdefDisableCommands{\let\ce\@firstofone}% after hyperref is loaded

Package bookmarks improves the algorithm for the bookmarks, that makes an additional LaTeX run obsolete in most cases. Also it adds more features.

Math example from the comments

\documentclass{article}
\usepackage[version=3]{mhchem}
\usepackage[pdfencoding=auto,psdextra]{hyperref}
\usepackage{bookmark}
\bookmarksetup{numbered,open}
\begin{document}
\section{Water \texorpdfstring{\ce{H2O}}{H\texttwoinferior O}}
\section{Implication of \texorpdfstring{$E=mc^2$}{E = mc\twosuperior}}
\section{Solutions of \texorpdfstring
  {$\ddot s = -\omega^2 s$}%
  {\"s = \textminus\omega\twosuperior s}%
}
\end{document}

Result with math