# How can I prepend code to the \tableofcontents command using etoolbox?

This started by the need to have a table of contents entry in my PDF bookmarks. After accomplishing that, I decided that I wanted to have it always appear bold (supported as of PDF 1.4).

I would like to use etoolbox to get this working:

\preto<hook>{<code>}
\pretocmd{<command>}{<code>}{<success>}{<failure>}
%    \preto\tableofcontents{% Something like this
%      \bookmarksetupnext{bold=true}
%      \pdfbookmark{\contentsname}{bkm\contentsname}
%    }


This way, everytime \tableofcontents is called, a bookmark will be created with bold formatting.

# Code

\documentclass{article}
\usepackage{fontspec}
\usepackage{hyperref}
\usepackage{bookmark}
\usepackage{etoolbox}

%    \preto\tableofcontents{% Something like this
%      \bookmarksetupnext{bold=true}
%      \pdfbookmark{\contentsname}{bkm\contentsname}
%    }

\begin{document}
\tableofcontents
\clearpage
\section{Ablutophobia}
\section{Ergophobia}
\section{Nomophobia}

\end{document}

• Side note: I recommend xpatch for this stuff. – Sean Allred Nov 9 '15 at 19:32
• The interfaces package also allows you to modify the appearance of the pdf bookmarks. – ArTourter Nov 9 '15 at 19:48

Your usage is correct. So, fundamentally you can do the following:

\documentclass{article}
\usepackage{hyperref,bookmark}
\usepackage{etoolbox}

\pretocmd\tableofcontents{%
\bookmarksetupnext{bold=true}%
\pdfbookmark{\contentsname}{bkm\contentsname}%
}{}{}

\begin{document}

\tableofcontents
\clearpage
\section{Ablutophobia}
\section{Ergophobia}
\section{Nomophobia}

\end{document}


You have to be cautious about the location of the mark. In the above example this doesn't seem like a problem, as the hyperlink from the bookmark lands where the Contents starts in the PDF. However, it may be that some "administration" is performed before placing Content, which could introduce a gap between the jump mark and the text placement.

Another approach - somewhat oldschool - would be to use

\let\oldtableofcontents\tableofcontents
\renewcommand{\tableofcontents}{%
\bookmarksetupnext{bold=true}%
\pdfbookmark{\contentsname}{bkm\contentsname}%
\oldtableofcontents
}


The above provides a similar \pretocmd interface, if you don't want to use etoolbox.

• Great! I was so close. I did not think about "administration" factors. If an example of where that happens should come to mind, please do share. – Jonathan Komar Nov 10 '15 at 6:39
• @macmadness86: Just add some regular text before \tableofcontents to see that the hyperlink jump might not be on point. – Werner Nov 10 '15 at 7:08