# LaTeX won't expand macros in \index

I have what, in some sense, seems like the opposite of a fragile macro problem.

I am working on building an index for a book. I have long index commands I want to re-use and/or easily change without changing them in every instance of the book. I want to use \def or \newcommand to create commands in the preamble and reuse them.

For example, in preamble, I'd like to put something like:

\newcommand{\oGravity}{Sir Isaac Newton!Gravity!As Occult Force}


This should create a 3-level index entry with "Sir Isaac Newton" on the top line, "Gravity" as a sub-entry, and "As Occult Force" as a sub-sub entry.

Then later anytime I want to have that entry show up, I could just type

\index{\oGravity


The problem is that when I actually do this the \oGravity is not being expanded, so in the .idx file it just shows up as \oGravity. It is only expanded later by makeindex so that I get "Sir Isaac Newton!Gravity!Occult Force" in the index itself rather than what is intended.

I also tried using \def instead of \newcommand in the hope that using the TeX primitive would make a different. No change. I also tried using a \protect before the command (though it seems to do the reverse of what I want). No help.

MWE below the index shows two entries. The one where the actual string is used generates expected behavior. The other does not.

\documentclass[openright, onecolumn, 11pt]{memoir}
\immediate\write18{makeindex MWE}
\makeindex
\def\oGravity{Sir Isaac Newton!Gravity!As Occult Force}
\checkandfixthelayout
\begin{document}
Page 1 Gravity
\index{\oGravity}
\vfill\eject
Page 2 More gravity
\index{Sir Isaac Newton!Gravity!As Occult Force}
\printindex
\end{document}

• Indeed, \index tries hard not to expand macros in its argument; actually, it absorbs it (almost) verbatim. – egreg Jan 15 '18 at 0:21
• try \newcommand{\oGravity}{\index{Sir Isaac Newton!Gravity!As Occult Force}} to get the two parts at the same effective level. (of course, you'll have to remember that \oGravity already includes the \index component. – barbara beeton Jan 15 '18 at 2:59
• @barbarabeeton thanks for the suggestion. That worked. Feel free to enter as an answer so I can select. – David R Jan 15 '18 at 19:15

since input with \index{...} is passed on essentially verbatim, what you can do is define your macro to include the \index component:
\newcommand{\oGravity}{\index{Sir Isaac Newton!Gravity!As Occult Force}}

this will place the desired string in the .idx file. of course, you will have to remember that \index is already included, and not repeat that in the main text input. also, it could make finding index input in the file somewhat more difficult. on the other hand, it does have the advantage of consistency, the lack of which can be a definite nuisance when such elaborate entries are used.