# Get current “section” name without label that works in captions

My question basically the same as in question Get current “section” name without label. However I also need that this command also works in captions (which none of the linked solutions do).

I tries all three variants presented in this solution:

• nameref -> does not work at all (compile error)
• titleref -> does compile but the result is wrong
• zref-titleref -> does compile but the result is wrong (exactly like with titleref)

My adapted example looks as follows:

\documentclass{article}

\usepackage{titleref}
\makeatletter
\newcommand*{\currentname}{\TR@currentTitle}
\makeatother

\begin{document}

\section{My section name}
The name of the current section is: "\currentname{}".\\
It should be: "My section name".

\subsection{My subsection name}
The name of the current subsection is: "\currentname{}".\\
It should be: "My subsection name".

\begin{figure}
\caption{AAA "\currentname{}" BBB}
FIGURE
\end{figure}

\end{document}


The expected output for the figure caption was

AAA "My subsection name" BBB. However it is

AAA "AAA "My subsection name" BBB" BBB.

Is there anything I can do to make \currentname{} work also in captions?

The titleref package redefines the \caption command to also save its contents to \TR@currentTitle. That's why you get a repetition in your output.

You can deactivate the effect of titleref on \caption by doing:

\makeatletter
\AtBeginDocument{\let\@caption\TR@old@caption}
\makeatother


Complete code:

\documentclass{article}

\usepackage{titleref}
\makeatletter
\newcommand*{\currentname}{\TR@currentTitle}
\AtBeginDocument{\let\@caption\TR@old@caption}
\makeatother

\begin{document}

\section{My section name}
The name of the current section is: "\currentname{}".\\
It should be: "My section name".

\subsection{My subsection name}
The name of the current subsection is: "\currentname{}".\\
It should be: "My subsection name".

\begin{figure}
\caption{AAA "\currentname{}" BBB}
\end{figure}

\end{document}