TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

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 am trying to get only the actual code to be line numbered rather than both code and comments. Example:

\lstset{basicstyle=\footnotesize, xleftmargin=40pt, frame =
single, numbers = left,caption = Test, label = list:Test} 
\begin{lstlisting}[language = java,mathescape]
//Test comment
if( this = test)
\vspace{2 mm}

Prints all line numbers for the comment as well.

Thanks for your help.

share|improve this question
up vote 9 down vote accepted

I don't think it is possible to do what you want with the "listings" package. However, if it is worth your time you can break it up in sections and use a style for numbers and another for no-numbers. See the example below for one way of doing this.

{numbers=left, stepnumber=1, numberstyle=\tiny, numbersep=10pt}
// this is comments
// and more
for i:=maxint to 0 do
  {do some code}
// this is comments
// and more

Personally, I avoid typesetting code with comments, as it looks very ugly. Since you describing your code it is preferable - instead of comments to provide your own commentary in words (like the documentation in most packages).

You can also try the 'fancyvrb" which I believe provides such a facility as you specified.

share|improve this answer
Thanks a lot for your well laid out answer. However, one question remains; is it going to be possible to extend the frame of the code from one listing to the other? I both agree and disagree with your opinion of comments though. I do want to explain my code, however, there are subtle things that I want to write within the listing. – arin Jan 18 '11 at 19:01

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.