Try the listings package. It allows to escape to tex from within the typeset listing, so you could do something like (untested:)
\begin{lstlisting}[escapechar=\%]
..
..
..
.. %\index{key}%
..
..
..
\end{lstlisting}
Edsko