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}



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

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]:
            pred[w] = v
            BFS(w,currentLength + 1, maxLength)

root = PickVertex()

  • 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


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.)

enter image description here

  • 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
  • I'll have another look tomorrow. There may be something we can do with hooks. In any case, that sure looks like a bug. Whether someone on TeX.SX finds a solution or not, the maintainer should be contacted. – jub0bs Sep 2 '14 at 23:47
  • Works for me. The first line is not numbered, but the rest is fine. Thanks a lot. – Erik Itter Sep 3 '14 at 10:20
  • @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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.