I looked up for a solution to access the name of current sections (chapters, sections, etc.) from macros (including starred variations of the section command). The set of macros proposed here works like a charm in the base class book
.
\documentclass{book}
\usepackage{etoolbox}
% Patch the sectioning commands to provide a hook to be used later
\preto{\chapter}{\def\leveltitle{\chaptertitle}}
\preto{\section}{\def\leveltitle{\sectiontitle}}
\preto{\subsection}{\def\leveltitle{\subsectiontitle}}
\preto{\subsubsection}{\def\leveltitle{\subsubsectiontitle}}
\makeatletter
\pretocmd{\@sect}
{\expandafter\gdef\leveltitle{#8}}
{}{}
\pretocmd{\@ssect}
{\expandafter\gdef\leveltitle{#5}}
{}{}
\pretocmd{\@chapter}
{\expandafter\gdef\leveltitle{#2}}
{}{}
\pretocmd{\@schapter}
{\expandafter\gdef\leveltitle{#1}}
{}{}
\makeatother
\newcommand\test{%
\noindent
The chapter title is \chaptertitle\\
The section title is \sectiontitle\\
The subsection title is \subsectiontitle\\
The subsubsection title is \subsubsectiontitle
}
\begin{document}
\chapter{First chapter}
\section{First section}
\subsection{First subsection}
\subsubsection{First subsubsection}
\test
\chapter*{Second chapter}
\section*{Second section}
\subsection*{Second subsection}
\subsubsection*{Second subsubsection}
\test
\end{document}
However I need to implement my macros in Koma-Script, with scrbook
and here things start to get unexpected. With the same code but with class scrbook
I get the following:
The chapter name is not rendered. I looked up the code of scrbook
and the title is indeed #2. Is there something wrong with the macros and how to fix this issue?
For my needs, it is not possible to use nameref
, I need a hard-coded solution. Thanks for you help.
Bonus: Is it possible to choose between long titles and short titles (the ones defined with \section[short]{long}
? Thanks again.