[Tex/LaTex] Get reference to “current” section

cross-referencingmacros

I'd like to write a command to get a reference to the "current" section provided (the term is all wrong, but the example will clarify).

The idea is something along the lines of:

\getcurrentref{chapter}

or

\getcurrentref{subsubsection}

and so on.

A section is considered "current" at a given point if said point is within the "scope" of said section.

Example:

\chapter{A}
  % point (1)
  \section{A.A}
    % point (2)
  \section{A.B}
    % point (3)
    \subsection{A.B.A}
      % point (4)

the only "living" section at point (1) is chapter, the only "living" sections at points (2) and (3) are chapter and section, and the only "living" sections at point (4) are chapter, section and subsection.

I hope I could explain myself (it's tricky).

PS: in case of trying to get the reference to a non-"living" section, the command should return ?? (this is just to have a standard graceful way of saying "no such section alive").

Best Answer

Assuming that subordinate "sections" are reset to 0 by larger ones (so \chapter resets \section and so on), you just have to look at the counters chapter, section, etc., and check whether they're nonzero:

\documentclass{book} % For {chapter}
\usepackage{etoolbox}

\newcommand\getcurrentref[1]{%
 \ifnumequal{\value{#1}}{0}
  {??}
  {\the\value{#1}}%
}    
\begin{document}
 Chapter: \getcurrentref{chapter}

 \chapter{I}
 \tracingmacros=1\tracingonline=1
 Chapter: \getcurrentref{chapter}\\
 \tracingmacros=0
 Section: \getcurrentref{section}

 \section{i}
 Chapter: \getcurrentref{chapter}\\
 Section: \getcurrentref{section}\\
 Subsection: \getcurrentref{subsection}

 \section{ii}
 Section: \getcurrentref{section}

 \subsection{a}
 Subsection: \getcurrentref{subsection}
\end{document}

This should be expandable, by the way. I only use etoolbox for the handy conditional, which in a more complicated situation might be simpler than a TeX primitive (e.g. with respect to nesting or expansion order). Here, it's optional.

Edit: I now use \value{#1} rather than \csname c@#1\endcsname for the number, as one would like. As egreg says, it is expandable (actually, it expands just to this). However, it does expand rather unpredictably in the sense that it is equivalent to a count register, not to an actual number, and so the part of the macro that actually prints the value needs a \the to avoid weird errors. In my case, I was seeing "Missing number inserted" in the expansion of \\, which (upon tracing) appeared to be related to \protect.