LaTeX/Source Code Listings

Using the listings package

Using the package listings you can add non-formatted text as you would do with \begin{verbatim} but its main aim is to include the source code of any programming language within your document. If you wish to include pseudocode or algorithms, you may find Algorithms and Pseudocode useful also.

To use the package, you need:

\usepackage{listings}

The listings package supports highlighting of all the most common languages and it is highly customizable. If you just want to write code within your document the package provides the lstlisting environment:

\begin{lstlisting}
Put your code here.
\end{lstlisting
}

Another possibility, that is very useful if you created a program on several files and you are still editing it, is to import the code from the source itself. This way, if you modify the source, you just have to recompile the LaTeX code and your document will be updated. The command is:

\lstinputlisting{source_filename.py}

in the example there is a Python source, but it doesn't matter: you can include any file but you have to write the full file name. It will be considered plain text and it will be highlighted according to your settings, that means it doesn't recognize the programming language by itself. You can specify the language while including the file with the following command:

\lstinputlisting[language=Python]{source_filename.py}

You can also specify a scope for the file.

\lstinputlisting[language=Python, firstline=37, lastline=45]{source_filename.py}

This comes in handy if you are sure that the file will not change (at least before the specified lines). You may also omit the firstline or lastline parameter: it means everything up to or starting from this point.

This is a basic example for some Pascal code:

\documentclass{article}
\usepackage{listings
}             % Include the listings-package
\begin{document}
\lstset{language=Pascal
}          % Set your language (you can change the language for each code-block optionally)

\begin{lstlisting}[frame=single]  % Start your code-block
for i:=maxint to 0 do
begin
{ do nothing }
end;
Write(’Case insensitive ’);
Write(’Pascal keywords.’);
\end{lstlisting}

\end{document
}

Latex sample code.PNG

Supported languages

It supports the following programming languages:

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

For some of them, several dialects are supported. For more information, refer to the documentation that comes with the package, it should be within your distribution under the name listings-*.dvi.

Notes
  1. It supports Mathematica code only if you are typing in plain text format. You can't include *.NB files \lstinputlisting{...} as you could with any other programming language, but Mathematica can export in a pretty-formatted LaTeX source.
  2. Specification of the dialect is mandatory for these languages (e.g. language={[x86masm]Assembler}).
  3. Modelica is supported via the dtsyntax package available here.
  4. Some languages have optional dialects. Like C has (ANSI, Handel, Objective, Sharp) the listings manual, p12.

Settings

You can modify several parameters that will affect how the code is shown. You can put the following code anywhere in the document (it doesn't matter whether before or after \begin{document}), change it according to your needs. The meaning is explained next to any line.

\usepackage{listings}
\usepackage{color}

\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82
}

\lstset{ %
  backgroundcolor=\color{white},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
  basicstyle=\footnotesize,        % the size of the fonts that are used for the code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true,                 % sets automatic line breaking
  captionpos=b,                    % sets the caption-position to bottom
  commentstyle=\color{mygreen},    % comment style
  deletekeywords={...},            % if you want to delete keywords from the given language
  escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
  frame=single,                    % adds a frame around the code
  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
  keywordstyle=\color{blue},       % keyword style
  language=Octave,                 % the language of the code
  morekeywords={*,...},            % if you want to add more keywords to the set
  numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
  numbersep=5pt,                   % how far the line-numbers are from the code
  numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
  rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
  showstringspaces=false,          % underline spaces within strings only
  showtabs=false,                  % show tabs within strings adding particular underscores
  stepnumber=2,                    % the step between two line-numbers. If it's 1, each line will be numbered
  stringstyle=\color{mymauve},     % string literal style
  tabsize=2,                       % sets default tabsize to 2 spaces
  title=\lstname                   % show the filename of files included with \lstinputlisting; also try caption instead of title
}

escapeinside

The escapeinside line needs an explanation. The option escapeinside={A}{B} will define delimiters for escaping into LaTeX code, i.e. all the code between the string "A" and "B" will be parsed as LaTeX over the current listings style. In the example above, the comments for Octave start with %, and they are going to be printed in the document unless they start with %*, in which case they are read as LaTeX (with all LaTeX commands fulfilled) until they're closed with another *). If you add the above paragraph, the following can be used to alter the settings within the code:

\lstset{language=C,caption={Descriptive Caption Text},label=DescriptiveLabel}

There are many more options, check the official documentation.

Style definition

The package lets you define styles, i.e. profiles specifying a set of settings.

Example

\lstdefinestyle{customc}{
  belowcaptionskip=1\baselineskip,
  breaklines=true,
  frame=L,
  xleftmargin=\parindent,
  language=C,
  showstringspaces=false,
  basicstyle=\footnotesize\ttfamily,
  keywordstyle=\bfseries\color{green!40!black},
  commentstyle=\itshape\color{purple!40!black},
  identifierstyle=\color{blue},
  stringstyle=\color{orange},
}

\lstdefinestyle{customasm}{
  belowcaptionskip=1\baselineskip,
  frame=L,
  xleftmargin=\parindent,
  language=[x86masm]Assembler,
  basicstyle=\footnotesize\ttfamily,
  commentstyle=\itshape\color{purple!40!black},
}

\lstset{escapechar=@,style=customc
}

In our example, we only set two options globally: the default style and the escape character. Usage:

\begin{lstlisting}
#include <stdio.h>
#define N 10
/* Block
 * comment */
 
int main()
{
    int i;
 
    // Line comment.
    puts("Hello world!");
 
    for (i = 0; i < N; i++)
    {
        puts("LaTeX is also great for programmers!");
    }
 
    return 0;
}
\end{lstlisting}
 
\lstinputlisting[caption=Scheduler, style=customasm]{sched.s}

The C part will print as

Listings Example.svg

Automating file inclusion

If you have a bunch of source files you want to include, you may find yourself doing the same thing over and over again. This is where macros show their real power.

\newcommand{\includecode}[2][c]{\lstinputlisting[caption=#2, escapechar=, style=custom#1]{#2}}
% ...

\includecode{sched.c}
\includecode[asm]{sched.s
}
% ...

\lstlistoflistings

In this example, we create one command to ease source code inclusion. We set the default style to be customc. All listings will have their name as caption: we do not have to write the file name twice thanks to the macro. Finally we list all listings with this command from the listings package.

See Macros for more details.

Encoding issue

Unfortunately, listings does not support multi-byte encoding for source code. You cannot input UTF-8 source files nor use special characters in your listing environment while your document is saved as UTF-8.

The extendedchar option only works for 8-bits encodings such as latin1.

Some languages only make use of some diacritics over the traditional ASCII characters (A-Za-z). In that case you may want to turn all accented characters to the blank ASCII one. You can automate this task with tools like sed.

sed -i -e 's/áàâä/a/g' -e 's/éèêë/e/g' source.c

Nonetheless, commenting source code in a language other than English is often considered bad practice. English normally allows your source code to be widely understood and maintained.

↑Jump back a section

Customizing captions

You can have fancy captions (or titles) for your listings using the caption package. Here is an example for listings.

\usepackage{caption}
\usepackage{listings}

\DeclareCaptionFont{white}{ \color{white} }
\DeclareCaptionFormat{listing}{
  \colorbox[cmyk]{0.43, 0.35, 0.35,0.01 }{
    \parbox{\textwidth}{\hspace{15pt}#1#2#3}
  }
}
\captionsetup[lstlisting]{ format=listing, labelfont=white, textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize}
}

% ...

\lstinputlisting[caption=My caption]{sourcefile.lang}

↑Jump back a section

References

A lot more detailed information can be found in a PDF by Carsten Heinz and Brooks Moses.

Details and documentation about the Listings package can be found at its CTAN website.


Previous: Algorithms Index Next: Linguistics
↑Jump back a section
Last modified on 17 May 2013, at 06:44