Using listings to include code in LaTeX

Introduction
During the last year I have written several small Matlab programs which I needed to include in my masters thesis which I am writing in LaTeX. The easiest way to do this is using the LaTeX package called listings.


This package makes it very easy to include and highlight all sorts of programming languages. The list of supported languages is quite long:

ABAP,ACSL,Ada,Algol,Ant,Assembler,Awk,bash,Basic,C,C++,
Caml,Clean,Cobol,Comal,csh,Delphi,Eiffel,Elan,erlang,
Euphoria,Fortran,GCL,Gnuplot,Haskell,HTML,IDL,inform,Java,
JVMIS,ksh,Lisp,Logo,make,Mathematica1,Matlab,Mercury,
MetaPost,Miranda,Mizar,ML,Modula2,MuPAD,NASTRAN,
Oberon-1,OCL,Octave,Oz,Pascal,Perl,PHP,PL/I,Plasm,POV,
Prolog,Promela,Python,R,Reduce,Rexx,RSL,Ruby,S,SAS,
Scilab,sh,SHELXL,Simula,SQL,tcl,TeX,VBScript,Verilog,VHDL,
VRML,XML,XSLT

When first went looking for the a way to highlight the code in a nice way a ran across M-code LaTeX Package [mathworks.com]. This was a small package which basically just wrapped around listings and defined some Matlab specific settings. I took some of the colors from this package made some other changes and ended up with a highlighting that suited me better. The syntax is quite straight forward and it is very to change the language. The package requires to have the setting defines in the preamble of the LaTeX document. The settings I am using for Matlab code is the following:

\usepackage{listings}
\usepackage{color}
\usepackage{textcomp}
\definecolor{listinggray}{gray}{0.9}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\lstset{
	backgroundcolor=\color{lbcolor},
	tabsize=4,
	rulecolor=,
	language=matlab,
        basicstyle=\scriptsize,
        upquote=true,
        aboveskip={1.5\baselineskip},
        columns=fixed,
        showstringspaces=false,
        extendedchars=true,
        breaklines=true,
        prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
        frame=single,
        showtabs=false,
        showspaces=false,
        showstringspaces=false,
        identifierstyle=\ttfamily,
        keywordstyle=\color[rgb]{0,0,1},
        commentstyle=\color[rgb]{0.133,0.545,0.133},
        stringstyle=\color[rgb]{0.627,0.126,0.941},
}

To include a code-snippet I just start the lstlisting environment as such:

\begin{lstlisting}
if draw
    print([outputpath, 'mygraph.eps'],'-depsc')
end
\end{lstlisting}

And if I want to include a whole source code file I use the lstinputlisting command:

\lstinputlisting{../Matlab/inverse/MetropolisDataMany.m}

Further reading
The package is quite well documented and the 58 pages long manual can be found here: listings.pdf

This entry was posted in Articles. Bookmark the permalink.

