TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to refer to to the count value of the number of lines in a listing. Is there a way to do that ?

    \lstinputlisting[caption={SPARQL query used...},label={lst:sqry}]{codes/sparql_query.sparql}

I can refer to this listing in a document by using \ref{lst:sqry}, but I need to be able to automatically count the number of lines in that listing and refer to the value.

I would deeply appreciate any help.

share|improve this question
Welcome to TeX.sx! – Peter Jansson Apr 17 '13 at 10:30
Does this only hold for \lstinputlistings or for regular lstlistings as well? – Werner Apr 17 '13 at 11:28
@PeterJansson Thank you :) – Joshua Apr 18 '13 at 16:50
up vote 8 down vote accepted

The following should do the trick using counter lst@lineno. The example creates a reference after the listings that contains the number of lines:




  caption={The listings has \ref{lst:job} lines.},


share|improve this answer
Brilliant ! Thank you very much for the prompt reply. Will surely mention this help in my acknowledgement :) – Joshua Apr 18 '13 at 16:47

This solution uses a different approach and was written as answer for question "Listings: total line number count" that was closed too fast.

This solution uses a different approach than my other answer:

  • Also a label is used to remember the number of code lines. This variant uses package zref for this purpose.

  • The number of code lines is made available by macro \mylstlines in the caption for the listing. That saves the user from the need to invent unique label names. Counter mylstlisting identifies a listing and the value is used in the name of the label.

  • The code lines are counted via counter mylstlines by hooking into the listings hook EveryPar. This way, the value of mylstlines should not be affected by options that affect the selected line range (firstline) or that change the printed line numbers (firstnumber).

Example file:



% \mylstlines print number of lines inside listing caption

% cosmetics
\lstset{basicstyle=\ttfamily, columns=fullflexible,
    numbers=left, stepnumber=1}

    caption={Example with \mylstlines\ lines.},


BTW [off topic]: The number of code lines in this example is the answer to another question.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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