Inclusion of hash marks in a LaTeX \indexentry aliased with a \newcommand

1.6k Views Asked by At

This is a strange one. I've had to do some interesting workarounds to get it to function even a little bit, but we have another stumbling block.

I've been struggling to create a separate document which employs a large .ind file (index created using makeindex from catenated, small individual .idx files), the idea being that I will eventually have a single document which indicates the SUB-documents and page numbers where the indexed data occurs.

To this end, I've had to define a command which collects all index entries as:

\newcommand{\myindexer}[3]
    {\index{myindex}{#1 : #2.#3!\href{\doctitle.pdf}}}

The result is index entries in the myindex.idx file as:

\indexentry{IndexedItemA : 55.iii!\href{Volume 1.pdf}{Volume 1.pdf}}{30}}
\indexentry{IndexedItemB : 23.vi!\href{Volume 3.pdf}{Volume 3.pdf}}{114}}

Yet, the problem exists in trying to create a hyperref to the target PDF. In order to open a PDF at a specific page, the following format needs to be employed (thanks to someone else on this board for pointing out the #page.xx syntax in the hyperref package):

\href{FILENAME#page.XX}{Link Text}

wihch means that a hash mark needs to be included in the output stream of the \newcommand when myindex is declared, possibly using an escaped hash mark # as:

\newcommand{\myindexer}[3]
    {\index{myindex}{#1 : #2.#3!\href{\doctitle.pdf\#page.\thepage}}}

or according to some fragment I found somewhere using a double-hash mark as:

\newcommand{\myindexer}[3]
    {\index{myindex}{#1 : #2.#3!\href{\doctitle.pdf##page.\thepage}}}

The former results in the following error during compilation of the latex source for the multiple documents being indexed:

! Illegal parameter number in definition of \@gtempa.
<to be read again>
                   \thepage
l.31 \myindex{IndexedItemA}{55}{iii}

While the latter results in an unwanted backslash in the resulting myindex.idx file as:

\indexentry{IndexedItemA : 55.iii!\href  {Volume 1.pdf\#page.33}{Volume 1}}{33}

which results in the target PDF not opening correctly.

Any idea how the newcommand can be forced to output the hash mark to support hyperlinking of PDFs in this way?

2

There are 2 best solutions below

1
On

What about wrapping the \href in \protect?

0
On

You can swap the catcode of # and %:

\catcode`\%=6 \catcode`\#=12

Then use % to mark parameters:

\newcommand{\myindexer}[3]
    {\index{myindex}{%1 : %2.%3!\href{\doctitle.pdf#page.\thepage}}}

After that, restore the usual catcodes:

\catcode`\%=12 \catcode`\#=6

This is kind of clumsy, but it should work even if something interferes with usual escaping mechanisms, and it allows \href to be exanded at the point \myindexer is used.