# Xindy and custom Hyperref index entries

My goal is to have index entries that provide hyperlinks to specific examples on a page, using xindy. This follows from an earlier question; that question has code that works with makeindex. It creates an .idx file with entries like this:

\indexentry {First example|indexanchor{example:2}}{1(2)}
\indexentry {Second example|indexanchor{example:3}}{1(3)}
\indexentry {Third example|indexanchor{example:4}}{1(4)}


Running such an .idx file through xindy produces errors like this, as xindy interprets the input as cross-references:

WARNING: unknown cross-reference-class indexanchor'! (ignored)


How can xindy process these files?

The solution I came up with is to teach xindy to recognize hyperlink commands as types of page references. (The code that follows doesn't able page range references, but I simply didn't include that because it's irrelevant to my application.)

The code generates an .idx file like this, with the hyperlink command included as part of the page reference. (\indexanchor is defined below; the " marks are just escapes for {.

\indexentry{First example}{\indexanchor{example:1"}{1(1)"}}
\indexentry{Second example}{\indexanchor{example:2"}{1(2)"}}
\indexentry{Third example}{\indexanchor{example:3"}{1(3)"}}


xindy just needs to be told what these page ranges look like. This is xindy-hyperref.xdy:

(define-location-class "page-example-hyperref" ( :sep "\indexanchor{example:" "arabic-numbers" :sep "}{" "arabic-numbers" :sep "(" "arabic-numbers" :sep ")}" ))


To produce the .idx in the proper format, I needed to create my own output structure. (I would be interested if anyone had a more elegant way to redefine a macro from an indexing package. When it came to it I was surprised at how simple it was to write my own indexing code.) xindy-hyperref.tex:

\documentclass{book}
\usepackage{expex,hyperref,lipsum}
% open the index file
\newwrite\outputstream
\immediate\openout\outputstream=xindy-hyperref.idx
% Index references like 2(3)
\newcommand{\PageExample}{\thepage (\the\excnt)}
% Write the index entries to a file
\def\xindex#1#2#3{%
\immediate\write#3{\string\indexentry {#2}{\string\indexanchor{example:\the\excnt"}{\PageExample"}}}
}
% clean output
\def\iex#1{%
\xindex{my-index}{#1}{\outputstream}%
\ex %
\raisebox{\baselineskip}{\hypertarget{example:\the\excnt}{}}\ignorespaces}

\begin{document}
\iex{First example} \lipsum[1] \xe

\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

\InputIfFileExists{xindy-hyperref.ind}{}{}

\end{document}


To compile the example:

xelatex xindy-hyperref.tex
texindy -L english xindy-hyperref.idx -o xindy-hyperref.ind -M xindy-hyperref
xelatex xindy-hyperref.tex
`