# listings line numbers work with one lstlisting but not another

The first listing has its line numbers ignoring the stepnumber while the second is just fine. Guess it might have to do with using math mode but mathescape applies to both, so if that is the case it is not obvious what to do to me

\documentclass[a4paper, twoside]{book}

\usepackage{listings}
\lstset{
basicstyle=\small,
keywordstyle=\ttfamily,
identifierstyle=\ttfamily,
numbers=left,
numberstyle=\tiny,
stepnumber=5,
numbersep=5pt,
numberfirstline=true,
firstnumber=1,
mathescape=true
}

\begin{document}

\begin{lstlisting}
g = $\infty$

for $v$ in vertices:
s = $\emptyset$
r = $\{v\}$
pred[v] = $\emptyset$
d[v] = $0$
while not r == $\emptyset$:
x = $x \in r$
s = s $\cup$ x
r = r $\setminus$ x
for
\end{lstlisting}

\begin{lstlisting}
step = 1
res = new Graph()

def BFS(v,currentLength,maxLength):
if currentLength < maxLength:
if not label[v]:
label[v] = step
step = step + 1
for w in Neighborhood(v):
if label[w]:
continue
pred[w] = v
res.Append(v,w)
BFS(w,currentLength + 1, maxLength)

root = PickVertex()
BFS(root,0,k)
\end{lstlisting}

\end{document}

• It seems that every line in which a math formula is present triggers numbering the next line. – egreg Sep 1 '14 at 23:32

I believe that is caused by a bug in the listings code. These line numbers are printed because the flag that tests to see whether the code line is the first line is never reset. If you add

\makeatletter
\gdef\lst@numberfirstlinefalse{\global\let\lst@ifnumberfirstline\iffalse}

to you code (after \usepackage{listings}) then you will get the expected result (the \global is missing in lstmisc.sty). (Edit: I just added the Init line above to fix the first line number issue mentioned in the comments below.) • I wonder whether changing the definition of \lst@numberfirstlinefalse as you did has side effects. Anyway, well done for tracking that down, Andrew. I'm gonna post a small bounty to attract attention (and upvotes) to your answer. – jub0bs Sep 2 '14 at 23:05
• @Jubobs I realised that there is one side effect in that in the second code block above the first line number is not printed. When I have time I'll look and see if I can fix this -- each listings should just reset \lst@ifnumberfirstline. There probably shouldn't be any other side effects as this seems to only be used for printing line numbers...but the code is sufficiently complicated that I can't be sure. In any case, I reported this to the package maintainers. – Andrew Sep 2 '14 at 23:42
• @user60625 I just added the \lst@AddToHook{Init} line to my solution. This fixes the numbering of the first line. Let me know if this breaks anything else! – Andrew Sep 3 '14 at 11:24