# Correct sorting of \index entries containing macros

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?

-
Welcome to TeX.SX. I changed the formatting of your code to use backticks  instead and adjusted the title a little. At first I thought you use \def inside \index. –  Martin Scharrer May 16 '11 at 9:51

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


-
To trick with \expandafter does not work in my document. Maybe it's because I have a \textsc in the beginning of my \def ? –  bloub__ May 16 '11 at 10:42
What "does not work" exactly? Is the sorting order still incorrect, you mean? I would need to see the full code. Please add a minimal working example (MWE) that illustrates your problem. –  Martin Scharrer May 16 '11 at 10:47
\documentclass[]{article} \usepackage{xspace} \usepackage{index} \title{} \author{} \makeindex \def \px {{\textsc{Exact}\xspace}} \expandafter\index\px \begin{document} Blah \index{aaa} \index{\px} \index{zzz} \printindex \end{document} –  bloub__ May 16 '11 at 11:18
@bloub__: You need to write the index entry as text@\format{text} instead, i.e. Exact@\textsc{Exact}, to allow the index to be sorted correctly. I also wouldn't use \xspace for an index-only macro. –  Martin Scharrer May 16 '11 at 11:29
Thanks ! But unfortunately, there're not index-only macros -- I also use them in the text. I guess the simple way to solve my problem is to change every "classical" indexes by macros indexes ! –  bloub__ May 16 '11 at 11:32
\documentclass{article}
\usepackage{makeidx}\makeindex
\def\Index#1{#1\expandafter\index\expandafter{#1}}
\begin{document}

\index{classical}
\def\foo{BAR} and I use then \foo\index{\foo} (the wrong entry)\newpage
and \Index{\foo} (the correct entry).

\printindex
\end{document}


The first entry is wrong the second with \Index correct:

-
Thanks, but unfortunately, the index calls are done in a \newcommand, so I cannot make a difference between a classical one and a \def one. –  bloub__ May 16 '11 at 10:47
\Index{foo} is the same as foo\expandafter\index\expandafter{foo}` –  Herbert May 16 '11 at 10:51