2

I am using the theorem environment to arrange equations. I am assigning a distinct label for each equation. Some equations, e.g. \label{equation-a} and \label{equation-b}, are under the same theorem environment:

\begin{theorem}[Algebra-Basic] For any natural numbers a, b and c
\begin{IEEEeqnarray}{c}
a + b = b + a \label{equation-a}\\
a + (b + c) = (a + b) + c\label{equation-b}
\end{IEEEeqnarray}
\end{theorem}

I would like to add equation-a and equation-b to the index. But these should collapsed under the same entry because \nameref{...} expands both to the same string. The problem is that the expansion does not occur before generating the index, and I end up with duplicates in my list of indexes. Is it possible to make latex to expand \nameref{} before generating the index?

3

I've found these two snippets that can be defined in the preamble of a document in order to force the expansion of \nameref{} prior to the generation of an index.

I've haven't fully understood the details behind these snippets, but it seems that when a label is added to latex, its details (pagenumber, title, hyperlink, etc.) are saved as a tuple of five components. The name is the third in this tuple, and is extracted using some primitives of TEX. The key difference between \nameref{} and \getnamereftex{} is that the can be expanded before generate an index, while \nameref{} cannot.

\makeatletter
\newcommand{\getnamereftext}[1]{%
  \@ifundefined{r@#1}{}{%
    \unexpanded\expandafter\expandafter\expandafter{%
      \expandafter\expandafter\expandafter\@thirdoffive\csname r@#1\endcsname
    }%
  }%
}

Snippet above taken from: How to use \nameref with xstring package to check string length

Now, to force the expansion of \getnamereftext prior the generation of the index, the next command is defined.

\newcommand{\indexref}[2]{%
  \sbox0{{\nameref{#2}}}%
  \expandafter\index{#1!{\getnamereftext{#2}}}}

Snippet taken from: Is there a command that expands to the current section name?

Then, to add entries to the index, the user uses the command \indexref, e.g. \nameref{Definition}{Code}. This solution takes care properly of multiple labels that are expanded to the same text via \nameref{}. So, rather than latex order the index based on the name of the label, it orders based on the content of the label. Moreover, if multiple labels on a page expand to the same text, then only one entry is added to the index.

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.