PDF Strings – Automatically Replace Underscore with \textunderscore in PDF Strings Using \pdfstringdefDisableCommands

bookmarkshyperref

Is it possible to mimic the output of

\section{\texorpdfstring{$x_1$}{x\_1}}

using \section{$x_1$} and \pdfstringdefDisableCommands{...} ? I've only seen this answer, which tries to do something similar, but it doesn't work (as they acknowledge). I'm not too concerned about warnings; I just want x_1 to appear in the bookmarks for the PDF, while not having \texorpdfstring{...}{...} for every instance of an underline.


MWE for the error generated by tikz when using @StevenB.Segletes's first solution:

\documentclass{article}
\usepackage{hyperref}

%\usepackage{tikz} % OK

\let\svus_
\catcode`\_=\active
\gdef_{\texorpdfstring{\svus}{\string_}}

%%%    
% pgfmathparser.code.tex
% ! Missing \endcsname inserted.
% <to be read again> 
%                    \svus 
% l.251 ...mnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ}
% \usepackage{tikz}    
%%%

\begin{document}
\tableofcontents

\section{$x_1$}

Document math, $a^3_1$ should be no problem

\section{$y_1$}

Does This\_work?

\end{document}

Best Answer

Recall that hyperref warns you about the subscript character with something like

Package hyperref Warning: Token not allowed in a PDF string (Unicode):
(hyperref)                removing `subscript' on input line 33.  

So clearly hyperref knows that it encounters a subscript character. All you need to do is to tell hyperref that, the next time you see _, instead of a warning, you put that character into the pdf toc.

The following code does that.

\documentclass{article}

\usepackage{tikz}

\usepackage{hyperref}

\makeatletter
\def\subscripttext{subscript}
\def\HyPsd@CatcodeWarning#1{%
  \def\argone{#1}
  \ifx\subscripttext\argone
    \expandafter\def\expandafter\HyPsd@String\expandafter{\HyPsd@String_}%
  \else
    \HyPsd@Warning{%
      Token not allowed in a PDF string (%
      \ifHy@unicode
        Unicode%
      \else
        PDFDocEncoding%
      \fi
      ):%
      \MessageBreak removing `\HyPsd@RemoveCmdPrefix#1'%
    }%
  \fi
}

\begin{document}

\tableofcontents

\section{$x_1$}
    Document math, $a^3_1$ should be no problem
\section{$y_1$}
    Does This\_work?

\end{document}

This approach allows you to not setting the catcode of _. There are only this many special characters and a bunch of packages are competing with each other for a chance to define the activated characters. TikZ, as you noticed, is an expert in that sort.

Related Question