[Tex/LaTex] Automatically insert “in the next [chapter/section/subsection]” if reference is sequential

cleverefcross-referencing

I'm aware of the cleveref package \cref which adds the correct reference name (see:
Automatically inserting "Section", "Subsection", etc). I have a few references which refer to the very next section and some find it odd to give the number in this case rather than just say "in the next section". Sometimes I've moved sections around and these references suddenly become quite broken. To have the best of both worlds, is there a way to automate this change?

E.g.: replace "this is discussed further in section 1.4" with "this is discussed further in the next section"

Best Answer

Here is a solution based on cleveref package. If the hyperref package is loaded, the word "section" (or chapter/subsection/...) is a clickable hyperlink.

\documentclass{article}

%\usepackage{hyperref}
\usepackage{cleveref}
\crefname{subsection}{subsection}{subsections}

\providecommand\hyperref[2][]{#2}

\makeatletter
\newcommand{\mt@ref}[1]{%
\cref@gettype{#1}{\@temptype}%
\cref@getcounter{#1}{\@tempctr}%
\def\mtt{\the\csname c@\@temptype\endcsname}%
\ifnum\mtt=\numexpr\@tempctr-1\relax \mtcase the next \hyperref[#1]{\@temptype}\else%
\ifnum\mtt=\numexpr\@tempctr+1\relax \mtcase the previous \hyperref[#1]{\@temptype}\else%
\cref{#1}\fi\fi}

\newcommand{\mtref}{\let\mtcase\relax\mt@ref}
\newcommand{\Mtref}{\let\mtcase\MakeUppercase\mt@ref}
\makeatother


\begin{document}
\section{Foo}\label{sec:foo}
this is \Mtref{sec:bar} and this is \mtref{sec:baz}
\subsection{Sub foo}\label{ss:sfoo}
this is \mtref{sec:baz} and this is \mtref{sec:bar}
and \mtref{ss:sfbla} and \mtref{ss:sfbaz}
\subsection{Bla foo}\label{ss:sfbla}
bla bla bla
\subsection{Bar foo}\label{ss:sfbar}
bla bla bla
\subsection{Baz foo}\label{ss:sfbaz}
bla bla bla
\section{Bar}\label{sec:bar}
bla bla bla
\section{Baz}\label{sec:baz}
bla bla bla

\end{document}

The result looks approximately like this (compiled with a previous version of the code):

Result of compilation

Related Question