8

Is there a command that expands to the current section name (which I can then use with \index{})?

This is similar to Name of current section/figure, but I like to get the name of the section instead of the current type, also \nameref{} doesn't work when using index. I tried

\label{sec:foo} \index{\nameref{sec:foo}}

which will show the current section name in Index, but it's out of order with the other non-\nameref{} Index entries. I believe that's because they are hyperlinked.

  • 1
    Dirty hack: add \let\oldsection\section, \def\section#1#{\sectionii{#1}}\def\sectionii#1#2{\def\currsecname{#2}\oldsection#1{#2}} to your preamble; then in each section \currsecname holds the name of the current section. – Bruno Le Floch Feb 13 '12 at 13:06
  • @Bruno: did not work for me :( Undefinied control sequenz – Megachip Nov 22 '12 at 21:32
  • @Megachip Which control sequence is undefined? Maybe you have a typo? – Bruno Le Floch Nov 23 '12 at 20:29
4
\documentclass[a4paper]{article}
\usepackage{makeidx}
\usepackage{nameref}
\usepackage{hyperref}
\makeindex

\newcommand{\indexref}[1]{%
  \sbox0{\nameref{#1}}%
  \expandafter\index\expandafter{\GetTitleStringResult}}

\begin{document}
\section{A section}\label{x}\indexref{x}
\end{document}

According to the documentation of nameref.sty, the title to which \label{x} refers is stored in the macro \GetTitleStringResult (globally). So we emit \nameref{x} in a box just to get the title and expand the macro containing the title before applying \index.

|improve this answer|||||
  • 1
    Thanks a log egreg, this does work! But there is now way to get the current section name from a command, so that I could avoid the detour with \label{} and \nameref{}? – Flow Feb 13 '12 at 13:46
  • You might redefine \section, but it's tedious; this has the merit to work with any sectional level. – egreg Feb 13 '12 at 13:53
  • You should be able to define \newcommand\labelandindex[1]{\label{#1}\indexref{#1} to at least avoid writing everything twice, shouldn't you? – yo' Nov 21 '13 at 8:00

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.