# Why does adding hypertarget to TOC change pagination?

I'm trying to have links to lines in the table of contents, as suggested in, e.g., this question. It seems like the standard answer is to include lines like

\addtocontents{toc}{\protect\hypertarget{label}{}}


in the appropriate part of the document. This works great except that the table of contents doesn't seem willing to have page breaks between subsections that have this line between them, which leads to awkward spacing. I've posted an example below.

\documentclass[12pt,letterpaper]{article}

\begin{document}

x\vspace{5.5in}
\tableofcontents

\section{A}
\section{B}
\subsection{BA}

\subsection{Pagebreak should go below here}
% but it doesn't if this is uncommented

\subsection{BC}
\subsection{BD}
\section{C}

\end{document}


Why is this, and how can I specify that page breaks are OK?

-

The answer to your question Why does adding hypertarget to TOC change pagination? is that by adding \addtocontents{toc}{\protect\hypertarget{moo}{}} will add a new line in the .aux file with \@writefile{toc}{\hypertarget {moo}{}}. On the next compilation, an additional empty line with invisible hyper-target will appear in the PDF, which seems to us that the pagination changed.

To overcome this situation, we need to tweak \section, \subsection and what ever section commands which require navigation as given in the below example:

\documentclass[12pt,twoside]{article}
\usepackage{lipsum}

\makeatletter
\if@twoside
\else%
\fi%
\def\@oddfoot{\mbox{}\hfil\thepage\hfil\mbox{}}%
\let\@evenfoot\@oddfoot%
}
\section[\string\smash{\string\raisebox{\baselineskip}{\string\hypertarget{moo.\thesection}{}}}#1]{#1}%
\let\leftmark\rightmark%
}
\subsection[\string\smash{\string\raisebox{\baselineskip}{\string\hypertarget{moo.\thesubsection}{}}}#1]{#1}%
\let\leftmark\rightmark%
}
\section{#1}%
\let\leftmark\rightmark%
}
\subsection{#1}%
\let\leftmark\rightmark%
}
\makeatother

\begin{document}

\mbox{}\vspace{5.5in}
\tableofcontents

\lipsum

\lipsum

\lipsum

\nolinksubsection{Pagebreak should go below here}
\lipsum
% but it doesn't if this is un-commented

\lipsum

\lipsum


Defined a new pagestyle (header and footer) named myheading to put the navigation in headers which lead back to the ToC entry. Also, the commands \section, \subsection, etc changed to \linksection, \linksubsection respectively for those sections which required the navigation using hyper-linking. And those \section, \subsection which does not require navigation are defined as \nolinksection, \nolinksubsection respectively. These macros will define respective entries for \hypertarget in the ToC and \hyperlink in the headers.