# error when using expandafter for databib command in indexing command in foreach loop

I'm trying to create an author index using the databib package (datatool) bundle. I can loop over the entries in a BibTeX database and for each entry, loop over the authors using the \foreach command from the pgffor package. I then would like to add the author to the index, but this fails.

The following minimal example illustrates the issue:

\begin{filecontents}{data.bib}
@inproceedings{test,
Author = {Author One and Auteur Twee},
}
\end{filecontents}
\documentclass{article}
\usepackage{databib,pgffor}
\usepackage{imakeidx}
\makeindex[name=test]

\newcommand*{\invertfourargs}[4]{#4 #3 #2 #1}

\begin{document}
\invertfourargs{a}{b}{c}{d}

***

\def\multiplefourargs{{c}{d}{e}{f},{g}{h}{i}{j}}
\foreach \fourargs in \multiplefourargs {%
\expandafter\invertfourargs\fourargs+}
\foreach \fourargs in \multiplefourargs {%
\index[test]{\expandafter\invertfourargs\fourargs}}

***

% GET DATA OUT OF BIBFILE INTO DB
\nocite{*}
\DTLloadbbl{data}{data.bib}

\DTLforeachbibentry*{data}{
\DTLbibfieldlet{\Authors}{Author}
\foreach \Author in \Authors {%
\expandafter\DTLformatauthor\Author+}
%     \foreach \Author in \Authors {% THIS DOES NOT WORK
%       \index[test]{\expandafter\DTLformatauthor\Author}}
}

\printindex[test]
\end{document}


The error I get is:

Runaway definition?
->\write \test@idxfile {\indexentry{\let \global \advance \dtlforeachlevel \ETC
.
! File ended while scanning definition of \reserved@a.
<inserted text>
}


What should I do to fix my code?

## 1 Answer

Your problem is not to expand the \Author (\index will do it anyway) but to prevent the expansion of \DTLformatauthor when the index is written. So use

 \index[test]{\protect\DTLformatauthor\Author}}

• What is then the essential difference between \DTLformatauthor and \invertfourargs? – equaeghe May 27 '15 at 9:57
• The invertfourargs is expandable and can be executed while writing the .ind. Look in test.ind to see the differences. – Ulrike Fischer May 27 '15 at 10:15