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

Only registered users can comment.

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

    \lstset{
    	language=[Visual]C++,
    	keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
    	identifierstyle=\ttfamily,
    	commentstyle=\color[rgb]{0.133,0.545,0.133},
    	stringstyle=\ttfamily\color[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.5\baselineskip},
      columns=fixed,
      upquote=true,
      extendedchars=true,
    % frame=single,
    % backgroundcolor=\color{lbcolor},
    }
  2. 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]{\sourceRoot\myPackage/#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. 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 found your tutorial very helpful and to the point. Used it to complete a Pattern Recognition assignment. Thanx a bunch !!!

  5. 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.

  6. 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

  7. 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

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

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

  10. 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

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

  12. 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?

  13. 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.

Leave a Reply