I inserted a number of cross-references to different parts of my book. Currently, I simply do so by calling a self-defined macro:
\newcommand\secref[1]{See \ref{#1}, \nameref{#1}.}
This will print a reference such as the following:
See § 3:III.C.2.a), History and Institutions
Thus, the reference to the number, printed by \ref
, includes chapter
number, section
number, subsection
number, subsubsection
number and paragraph
number. Note that I defined my own numbering scheme using alnumsec
.
What I want to achieve now is to make \secref
aware of its relative position with regards to the label that is being referenced. If the \secref
macro for the "History and Institutions" paragraph is called in chapter "§ 3", for instance, the \ref
or a replacement command should only print "III.C.2.a)". If the \secref
macro is called in chapter "§ 3", section "III", it should only print "C.2.a)", and so on.
But if the macro is called in, let's say, section "III" of chapter "§ 4", it should print "3: III.C.2.a)" In effect, I want to re-create a behaviour that can be found in Microsoft Word, where a cross-reference to a numbered paragraph will only print as much information as is necessary to make the reference unambiguous in the current context.
So unless a chapter
,section
,etc. number is provided, the reader can assume that the reference is a reference to different section
,subsection
,etc in the same chapter
,section
,etc.
Based on @JohnKormylo's comment below and his answer to this question, I have prepared a MWE that tries to achieve what I want by using a custom \secrefnumber
macro that parses the content of \getrefnumber
, but I am still stuck because compiling the MWE will result in an error "Missing { inserted." (As regards the approach in the MWE: I am aware that the \if\thechapter\temptask
will always yield a false because the \temptask
does not include the colon; I was going to get to that once the MWE is working).
\documentclass{book}
\usepackage{xstring}
\usepackage{alnumsec}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[hidelinks]{hyperref}
\addto\captionsenglish{%
\renewcommand\chaptername{}}
\alnumsectionlevels{1}{chapter,section}
\otherseparators{2}
\alnumsecstyle{aR}
\surroundarabic[][]{§ }{:}
\surroundRoman{}{.}
\makeatletter
\newcommand\secref[1]{\secrefnumber{#1}, \nameref{#1}.}
\newcommand{\secrefnumber}[1]{% #1 = label name for subtasks
\@ifundefined{r@#1}{??}{%
\begingroup%
\edef\temp{\expandafter\detokenize\getrefnumber{#1}}%
\StrCut{\temp}{:}\temptask\tempsub%
\edef\templink{\getrefbykeydefault{#1}{anchor}{}}%
\if\thechapter\temptask%
\hyperlink{\templink}{\tempsub)}%
\else%
\hyperlink{\templink}{\temptask\,\tempsub)}%
\fi
\endgroup%
}}
\makeatother
\begin{document}
\chapter{My Very First Chapter}
\section{Introduction}
\label{sec:introduction}
\section{Once Upon a Time}
I am referencing \secref{sec:introduction}
\chapter{The Second Chapter}
I am referencing \secref{sec:introduction} again.
\end{document}