51 Comments

  1. Katie

    Oh, this is brilliant. I have always used the verbatim-environment. but this has so much more options. great.

  2. Steven

    I have read great things about the listings package but in reality it is causing me lots of problems. I am writing a paper and have to include listings in an enumerated list to answer question numbers
    1/ I have indented my source file to make easier reading/construction – if I have the listing section indented it is reflected in the pdf output! (using pdflatex) which is just madness
    2/ The resulting text just looks ugly with incredibly bad spacing – the character kerning is completely messed up. Currently using the following setup:

    \documentclass[11pt,a4paper,oneside,onecolumn]{article}
    \usepackage{amsmath,amssymb,harvard}
    \usepackage{amsfonts}
    \usepackage{amsthm}
    \usepackage{amssymb}
    \usepackage{graphicx}
    \usepackage{harvard}
    \usepackage{listings}
    \usepackage{algorithm2e}
    \renewcommand{\labelenumii}{(\roman{enumii})}
    \renewcommand{\labelenumiii}{(\alph{enumiii})}
    \renewcommand{\labelenumiv}{(\roman{enumiv})}
    \begin{document}
    \lstset{basicstyle=\footnotesize,language=HTML}
    \headheight 14pt
    \bibliographystyle{plain}

    I will try to find a solution and see which package is conflicting (if any) but the result is really ugly and \verb is starting to look good…

  3. Hi Cesar

    Java is actually supported by the listings package. It appears in the list of supported languages above.

    Tom

  4. Rikke

    I’m having problems using lstinputlisting{}

    I guess that I should use something like C:\Users\Rikke\Documents\…\filename.R

    But it doesn’t work – have you any idea why?

    :o) Rikke

  5. Hi Rikke,

    As a starting directory, Latex will always use the location of your main document (where you have \documentclass{...}).
    To move upwards the directory-tree, you simply use “..\”.
    E.g. imagine you have a directory, with two folders, “code” and “report”. Inside “report”, you have your Latex-files and in “code” you have the source files. To include the source files, you would type:

    \lstinputlisting{..\code\filename.R}

    Cheers,
    Tom

  6. If you have python distribution in your machine you can use ‘pygmentize’. Using pygmentize you can also generate syntax highlighted code in Word, html and pdf formats besides LateX.

  7. nguyenminhhaivn

    @steven: You’ve said “The resulting text just looks ugly with incredibly bad spacing – the character kerning is completely messed up”. I finally found out that the “columns” option can solve your problem. The complete command is \lstset{columns=fullflexible}.

  8. The main problem I had with setting Awk scripts in verbatim mode is that single quotes are turned into curly apostrophes, making it awkward to copy and paste a typset example into a terminal or editor window to execute. Double quotes are OK in verbatim mode. Using lstlisting mode, ALL quotes are turned into curly quotes, one worse than verbatim.

    Any ideas? The simplest thing to make a listing in any mode without curling quotes would be good. Thanks.

  9. Answered my own question:

    \usepackage{upquote}

    after all other font specs will force typewriter font to Computer Modern Typewriter and make verbatim, verbatim*, verb, and verb* leave ` and ‘ in their original state.

    (” is already set unchanged; I’m not sure of the logic of curling ‘ and ` in a mode that otherwise leaves things unchanged. While it’s true that the old ASCII character set didn’t include encodings for these so it’s useful to be able to create them in verbatim mode, not having an obvious escape to get back to raw apostrophes and grave accents seems to me an omission).

    Not quote as fancy as the listings package but for simple scripts and one-liners, being able to get the various verbatim modes to behave is good. Unless you need the default behaviour for some other purpose in the same document …

    • Emerson

      Thansk Phillip for \usepackage{upquote}.

      I was looking for this solution.

      But I have another one. How to use a source code with accent (i.e. é, á, â, ã, etc.) in a utf8 enconding?

      I have tried \usepackage[utf8]{inputenc} and \lsset{extendedchars=\true,inputencoding=utf8} but without success. :-(

      • Hi there!

        Actually, you don’t need any package to do this. Try this: \'{e}\'{a}\^{a}\~{a}.

        Cheers,
        Tom.

  10. Nadine

    God mainly bless you for this page. It was a blessing for me to know how to put my SAS-Code into my latex document. So i just want to acknowledge and to thank you for it.

    • Hi Nadine,

      You can use the following options to omit the frame and numbering:

      frame=none, numbers=none

      You can find the documentation of the listings package here.

  11. Alexander Pokluda

    Here’s a line that creates a floating listing using \lstinputlisting :

    \lstinputlisting[float,caption=A floating example,label=R10]{R10.m}
  12. Phil

    I wanted this package to look a bit like the verbatim text. This can be achieved, by:

    \lstset{basicstyle=\small\ttfamily, basewidth=0.51em}.

    Thought it might be worth mentioning as it took me a while to find this.

  13. i82much

    I cannot get the lstlisting to work with autoref – if I attempt to wrap the listing in a labeled figure and then reference it, I jump to a random place on a page near the figure, but not at the figure itself. This is very frustrating. Has anyone figured a workaround for this?

  14. I’ve found a workaround for people, like me, who’s using UTF8 as encoding: ‘listingsutf8′. This package provides support for those ‘strange’ characters when using the \lstinputlisting command.

    Be aware that ‘listings’ package (as far as I read) doesn’t support multi-byte encodings (UTF8 and others), but only one-byte encoding. The trick of ‘listingsutf8′ is to translate a text file (the source code) to an encoding that ‘listings’ can understand… And hope, as well, that you understood me :)

    So, it’s not a final solution, but works.

  15. Is there any way to change the name of Listing like i can do with chapters (\renewcommand\chaptername{new_chapter_name}) ???

  16. Gaya

    I used the lstlisting for my code and used latex2pdf to create a pdf file.
    When I copy and paste the source code from a pdf generated file, it losses its formatting. What can I do about this?

  17. Allusion

    Hi there. I tried the listings package too. Everything would have been wonderful… if copying code chunks were not such a pain. Did somebody manage to do this properly?

    columns=flexible or columns=fixed have both severe problems, the first ruins my indentation, the second adds weird phantom spaces throughout my code. Thanks.

    • Hello!
      Probably easier than copying the code is to include it directly from the source file. I described how to do that in the post above.
      The problem with the columns-option is known. If you don’t need it, just drop it. If you think you need it, please provide a minimal example. I will then try to help you…
      I created a few code highlighting examples some time ago that you may find useful.
      Tom.

  18. Oke I used pygmentize to get the code working but that doesn’t really matters… I was wondering how you refer to the code? At the moment I use \figure to do this but i was wondering if there is something called \code to use as a reference so in the text will be something like…

    As can be seen in code 2.5 or something similar.

    Any ideas?

    • I wouldn’t know of anything like that. But you can always define it yourself:

      \newcommand{\code}[1]{source code \ref{#1}}
      ...
      See \code{code:example1}.

      Tom.

    • Iray

      Hi Jasper,

      How do you use pygmentize? If I can recall correctly, it only outputs fancyvrb env’s and not lstlistings

    • Hi Iray,

      The listings package covers that. Use the firstnumber=x key-value-pair.

      \begin{lstlisting}[firstnumber=3,numbers=left]
      ...
      \end{lstlisting}

      Best, Tom

      • Iray

        Hi, Tom,

        Sorry, I’m afraid I wasn’t very clear. I want numbering to start at line 3, with that line numbered 1

        #she-bang (line 1 not numbered but shown)
        (line 2 not numbered but shown)
        import math (line 3 would be numbered with 1)
        (line 4 would be numbered with 2)

        and so on.

        I knew about firstnumber and have already tried firstnumber=-1 but the pbm is I can’t see anywhere in the listings manual how to turn off the numbering for these first two lines or at least how to do it on a line by line basis.

  19. Robert

    I am trying to write a Latex document that explains what various parts of my code are doing, section-by-section.
    Sometimes it is better to show just a few lines at the start and end of each section and use dots in between.

    Is there any way to do that which doesn’t require me just to manually delete the body of the section and add a \dots or similar?

    For example, something like

    \displaysourcecodesection[1-3,10-12]{ section of code here }

    that would show only lines 1, 2 and 3 followed by dots and then lines 10, 11 and 12.

    It would allow me to not have to delete parts of my source code from the .tex file and would allow me flexibility to get the final balance right of how much of each section I want to show in the final output.

    Thanks

  20. Jack

    I am trying to include source code from a gnuplot script, but some of the lines are apparently being interpreted as LaTex commands. This is an example line with a problem. Is there a way to turn off interpretation of LaTex keywords within a listing?

    set xlabel “Particle Velocity (cm/{/Symbol \155}S)” font “Helvetica,18″ offset char 0, char -1

    • Hi Jack,

      Interesting question. I tried to reproduce your problem. The only thing I saw was an issue with the double quotes you are using. You would have to load the right encoding in order to make them display correctly. You could also replace them with standard double quotes (open and close the same) and then use standard encoding as in the code below.

      \documentclass[11pt]{article}
      \usepackage[latin1]{inputenc}
      \usepackage[T1]{fontenc}
      \usepackage{xcolor, listings}
      
      \definecolor{lightgrey}{rgb}{0.9,0.9,0.9}
      \definecolor{darkgreen}{rgb}{0,0.6,0}
      
      \lstset{language=Gnuplot,
      breaklines=true,
      keywordstyle=\color{darkgreen},
      otherkeywords={$, \{, \}, \[, \]},
      backgroundcolor=\color{lightgrey}}
      \begin{document}
      
      \begin{lstlisting}
      set xlabel "Particle Velocity (cm/{/Symbol \155}S)" font "Helvetica,18" offset char 0, char -1
      \end{lstlisting}
      
      \end{document}

      If this didn’t solve your problem, please post a minimal example similar to the one I provided.

      Thanks, Tom

Leave a Reply