5

Some pseudo-code to illustrate the problem:

\chapter{Another day in paradise}
\label{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)?

  • 1
    @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
  • 1
    I know what a string is (I've programmed a lot ;-))... Which string do you mean? – user31729 Jan 3 '18 at 17:29
  • 1
    I mean the string paradise. – Michael Palmer Jan 3 '18 at 17:29
  • 2
    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
  • 1
    When do you use \somemacro? Do you plan to do any \refstepcounter in between? – TeXnician Jan 3 '18 at 17:34
8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.