Using an \index format which changes based on section of the document

imakeidxindexingpage-numbering

I am copying a long book with musical pieces throughout, set with gregorio tex. Each musical piece has a \label and is entered in one of several indexes created using imakeidx.

The document has multiple formats of page numbers: roman, arabic, and then several other notations, e.g. [3], 7*, and <<22>>, based on different divisions of the overall document. Each section starts with a value of 1, but formatted differently.

I'd like \label/\pageref and \index to function seamlessly to give the right page with the right format based on the location of the chant.

I have previously posted about this problem here: More than two page formats for \label / \ref and \index with imakeidx

I was given the tip by David Carlisle that I can use \index{item|foo} to apply a format to the index page using a function \foo that I define. This is definitely on the way to solving the problem.

The problem is that there is basically one \index statement in the program – buried in a function \dostuff called by the gregorio tex package when a musical piece is loaded.

So I have an existing function

\newcommand{dostuff}{......
...
\index{item|foo}
...
}

I'd like to change the format of the index by redefining \foo at the start of each section in the document where the page number format changes, such as

% Switch to star pages now....
\renewcommand{\foo}[1]{#1*}

Instead, when I do this, the index only uses the most recent definition of foo at the time the \printindex executes, so every page number gets displayed in the same format, in this case, e.g. [7].

Is there a way to fix the definition of \foo or the \index command to get the page reference to get written to the index file at the time the index statement is given, so to use the 'current' definition of \foo and thus make sure the right format is applied?

I could redefine all of the macro \dostuff at the start of each document division, but it is a long macro and that would be a pain. If it is possible, just changing \foo would be a lot simpler, since that's all that changes.

Best Answer

This question was a follow-on question, as noted in the post. The answer was posted in the original question thread, linked in the top post here, but I repeat it for completeness.

The above solution in the comments thanks to David Carlisle solves the problem. In my function, I define

\bigfunction{
...
\index{item|foo}
...
}

where foo is defined, e.g.

\newcommand{foo}[1]{#1*}

to get starred page numbers, and similarly for other formats.

I have to then redefine the function \bigfunction at the beginning of each section to get different versions of foo for each section.