2

I'm trying to index the tokens in a listing, but they always get rejected if they are followed by a comma.

Here's mwe.tex:

\documentclass{article}
\usepackage{listings}

\lstset{index={foobar}}

\makeindex

\begin{document}
  \begin{lstlisting}
    foobar, baz
  \end{lstlisting}
\end{document}

pdflatex mwe produces mwe.idx:

\indexentry{{\ttfamily  foobar\unhbox \voidb@x \kern \z@ }}{1}

makeindex mwe however rejects the entry, as seen in mwe.ilg:

This is makeindex, version 2.15 [TeX Live 2018] (kpathsea + Thai support).
Scanning input file mwe.idx...
!! Input index error (file = mwe.idx, line = 1):
   -- Extra `@' at position 44 of first argument.
done (0 entries accepted, 1 rejected).
Nothing written in mwe.ind.
Transcript written in mwe.ilg.

I feel like \unhbox \voidb@x \kern \z@ shouldn't be there. I figured out that's the expansion of \lst@nolig.

I located \lst@nolig's definition in listings.sty but its purpose is not clear to me and I'm not sure why this happens only when a token preceeds a comma.

\let\lst@nolig\@empty is a solution, but of course that's not satisfactory.

What's the proper solution to the problem?

Also, what's going on with the \lst@nolig?

1 Answer 1

3

The problem is indeed the comma, because in this case \index is passed foobar\lst@nolig. Redefine, locally, \lst@nolig to avoid the issue.

\documentclass{article}
\usepackage{listings}

\makeatletter
\renewcommand{\lstindexmacro}[1]{%
  \begingroup
  \def\lst@nolig{}%
  \index{#1@{\ttfamily#1}}%
  \endgroup
}
\makeatother

\lstset{index={foobar,baz}}

\makeindex

\begin{document}

\begin{lstlisting}
foobar, baz
\end{lstlisting}

\end{document}

The standard definition of \lstindexmacro is just \index{#1}, but this will give sorting problems. Here is the produced .idx file:

\indexentry{foobar@{\ttfamily  foobar}}{1}
\indexentry{baz@{\ttfamily  baz}}{1}
1
  • Thanks! Local redefinition is what I ended up doing. I still feel like listings should be able to indicize the foobar token with no trailing extra macros, or provide some options to correctly handle the comma (I searched and found nothing). Could this actually be a bug in listings? I'll wait a bit just in case someone else chimes in. Sep 28, 2019 at 8:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .