Get reference to "current" section
Use \thechapter
, \thesection
, etc:
\documentclass{report}
\pagestyle{empty}
\begin{document}
\chapter{First}
\label{chap:first}
\section{First}
\label{sec:first}
This is the chapter number~\thechapter, section~\thesection.
\section{Second}
\label{sec:second}
This is the chapter number~\thechapter, section~\thesection.
\end{document}
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
.
There's no notion of "current" level, unless one plugs in one into the sectioning commands. The best one can do is to see if the related counter is zero or not:
\newcommand{\getcurrentref}[1]{%
\ifnum\value{#1}=0 ??\else\csname the#1\endcsname\fi
}
No packages. This is actually the same as Ryan's answer, but reduced to the essential.