[Tex/LaTex] Cross-reference to the next section, whatever it is

cross-referencingnumberingsectioning

Some sections of my document start with a remark such as the following: "This section may be omitted at the first reading."

I'd like to add to this text a (hypertext) reference to the next section (page) number and I can do it by labeling the next section (\label{sec:next}) and make use of \ref{sec:next} and/or \pageref{sec:next}. But, because the sec:next label is hard coded, the reference could be wrong in case of changes in the order of the sections.

Hence my question: is there a way to refer to the next section, whatever it is?

Best Answer

We have to setup a \label that will be evaluated at the next \section command.

So I patch \@sect to add a \label command to its argument #8 (which refers to the main section title), which is evaluated only if the command has been called by \section and a \nextsection command has been issued. Also \section and \subsection need to be patched, because they both use \@sect for typesetting the title. The argument to \label is automatically generated via a counter.

Note that the patches must be made before hyperref is loaded.

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newif\if@nextsection
\newif\if@section
\newcounter{ns@count}
\newcommand{\nextsection}{%
  \global\@nextsectiontrue
  \stepcounter{ns@count}%
  \xdef\@nstemp{ns@@\thens@count}%
  \ref{ns@@\@nstemp}%
}

\patchcmd{\@sect}
  {#8}
  {#8%
   \if@section\if@nextsection
     \label{ns@@\@nstemp}\global\@nextsectionfalse
   \fi\fi}
  {}{}
\preto\section{\global\@sectiontrue}
\preto\subsection{\global\@sectionfalse}
\makeatother

%%% hyperref should go after the patch, if used
\usepackage{hyperref}


\begin{document}
\section{TL;DR}

This section is long, go to section~\nextsection.

\subsection{A}

\newpage

\section{THIS IS IT}\label{foo}

\newpage

\section{Again TL;DR}
Check if it works \ref{foo}; now go to section~\nextsection.

\newpage

\section{Another}
\end{document}