I wish a multiline label in the lstlisting environment. I would like to reference more than one line within the same listing. Can you help me to find a solution?

I have found this link but this only helped me to refer to a certain line within the listing.

  • 2
    You want to reference "Lines 12 to 14"? That sort of thing? Can't you just do Lines \ref{first} to \ref{last}? – Seamus Jan 2 '13 at 12:26
  • Yes but I was curious to know if there is something better... – Kevin Jan 2 '13 at 14:33
  • 2
    In what way could something so simple be improved? – Seamus Jan 2 '13 at 14:53
  • Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count (see How do you accept an answer?). This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of this site's idea to identify good questions and answers through upvotes and acceptance of answers. – jub0bs Mar 2 '14 at 12:18

The best way which was mentioned in the commend and which is written in the documentation is the following:

You can define escape characters. Using this way, it is also possible to put labels to be able, later, to make reference to some lines of the verbatim environment.

In the documenation of listings you can find in section 7 the following hint: How to reference line numbers (page 53).

Based on the given example here a complete MWE:


if (i < 0)
i=0 (*@\label{commentI}@*)
j=1 end if
if (j < 0) j=0 (*@\label{commentII}@*)
end if
{ comment }
Lines \ref{commentI} to \ref{commentII}


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.