[Tex/LaTex] Correct sorting of \index entries containing macros

indexingmacrossorting

I use \index in classical way, but also with some macros as content. More precisely, I have some macros like \def\foo{BAR}, and I use then \index{\foo}.

Unfortunately, the index is then order by the name of the macro, not the content of the macro. It's quite embarrassing since all the macros are in the top of the list (due to the use of \).

Is there a way to change that?

Best Answer

If you expand the macro before \index reads it the sorting should be correct after the content. You can do this using \expandafter:

  \def\foo{BAR}
  % ...
  \expandafter\index\expandafter{\foo}

It is shorter if you put the { } inside the definition:

  \def\foo{{BAR}}
  % ...
  \expandafter\index\foo

For more complex content, i.e. with multiple macros you should expand the content fully using \edef (or maybe \protected@edef):

  \def\foo{BAR}
  \def\bar{FOO}
  % ...
  \edef\temp{\noexpand\index{\foo\bar}}
  \temp

If you want to keep the \temp definition local use:

  \begingroup
  \edef\temp{\endgroup\noexpand\index{\foo\bar}}
  \temp

instead.