# Automatically add \texorpdfstring for math-mode in section titles

I'm receiving a ton of warnings á la "token not allowed in a pdf string", since most of my section titles contain math (see this post here: Hyperref - Token not allowed or here: Hyperref warning - Token not allowed in a PDF string).

I want to apply the solution provided to previous questions, i.e. write \texorpdfstring{$$math$$}{Lg}. However, I would rather want this to be done automatically. Could the math environment (within section titles) be changed to automatically add \textorpdfstring.

MWE:

\documentclass{article}
\usepackage{hyperref}
\begin{document}
\section{$$I$$ cast warnings but I wish I wouldnt}
\section{\texorpdfstring{$$I$$}{I} dont}
\section{Of course me neither}
\end{document}
• What should be done with $$\alpha=\sum_{i=0}^n \beta_i$$? – egreg Apr 29 '16 at 10:07
• @egreg: That is not really important, for readability in the pdf-viewer it would probably be best to just strip all characters that can't be used (i think this roughly corresponds to the behavior when I just ignore the warning). As simpler solution could just be to replace it always with "[math]" or so. – sheß Apr 29 '16 at 10:10

A simple solution is to gobble math with \pdfstringdefDisableCommands:

\documentclass{article}
\usepackage{hyperref}

\makeatletter
\pdfstringdefDisableCommands{\let$$\fake@math} \newcommand\fake@math{}% just for safety \def\fake@math#1$${[math]}
\makeatother

\begin{document}
\section{$$I$$ cast warnings but I wish I wouldnt}
\section{\texorpdfstring{$$I$$}{I} dont}
\section{Of course me neither}
\end{document}

This will replace all math formulas in $$...$$ with [math].

Doing selective replacement would need implementing a full parser.

• Great. Do you know why this (or some more sophisticated version) is not implemented as the default? Rather than always displaying this warning? – sheß Apr 29 '16 at 10:39
• @sheß I guess that Heiko wanted to leave the decision to the user. – egreg Apr 29 '16 at 10:45
• @sheß May be you prefer \def\fake@math#1\){\detokenize{#1}} so you get a little more information than [math]. Or whatever you choose, but I mean that it contains \detoknize{#1} so you actually know what was in that particular math mode. – Manuel Apr 29 '16 at 10:55
• @Manuel That can be a good idea; of course it depends on what math is expected to sneak in titles. – egreg Apr 29 '16 at 10:57
• @sheß Well, if I enable the unicode option, $$\sum\alpha$$ outputs some strange Chinese characters in the bookmark: picture – egreg Apr 29 '16 at 11:08