5

I have code for creating an index that refers readers to a page number and an example number. (The code is included in this answer, reproduced below for convenience. I happen to be using expex, but it could just as well be an equation number, for example.) I would like to use hyperref to generate links to the specific example, rather than just the page. Is there a way to do this? I am using xindy as an index processor.

\documentclass{book}
\usepackage{expex,lipsum,index}
\newcommand{\PageExample}{\thepage-\the\excnt}
\newindex[PageExample]{my-index}{idx}{ind}{My Custom Index}
\makeindex
\begin{document}
\ex \lipsum[1]\index[my-index]{First example} \xe

\ex \lipsum[2] \index[my-index]{Second example}\xe

\ex \lipsum[3] \index[my-index]{Third example}\xe

\ex \lipsum[4] \index[my-index]{Fourth example}\xe

\ex \lipsum[5] \index[my-index]{Fifth example}\xe

\ex \lipsum[6] \index[my-index]{Sixth example}\xe

\ex \lipsum[6] \index[my-index]{Seventh example}\xe

\printindex[my-index]
\end{document}
  • Did you see this answer? – jon Apr 23 '15 at 4:38
  • Thank you, that is just what I needed -- that page, and some thinking about macro expansion! I've added my solution in an answer. – adam.baker Apr 23 '15 at 11:09
2

Here is the solution, based on this answer.

\documentclass{book}
\usepackage{expex,lipsum,index}
\newindex[PageExample]{my-index}{idx}{ind}{My Custom Index}
\usepackage[hyperindex=false]{hyperref} % has to be after makeidx
\newcommand{\PageExample}{\thepage-\the\excnt}
\makeindex

\def\xindex#1#2{%
  \edef\doindexentry{\noexpand\index[#1]
    {#2|indexanchor{example:\the\excnt}}}%
    \doindexentry}

\def\indexanchor#1#2{\hyperlink{#1}{#2}}

\begin{document}

\xindex{my-index}{First example}
\ex 
    \raisebox{\baselineskip}{\hypertarget{example:\the\excnt}{}}\ignorespaces%
    \lipsum[1] 
\xe

% now make the code prettier:
\def\iex#1{%
    \xindex{my-index}{#1}%
    \ex %
    \raisebox{\baselineskip}{\hypertarget{example:\the\excnt}{}}\ignorespaces}

\iex{Second example} \lipsum[2] \xe

\iex{Third example} \lipsum[3] \xe

\iex{Fourth example} \lipsum[4] \xe

\iex{Fifth example} \lipsum[5] \xe

\iex{Sixth example} \lipsum[6] \xe

\iex{Seventh example} \lipsum[7] \xe

\printindex[my-index]
\end{document}

There are two "tricks" to it. The first is that the a macro that creates a hyperlink is passed to \index as if it were a formatting command (e.g., \index{Joe|indexanchor} instead of \index{Joe|textit}).

The second trick is to use \edef to expand all of the needed macros before then calling it to call the \index macro. If \xindex had a call to \index outside of \edef, then it would write something like this to the .idx file: \indexentry {First example|indexanchor{example: \the \excnt}}{1-1}.

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.