[Tex/LaTex] Automatically add \texorpdfstring for math-mode in section titles

hyperrefmath-modesectioningwarnings

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}

Best Answer

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].

enter image description here

Doing selective replacement would need implementing a full parser.

Related Question