mhchem 和 hyperref 未定义控制序列错误,\ce 在 \section{} 内

mhchem 和 hyperref 未定义控制序列错误,\ce 在 \section{} 内

当我尝试将 mhchem 和 hyperref 包一起使用时,如果\ce位于\section{}标签内,则会收到“未定义控制序列”错误。以下是演示该问题的最小示例:

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

在 Windows 上的 MikTeX 2.9 中使用 pdflatex 的错误消息:

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

我对 mhchem 和 latex 都很陌生——这是一个已知问题吗?有解决方法吗?(作为背景,我第一次遇到这个问题是在 markdown 文件中尝试使用 \ce,然后使用 pandoc 制作 pdf 时。\usepackage{hyperref}使用 pdflatex 时会添加 pandoc 的 template.latex 文件。)

答案1

\ce尝试将其转换为书签字符串的代码中断。\texorpdfstring可以为书签提供替代方案:

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

在这种情况下,您很幸运,Unicode 中有一个下标 2(通过选项unicode或启用pdfencoding=auto)。

\ce可以禁用书签以至少打印其参数:

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

此软件包bookmarks改进了书签算法,在大多数情况下,这使得额外的 LaTeX 运行变得不再必要。此外,它还添加了更多功能。

来自评论的数学例子

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

数学结果

相关内容