Hyperlinks in the table of contents (TOC) are generated by the \contentsline
command defined in hyperref.sty
. The linktoc=all
option setting makes \contentsline
add separate links to the title and page number. A third link can be applied to the leader between the title and page number by patching the appropriate leader-generating command locally using etoolbox
. Enclosing the whole TOC entry in a hyperlink would be much tidier, but this is a relatively difficult problem.
For TOCs formatted by latex
internals, the leader is generated by the command
\@dottedtocline
defined in latex.ltx
. The following patch simply encloses the leader in a hyperlink pointing to the current TOC entry's location, which is passed as the fourth argument to \contentsline
.
\documentclass{report}
\usepackage[linktoc=all]{hyperref}
\usepackage{etoolbox}
\makeatletter
\pretocmd{\contentsline}
{\patchcmd{\@dottedtocline}
{\leaders}
{\hyper@linkstart{link}{#4}\leaders}
{}
{}%
\patchcmd{\@dottedtocline}
{\hfill}
{\hfill\hyper@linkend}
{}
{}}
{}
{}
\makeatother
\begin{document}
\tableofcontents
\chapter{First Chapter} \pagebreak
\section{First Section} \pagebreak
\subsection{First Subsection}
\chapter{Second Chapter} \pagebreak
\section{Second Section} \pagebreak
\subsection{Second Subsection}
\end{document}
The result looks terrible with link borders, but not so bad with colorlinks=true
.
This patch is general enough to work with TOCs formatted via package-defined user commands so long as the leader is generated by \@dottedtocline
. KOMA-Script
's tocstyle
is one example of such a package - it redefines \@dottedtocline
.
tocloft
and memoir
issue the command \cftdotfill
instead of \@dottedtocline
. The code below demonstrates a patch that will work for both the tocloft
package and the memoir
document class.
\documentclass{memoir}
\usepackage[linktoc=all]{hyperref}
\usepackage{etoolbox}
\makeatletter
\pretocmd{\contentsline}
{\patchcmd{\cftdotfill}
{\leaders}
{\hyper@linkstart{link}{#4}\leaders}
{}
{}%
\patchcmd{\cftdotfill}
{\hfill}
{\hfill\hyper@linkend}
{}
{}}
{}
{}
\makeatother
\setcounter{tocdepth}{2}
\renewcommand*{\cftdot}{\ensuremath{\ast}}
\renewcommand*{\cftsectionfont}{\itshape}
\renewcommand*{\cftsectionleader}{\cftdotfill{\cftsectiondotsep}}
\renewcommand*{\cftsubsectionfont}{\scshape}
\renewcommand*{\cftsubsectiondotsep}{9}
\renewcommand*{\cftsubsectionleader}{\cftdotfill{\cftsubsectiondotsep}}
\begin{document}
\tableofcontents
\chapter{First Chapter} \pagebreak
\section{First Section} \pagebreak
\subsection{First Subsection}
\chapter{Second Chapter} \pagebreak
\section{Second Section} \pagebreak
\subsection{Second Subsection}
\end{document}