# Dynamically determine label of current chapter

Some pseudo-code to illustrate the problem:

\chapter{Another day in paradise}
...
\section{The snake appears}
\label{snake}
...
\somemacro % a macro that wants to know the chapter label


In the definition of \somemacro, is it possible in some way to obtain the string used to \label the current chapter (paradise in this example)?

• @ChristianHupfer - sequence of characters. The word is commonly used in other programming languages, but maybe not in TeX/LaTeX. Should I say token instead? – Michael Palmer Jan 3 '18 at 17:28
• I know what a string is (I've programmed a lot ;-))... Which string do you mean? – user31729 Jan 3 '18 at 17:29
• I mean the string paradise. – Michael Palmer Jan 3 '18 at 17:29
• How should LaTeX know which chapter or section you mean? There's no default way to achieve this – user31729 Jan 3 '18 at 17:31
• When do you use \somemacro? Do you plan to do any \refstepcounter in between? – TeXnician Jan 3 '18 at 17:34

A simple and robust approach is to define a macro that sets the label and remembers the name of the label, e.g.:

\newcommand*{\CurrentChapterLabelName}{}
\newcommand*{\ChapterLabel}[1]{%
\renewcommand*{\CurrentChapterLabelName}{#1}%
\label{#1}%
}


Then, macro \CurrentChapterLabelName contains the last label name set by \ChapterLabel:

\chapter{My chapter title}
\ChapterLabel{MyChapterLabel}

... \section{My section title}\label{MySectionLabel} ...

\SomeMacro can now use \CurrentChapterLabelName;
the latter macro contains 'MyChapterLabel'.


Also, \chapter and \label could be merged to one macro with parameters for the chapter title, the label name and maybe the shorter title for the table of contents.

This solution works with lots of packages, because internal commands are not hacked.

• Thank you. Your point about compatibility is well taken. – Michael Palmer Jan 3 '18 at 18:09