33 Responses to Using listings to include code in LaTeX

  1. Ashish Jain says:

    Thank you so very much. Finally I have included C++ code that looks really fine.

    lstset{
    	language=[Visual]C++,
    	keywordstyle=bfseriesttfamilycolor[rgb]{0,0,1},
    	identifierstyle=ttfamily,
    	commentstyle=color[rgb]{0.133,0.545,0.133},
    	stringstyle=ttfamilycolor[rgb]{0.627,0.126,0.941},
    	showstringspaces=false,
    	basicstyle=small,
    	numberstyle=footnotesize,
    	numbers=left,
    	stepnumber=1,
    	numbersep=10pt,
    	tabsize=2,
    	breaklines=true,
    	prebreak = raisebox{0ex}[0ex][0ex]{ensuremath{hookleftarrow}},
    	breakatwhitespace=false,
    	aboveskip={1.5baselineskip},
      columns=fixed,
      upquote=true,
      extendedchars=true,
    % frame=single,
    % backgroundcolor=color{lbcolor},
    }
  2. Rasmus says:

    I liked Ashis’ layout though i enabled the frame=single key. For my own documents I often do the following when including many files (My example uses Java where different packages are used):

    newcommand{sourceRoot}{../Java/src/}
    newcommand{myPackage}{}
    newcommand{myJPackage}{}
    newcommand{sourcePackage}[2]{subsection*{Package: #2}renewcommand{myPackage}{#1}renewcommand{myJPackage}{#2}}
    newcommand{sourceClass}[1]{lstinputlisting[caption=myJPackage.#1]{sourceRootmyPackage/#1}}

    After this the following lines can be used to include files from directories:

    lstlistoflistings
    sourcePackage{edu/psp/proteins}{edu.psp.proteins}
    sourceClass{Protein.java}
    sourceClass{ProteinConfiguration.java}
    sourceClass{AuxPrediction.java}
     
    sourcePackage{edu/psp/model}{edu.psp.model}
    sourceClass{CaProteinStructure.java}
    sourceClass{CurveStructure.java}
    sourceClass{NativeStructure.java}
    ...
  3. James Raybould says:

    I stumbled across this while writing up an assignment and I just wanted to thank you, its saved me a lot of time!

  4. I’m using to format loads of code a thesis of mine. Just want to say thank you!!

  5. well done tutorial. I am looking for the same…

  6. Hung says:

    Hey, thanks for the post!

  7. Joel says:

    I found your tutorial very helpful and to the point. Used it to complete a Pattern Recognition assignment. Thanx a bunch !!!

  8. DaMan says:

    Thanks a lot dude

  9. mk says:

    exactly what i was searching for .. finally some nice highlighted code blocks – thanks a lot!

  10. Keiji says:

    Thanks for the post and the information!

    By the way, the link of the listings manual is down. Now the link is
    ftp://ftp.tex.ac.uk/tex-archive/macros/latex/contrib/listings/listings.pdf

  11. Randy says:

    I’ve been trying to implement this with mcode and with the preamble listed above, but everytime I get an error:

    Package Listings Error: Option `upquote’ requires `textcomp’
    package.
    (Listings) The option has been disabled.
    See the Listings package documentation for explanation.

    I have the textcomp package loaded, but for some reason, it’s not being recognized. I checked out the Listings documentation, but I could make sense of it.

    Any ideas? Thanks.

  12. Hi Randy

    It has been a while since I played around with listings, but could it be that you load the textcomp to late in the preamble for listings to be able to use it? Try load textcomp as the first package in the preamble.

    Kind regards
    Thomas

  13. charbel says:

    Hi,

    The XML or HTML (tags languages) are not highlighted,
    Am I missing something ?

    \lstset{language=XML, numbers=left, caption=Intel Binary Light Device Description, label=code:binaryLight, xrightmargin=0.5cm}
    \begin{lstlisting}

    urn:schemas-upnp-org:device:BinaryLight:1
    Light (G-NECVL360-10)
    Intel Corporation

    \end{lstlisting}

    Regards,
    Charbel

  14. Ramesh Thulasiram says:

    Thanks! It was very useful!

  15. Thank you for the howto!

  16. Elvis says:

    Thank you VERY much for sharing this code this helped me lots with my thesis. God bless you mate

  17. Remco says:

    Just like many others, this has saved me tons of time figuring this stuff out for a nice layout. Thanks for sharing!

  18. Chris says:

    Thanks for this! Very helpful!

  19. mulloy says:

    Links are broken. Please update.

  20. Mulloy: The link to the listings.pdf is now updated.

  21. Liliana says:

    Thomas, thank you, it was really helpful.

  22. Rasmus B says:

    This gives me everything – THANKS

  23. Lukas says:

    Thanks Thomas, it’s really useful.

  24. Hussain says:

    You guys are great! Thanks for posting these settings 🙂

  25. Jon says:

    Hi.

    Just wanted to thank you for a great guide. I’m currently using this to include some matlab code i a lab report I’m writing, and it really turns out good.

    Thanks again!

    -Jon

  26. fern17 says:

    Thank you, it was really helpful 🙂

  27. Juan Carlos says:

    Thanks Thomas for the tip. I was looking for this!, it was really helpful.

  28. Gaberber says:

    Thanks Ashish a LOT!! Saved me so much time typesetting C++ codes!!

  29. drrilll says:

    Thank you!!

  30. Martin says:

    Thanks dude, I was working on a project and really struggled on that ‘problem’. You really helped me! 🙂

  31. some Dude says:

    didn’t read all the comments but:
    if you define several \lstset{} you might want to tell latex which one to use for your current listing in the document. heres the example:
    above u have \lstset{language=Java}, \lstset{language=C} in the document u write
    \begin{lstlisting}[language=Java] for Java or …=C for C. see?

  32. Cathy says:

    How can I persuade Latex to recognise functions I have used from the GPML Toolbox, and SC Toolbox, which I have downloaded?

    Any help appreciated.

  33. Pingback: Lo que he aprendido: añadir código con sintaxis resaltada en Latex | Onda Hostil

Leave a Reply