Cross-reference to the next section, whatever it is
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}
This answer has been EDITED to work for the next section, the next subsection, as well as the next subsubsection.
In essence, rather that try to invoke a label in one place meant to apply to a subsequent report section, it makes more sense to me to create macros \nextsection
, \nextsubsection
, and \nextsubsubsection
in which the next [[sub]sub]section number is computed based on the current [[sub]sub]section number. It will, however, require you to know in advance whether the next sectioning unit entity is a section, a subsection, or a subsubsection.
\documentclass{article}
\newcounter{nextsec}
\newcommand\nextsection{%
\setcounter{nextsec}{\thesection}%
\stepcounter{nextsec}%
\thenextsec%
}
\newcommand\nextsubsection{%
\setcounter{nextsec}{\expandafter\parsesub\thesubsection\relax}%
\stepcounter{nextsec}%
\thesection.\thenextsec%
}
\newcommand\nextsubsubsection{%
\edef\tmp{\thesubsubsection}%
\setcounter{nextsec}{\expandafter\parsesubsub\tmp\relax}%
\stepcounter{nextsec}%
\thesubsection.\thenextsec%
}
\def\parsesub#1.#2\relax{#2}
\def\parsesubsub#1.#2.#3\relax{#3}
\begin{document}
\section{First Section\label{s:first}}
This is section \ref{s:first}. The following section is \nextsection,\\
but the next subsection is \nextsubsection.
\subsection{A subsection\label{s:firstsub}}
This is subsection \ref{s:firstsub}. The following subsection is \nextsubsection.
\subsection{Next subsection}
\section{Next Section}
The next subsubsection will be \nextsubsubsection.
\end{document}