6

I have a macro that contains the title for the current section, however when using the titlesec package, it no longer works for \section and \subsection. I know titlesec redefines the functions I'm using, but have not been able to figure out a workaround.

MWE:

\documentclass{article}

\usepackage{etoolbox}

\makeatletter
\pretocmd{\@sect}{\gdef\currtitle{#7}}{}{}
\pretocmd{\@ssect}{\gdef\currtitle{#5}}{}{}
\pretocmd{\@part}{\gdef\currtitle{#1}}{}{}
\pretocmd{\@spart}{\gdef\currtitle{#1}}{}{}
\makeatother

\usepackage{titlesec}

\begin{document}
\tableofcontents

\part*{First Starred part}
\currtitle

\part{First Un-starred part}
\currtitle

\section*{First Starred Section}
\currtitle

\section{Second Un-starred Section}
\currtitle

\subsection*{First Starred Subsection}
\currtitle

\subsection{Second Un-starred Subsection}
\currtitle

\end{document}
1

2 Answers 2

3

For \section and lower level titles you can do

\apptocmd{\ttl@straight@i}{\global\let\currtitle\ttl@savetitle}{}{}

However, if you're not going to hide titles in groups, the simple

\makeatletter
\newcommand{\currtitle}{\ttl@savetitle}
\makeatother

should suffice.

For \part your code still works and I believe also the similar one for \chapter.

In order to save only the current first level section title one can modify the code to

\documentclass{article}
\usepackage{titlesec}
\usepackage{etoolbox,pdftexcmds}

\makeatletter
\apptocmd{\ttl@straight@i}{\update@currsectitle{#1}}{}{}
\def\update@currsectitle#1{%
  \ifnum\pdf@strcmp{#1}{section}=0
    \global\let\currsectitle\ttl@savetitle
  \fi
}
\makeatother

\begin{document}

\section{Title of the first section}

\currsectitle

\subsection{A subsection}

\currsectitle

\section{Title of the second section}

\currsectitle

\end{document}
5
  • The first approach was exactly what I was looking for. Thanks!
    – mrtasktat
    Commented Nov 21, 2011 at 22:37
  • Could you please explain how to use these commands? An example would really help.
    – wkschwartz
    Commented Nov 9, 2015 at 17:46
  • How to get only section level and not the last sectioning command that occurred ? The problem with this command is that it may gives you the subsection or the paragraph title and not the section title. Maybe using \ifnum on ttll@.., but I did not succeeded with that yet.
    – perror
    Commented Jun 11, 2021 at 9:48
  • 1
    @perror I added the code
    – egreg
    Commented Jun 11, 2021 at 13:13
  • This is awesome, thanks a lot !!!
    – perror
    Commented Jun 11, 2021 at 13:53
0

Just to add on egrep's answer, here is the code needed to get chapter title:

\pretocmd{\ttl@mkchap@i}{\def\ttl@savetitle{#7}}{}{}
\apptocmd{\ttl@mkchap@i}{\global\let\currchaptitle\ttl@savetitle}{}{}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .