This is a modified version of the code from https://tex.stackexchange.com/a/388510/103046.
I used the very powerful zref
package and defined new label properties named shorttitle
, marktitle
and longtitle
which use the short section title, the chapter mark title or the long title after \refstepcounter
and \label
is applied.
The \chaptermark
macro is changed slightly in order to define \@currentmarktitle
which is expanded and stored with \zlabel
at its usage.
The macros \shortnameref
, \longnameref
and \middlenameref
check first whether the label is defined and if this is true, add the hyperlink automatically.
\documentclass[11pt]{book}
\usepackage{xpatch}
\usepackage[user,hyperref]{zref}
\makeatletter
% Empty dummy macros
\providecommand{\@currentshorttitle}{}
\providecommand{\@currentlongtitle}{}
\providecommand{\@currentmarktitle}{}
\zref@newprop{shorttitle}{\@currentshorttitle}
\zref@newprop{longtitle}{\@currentlongtitle}
\zref@newprop{marktitle}{\@currentmarktitle}
\zref@addprops{main}{shorttitle,longtitle,marktitle}
\NewDocumentCommand{\shortnameref}{m}{%
\zref@ifrefundefined{#1}{%
}{%
\hyperlink{\zref@extract{#1}{anchor}}{\zref@extract{#1}{shorttitle}}%
}%
}
\NewDocumentCommand{\longnameref}{m}{%
\zref@ifrefundefined{#1}{%
}{%
\hyperlink{\zref@extract{#1}{anchor}}{\zref@extract{#1}{longtitle}}%
}%
}
\NewDocumentCommand{\middlenameref}{m}{%
\zref@ifrefundefined{#1}{%
}{%
\hyperlink{\zref@extract{#1}{anchor}}{\zref@extract{#1}{marktitle}}%
}%
}
\xpretocmd{\chaptermark}{\def\@currentmarktitle{#1}}{}{}% Let \chaptermark define \@currentmarktitle{}
\xpatchcmd{\@chapter}{%
\refstepcounter{chapter}%
}{%
\def\@currentshorttitle{#1}%
\def\@currentlongtitle{#2}%
\refstepcounter{chapter}%
}{\typeout{Success}}{}
\xpatchcmd{\@sect}{%
\refstepcounter{#1}%
}{%
\def\@currentmarktitle{}%
\def\@currentshorttitle{#7}%
\def\@currentlongtitle{#8}%
\refstepcounter{#1}%
}{\typeout{Success again}}{}
\usepackage{hyperref} % Extensive support for hypertext in LaTeX
\AtBeginDocument{
\let\latex@@label\label
\RenewDocumentCommand{\label}{m}{%
\latex@@label{#1}%
\zlabel{#1}%
}
}
\makeatother
\begin{document}
\chapter[My moderately long chapter title]{My very long, rich and complex chapter title}
\chaptermark{My short chapter title}
\label{chapter_title}
Some text.
\section[My moderately long section title]{My very long, rich and complex section title}
\label{section_title}
\subsection[My moderately long subsection title]{My very long, rich and complex subsection title} \label{subsection_title}
Some text.
\clearpage
\tiny
\renewcommand{\arraystretch}{1.5}
\begin{tabular}{llll}
chapter & \longnameref{chapter_title} & \shortnameref{chapter_title} & \middlenameref{chapter_title}\tabularnewline
section & \longnameref{section_title} & \shortnameref{section_title} & \tabularnewline
subsection & \longnameref{subsection_title} & \shortnameref{subsection_title} & \tabularnewline
\end{tabular}
\end{document}
