The Listings Package
Copyright 1996–2004, Carsten Heinz
Copyright 2006–2007, Brooks Moses
Copyright 2013–, Jobst Hoffmann
Maintainer: Jobst Hoffmann∗ <j.hoffmann(at)fh-aachen.de>
2024/05/25 Version 1.10b
Abstract
The listings package is a source code printer for LATEX. You can typeset
stand alone files as well as listings with an environment similar to verbatim
as well as you can print code snippets using a command similar to \verb.
Many parameters control the output and if your preferred programming
language isn’t already supported, you can make your own definition.

User’s guide4 4 Main reference

1 Getting started
1.1 A minimal file . . . . . . . . .
1.2 Typesetting listings . . . . .
1.3 Figure out the appearance . .
1.4 Seduce to use . . . . . . . . .
1.5 Alternatives . . . . . . . . . .
2 The next steps
2.1 Software license . . . . . . . .
2.2 Package loading . . . . . . .
2.3 The key=value interface . . .
2.4 Programming languages . . .
2.4.1 Preferences . . . . . . . . .
2.5 Special characters . . . . . .
2.6 Line numbers . . . . . . . . .
2.7 Layout elements . . . . . . .
2.8 Emphasize identifiers . . . . .
2.9 Indexing . . . . . . . . . . . .
2.10 Fixed and flexible columns .
3 Advanced techniques
3.1 Style definitions . . . . . . . .
3.2 Language definitions . . . . .
3.3 Delimiters . . . . . . . . . . .
3.4 Closing and credits . . . . . .

4
4
4
6
7
8
10
10
11
12
12
14
14
16
17
20
21
22
23
23
23
25
26

28
4.1 How to read the reference . . 28
4.2 Typesetting listings . . . . . 29
4.3 Options . . . . . . . . . . . . 29
4.3.1 Searching for files . . . . . 29
4.3.2 Space and placement . . . . 30
4.3.3 The printed range . . . . . 30
4.3.4 Languages and styles . . . 31
4.3.5 Figure out the appearance . 32
4.3.6 Getting all characters right 34
4.3.7 Line numbers . . . . . . . . 35
4.3.8 Captions . . . . . . . . . . 36
4.3.9 Margins and line shape . . 37
4.3.10 Frames . . . . . . . . . . . 38
4.3.11 Indexing . . . . . . . . . . . 40
4.3.12 Column alignment . . . . . 41
4.3.13 Escaping to LATEX . . . . . 42
4.4 Interface to fancyvrb . . . . . 43
4.5 Environments . . . . . . . . . 44
4.6 Short Inline Listing Commands 45
4.7 Language definitions . . . . . 45
4.8 Installation . . . . . . . . . . 49
5 Experimental features
50
5.1 Listings inside arguments . . 50
5.2 † Export of identifiers . . . . 51
5.3 † Hyperlink references . . . . 52
Reference guide
27 5.4 Literate programming . . . . 52
5.5 LGrind definitions . . . . . . . 53
∗ Jobst Hoffmann became the maintainer of
5.6 † Automatic formatting . . . 53
the listings package in 2013; see the Preface for
5.7 Arbitrary linerange markers . 55
details.
5.8 Multicolumn Listings . . . . . 56

1

Tips and tricks

56

6 Troubleshooting
7 Bugs and workarounds
7.1 Listings inside arguments . .
7.2 Listings with a backgroundcolour and LATEX escaped formulas . . . . . . . . . . . . .
8 How tos

56
57
57
57
58

Index

62

2

Preface
Transition of package maintenance The TEX world lost contact with Carsten
Heinz in late 2004, shortly after he released version 1.3b of the listings package.
After many attempts to reach him had failed, Hendri Adriaens took over maintenance of the package in accordance with the LPPL’s procedure for abandoned
packages. He then passed the maintainership of the package to Brooks Moses,
who had volunteered for the position while this procedure was going through.
The result is known as listings version 1.4.
This release, version 1.5, is a minor maintenance release since I accepted maintainership of the package. I would like to thank Stephan Hennig who supported
the Lua language definitions. He is the one who asked for the integration of a new
language and gave the impetus to me to become the maintainer of this package.
News and changes Version 1.5 is the fifth bugfix release. There are no changes
in this version, but two extensions: support of modern Fortran (2003, 2008) andLua.

Thanks There are many people I have to thank for fruitful communication,
posting their ideas, giving error reports, adding programming languages tolstdrvrs.dtx, and so on. Their names are listed in section 3.4.
Trademarks Trademarks appear throughout this documentation without any
trademark symbol; they are the property of their respective trademark owner.
There is no intention of infringement; the usage is to the benefit of the trademark
owner.
3

User’s guide1

Getting started

1.1

A minimal file

Before using the listings package, you should be familiar with the LATEX typesetting
system. You need not to be an expert. Here is a minimal file for listings.
%
%
%
%
%
%
%
%
%

\documentclass{article}\usepackage{listings}\begin{document}\lstset{language=Pascal}% Insert Pascal examples here.
\end{document}

Now type in this first example and run it through LATEX.
→ Must I do that really?
Yes and no. Some books about programming say this is good.
What a mistake! Typing takes time—which is wasted if the code is clear to you. And if you
need that time to understand what is going on, the author of the book should reconsider theconcept of presenting the crucial things—you might want to say that about this guide even—or you’re simply inexperienced with programming. If only the latter case applies, you should
spend more time on reading (good) books about programming, (good) documentations, and(good) source code from other people. Of course you should also make your own experiments.
You will learn a lot. However, running the example through LATEX shows whether the listings
package is installed correctly.
→ The example doesn’t work.
Are the two packages listings and keyval installed on yoursystem? Consult the administration tool of your TEX distribution, your system administrator,
the local TEX and LATEX guides, a TEX FAQ, and section 4.8—in that order. If you’ve checked
all these sources and are still helpless, you might want to write a post to a TEX newsgrouplike comp.text.tex.
→ Should I read the software license before using the package?
Yes, but read this Getting
started section first to decide whether you are willing to use the package.

1.2

Typesetting listingsThree types of source codes are supported: code snippets, code segments, andlistings of stand alone files. Snippets are placed inside paragraphs and the others as
separate paragraphs—the difference is the same as between text style and display
style formulas.
→ No matter what kind of source you have, if a listing contains national characters like é, L, ä,or whatever, you must tell the package about it! Section 2.5 Special characters discusses thisissue.

Code snippets The well-known LATEX command \verb typesets code snippets
verbatim. The new command \lstinline pretty-prints the code, for example‘var i : integer;’ is typeset by ‘\lstinline!var i:integer;!’. The exclamation
marks delimit the code and can be replaced by any character not in the code;\lstinline$var i:integer;$ gives the same result.
4Displayed code The lstlisting environment typesets the enclosed sourcecode. Like most examples, the following one shows verbatim LATEX code on theright and the result on the left. You might take the right-hand side, put it into
the minimal file, and run it through LATEX.
1 \begin{lstlisting}
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6
7 Write(’Case insensitive ’);
8 WritE(’Pascal keywords.’);
9 \end{lstlisting}

1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;
5
6 Write ( ’ Case i n s e n s i t i v e ’ ) ;7 WritE( ’ P a s c a l keywords . ’ ) ;It can’t be easier.
→ That’s not true. The name ‘listing’ is shorter.
Indeed. But other packages alreadydefine environments with that name. To be compatible with such packages, all commands
and environments of the listings package use the prefix ‘lst’.

The environment provides an optional argument. It tells the package to perform
special tasks, for example, to print only the lines 2–5:

1 begin2{ do n o t h i n g }3 end ;

1 \begin{lstlisting}[firstline=2,2
lastline=5]
3 for i:=maxint to 0 do
4 begin5{ do nothing }6 end;
7
8 Write(’Case insensitive ’);
9 WritE(’Pascal keywords.’);
10 \end{lstlisting}→ Hold on! Where comes the frame from and what is it good for?
You can put framesaround all listings except code snippets. You will learn how later. The frame shows that empty
lines at the end of listings aren’t printed. This is line 5 in the example.
→ Hey, you can’t drop my empty lines!
You can tell the package not to drop them: The key‘showlines’ controls these empty lines and is described in section 4.2. Warning: First readahead on how to use keys in general.
→ I get obscure error messages when using ‘firstline’.
bug report as described in section 6 Troubleshooting.

That shouldn’t happen. Make aStand alone files Finally we come to \lstinputlisting, the command used
to pretty-print stand alone files. It has one optional and one file name argument.
Note that you possibly need to specify the relative path to the file. Here now theresult is printed below the verbatim code since both together don’t fit the text
width.
1 \lstinputlisting[lastline=4]{listings.sty}

5

1 %%
2 %% This is file ‘listings.sty’,
3 %% generated with the docstrip utility.
4 %%→ The spacing is different in this example.
Yes. The two previous examples have aligned
columns, i.e. columns with identical numbers have the same horizontal position—this package
makes small adjustments only. The columns in the example here are not aligned. This is
explained in section 2.10 (keyword: full flexible column format).

Now you know all pretty-printing commands and environments. It remains
to learn the parameters which control the work of the listings package. This is,however, the main task. Here are some of them.

1.3

Figure out the appearance

Keywords are typeset bold, comments in italic shape, and spaces in strings appear
as . You don’t like these settings? Look at this:
1 \lstset{% general command to set parameter(s)2basicstyle=\small,% print whole listing small
3
keywordstyle=\color{black}\bfseries\underbar,
4% underlined bold black keywords
5
identifierstyle=,% nothing happens
6
commentstyle=\color{white}, % white comments
7
stringstyle=\ttfamily,% typewriter type for strings
8showstringspaces=false}% no special string spaces
1 \begin{lstlisting}
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6
7 Write(’Case insensitive ’);
8 WritE(’Pascal keywords.’);
9 \end{lstlisting}

1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;
5
6 Write ( ’ Case insensitive ’ ) ;7 WritE( ’ Pascal keywords . ’ ) ;→ You’ve requested white coloured comments, but I can see the comment on the left side.
There are a couple of possible reasons: (1) You’ve printed the documentation on nonwhite
paper. (2) If you are viewing this documentation as a .dvi-file, your viewer seems to haveproblems with colour specials. Try to print the page on white paper. (3) If a printout on
white paper shows the comment, the colour specials aren’t suitable for your printer or printerdriver. Recreate the documentation and try it again—and ensure that the color package iswell-configured.

The styles use two different kinds of commands. \ttfamily and \bfseries bothtake no arguments but \underbar does; it underlines the following argument. In
general, the very last command may read exactly one argument, namely somematerial the package typesets. There’s one exception. The last command ofbasicstyle must not read any tokens—or you will get deep in trouble.
→ ‘basicstyle=\small’ looks fine, but comments look really bad with ‘commentstyle=\tiny’and empty basic style, say.
Don’t use different font sizes in a single listing.
→ But I really want it!

No, you don’t.

6Warning You should be very careful with striking styles; the recent example
is rather moderate—it can get horrible. Always use decent highlighting. Unfortunately it is difficult to give more recommendations since they depend on thetype of document you’re creating. Slides or other presentations often require morestriking styles than books, for example. In the end, it’s you who have to find thegolden mean!

1.4

Seduce to use

You know all pretty-printing commands and some main parameters. Here now
comes a small and incomplete overview of other features. The table of contents
and the index also provide information.
Line numbers are available for all displayed listings, e.g. tiny numbers on theleft, each second line, with 5pt distance to the listing:
1 \lstset{numbers=left, numberstyle=\tiny, stepnumber=2, numbersep=5pt}
1 \begin{lstlisting}
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6
7 Write(’Case insensitive ’);
8 WritE(’Pascal keywords.’);
9 \end{lstlisting}f o r i :=maxint to 0 do
begin
3{ do n o t h i n g }
end ;
1

5

7

Write ( ’ Case i n s e n s i t i v e ’ ) ;WritE( ’ P a s c a l keywords . ’ ) ;→ I can’t get rid of line numbers in subsequent listings.

‘numbers=none’ turns them off.

→ Can I use these keys in the optional arguments?
Of course. Note that optional arguments
modify values for one particular listing only: you change the appearance, step or distance ofline numbers for a single listing. The previous values are restored afterwards.

The environment allows you to interrupt your listings: you can end a listing andcontinue it later with the correct line number even if there are other listings in
between. Read section 2.6 for a thorough discussion.
Floating listings

Displayed listings may float:

1 \begin{lstlisting}[float,caption=A floating example]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6
7 Write(’Case insensitive ’);
8 WritE(’Pascal keywords.’);
9 \end{lstlisting}Don’t care about the parameter caption now. And if you put the example into
the minimal file and run it through LATEX, please don’t wonder: you’ll miss thehorizontal rules since they are described elsewhere.
→ LATEX’s float mechanism allows one to determine the placement of floats. How can I do thatwith these?
You can write ‘float=tp’, for example.

7

Listing 1: A floating example
1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;
5
6 Write ( ’ Case i n s e n s i t i v e ’ ) ;7 WritE( ’ P a s c a l keywords . ’ ) ;Other features There are still features not mentioned so far: automatic breaking of long lines, the possibility to use LATEX code in listings, automated indexing,
or personal language definitions. One more little teaser? Here you are. But notethat the result is not produced by the LATEX code on the right alone. The main
parameter is hidden.
1 \begin{lstlisting}
2 if (i<=0) then i := 1;
3 if (i>=0) then i := 0;
4 if (i<>0) then i := 0;
5 \end{lstlisting}

1 i f ( i≤0 ) then i ← 1 ;2 i f ( i≥0 ) then i ← 0 ;3 i f ( i̸=0 ) then i ← 0 ;You’re not sure whether you should use listings? Read the next section!

1.5

Alternatives→ Why do you list alternatives?

Well, it’s always good to know the competitors.

→ I’ve read the descriptions below and the listings package seems to incorporate all the features.
Why should I use one of the other programs?
Firstly, the descriptions give a taste andnot a complete overview, secondly, listings lacks some properties, and, ultimately, you should
use the program matching your needs most precisely.

This package is certainly not the final utility for typesetting source code. Other
programs do their job very well, if you are not satisfied with listings. Some are
independent of LATEX, others come as separate program plus LATEX package, andothers are packages which don’t pretty-print the source code. The second typeincludes converters, cross compilers, and preprocessors. Such programs create
LATEX files you can use in your document or stand alone ready-to-run LATEX files.
Note that I’m not dealing with any literate programming tools here, which
could also be alternatives. However, you should have heard of the WEB system,
the tool Prof. Donald E. Knuth developed and made use of to document andimplement TEX.
a2ps started as ‘ASCII to PostScript’ converter, but today you can invoke theprogram with --pretty-print=⟨language⟩ option. If your favourite programming
language is not already supported, you can write your own so-called style sheet.
You can request line numbers, borders, headers, multiple pages per sheet, andmany more. You can even print symbols like ∀ or α instead of their verbose forms.
If you just want program listings and not a document with some listings, this isthe best choice.

8

LGrind is a cross compiler and comes with many predefined programming languages. For example, you can put the code on the right in your document, invoke
LGrind with -e option (and file names), and run the created file through LATEX.
You should get a result similar to the left-hand side:

LGrind not installed.

% %[% for i:=maxint to 0 do
% begin%{ do nothing }% end;%% Write(’Case insensitive ’);% WritE(’Pascal keywords.’);% %]If you use %( and %) instead of %[ and %], you get a code snippet instead ofa displayed listing. Moreover you can get line numbers to the left or right, use
arbitrary LATEX code in the source code, print symbols instead of verbose names,
make font setup, and more. You will (have to) like it (if you don’t like listings).
Note that LGrind contains code with a no-sell license and is thus nonfree software.
cvt2ltx is a family of ‘source code to LATEX’ converters for C, Objective C, C++,IDL and Perl. Different styles, line numbers and other qualifiers can be chosen bycommand-line option. Unfortunately it isn’t documented how other programming
languages can be added.
C++2LATEX is a C/C++ to LATEX converter. You can specify the fonts for comments, directives, keywords, and strings, or the size of a tabulator. But as far as
I know you can’t number lines.
SLATEX is a pretty-printing Scheme program (which invokes LATEX automatically)
especially designed for Scheme and other Lisp dialects. It supports stand alone
files, text and display listings, and you can even nest the commands/environments
if you use LATEX code in comments, for example. Keywords, constants, variables,and symbols are definable and use of different styles is possible. No line numbers.
tiny c2ltx is a C/C++/Java to LATEX converter based on cvt2ltx (or the other way
round?). It supports line numbers, block comments, LATEX code in/as comments,and smart line breaking. Font selection and tabulators are hard-coded, i.e. you
have to rebuild the program if you want to change the appearance.
listing —note the missing s—is not a pretty-printer and the aphorism about
documentation at the end of listing.sty is not true. It defines \listoflistings
and a nonfloating environment for listings. All font selection and indention must
be done by hand. However, it’s useful if you have another tool doing that work,
e.g. LGrind.
alg provides essentially the same functionality as algorithms. So read the next
paragraph and note that the syntax will be different.

9algorithms goes a quite different way. You describe an algorithm and the package
formats it, for example
if i ≤ 0 theni←1
else
if i ≥ 0 theni←0
end ifend if%\begin{algorithmic}%\IF{$i\leq0$}%\STATE $i\gets1$%\ELSE\IF{$i\geq0$}%\STATE $i\gets0$%\ENDIF\ENDIF%\end{algorithmic}

As this example shows, you get a good looking algorithm even from a bad looking
input. The package provides a lot more constructs like for-loops, while-loops, orcomments. You can request line numbers, ‘ruled’, ‘boxed’ and floating algorithms,
a list of algorithms, and you can customize the terms if, then, and so on.
pretprin is a package for pretty-printing texts in formal languages—as the title in
TUGboat, Volume 19 (1998), No. 3 states. It provides environments which prettyprint and format the source code. Analyzers for Pascal and Prolog are defined;
adding other languages is easy—if you are or get a bit familiar with automatonsand formal languages.
alltt defines an environment similar to verbatim except that \, { and } havetheir usual meanings. This means that you can use commands in the verbatims,
e.g. select different fonts or enter math mode.
moreverb requires verbatim and provides verbatim output to a file, ‘boxed’ verbatims and line numbers.
verbatim defines an improved version of the standard verbatim environment anda command to input files verbatim.
fancyvrb is, roughly speaking, a superset of alltt, moreverb, and verbatim, butmany more parameters control the output. The package provides frames, line
numbers on the left or on the right, automatic line breaking (difficult), and more.
For example, an interface to listings exists, i.e. you can pretty-print source code
automatically. The package fvrb-ex builds on fancyvrb and defines environments
to present examples similar to the ones in this guide.

2

The next steps

Now, before actually using the listings package, you should really read the software
license. It does not cost much time and provides information you probably needto know.

2.1

Software license

The files listings.dtx and listings.ins and all files generated from only
these two files are referred to as ‘the listings package’ or simply ‘the package’.
lstdrvrs.dtx and the files generated from that file are ‘drivers’.
Copyright The listings package is copyright 1996–2004 Carsten Heinz, and copyright 2006 Brooks Moses. The drivers are copyright any individual author listed
in the driver files.
10Distribution and modification The listings package and its drivers may be
distributed and/or modified under the conditions of the LaTeX Project Public
License, either version 1.3c of this license or (at your option) any later version.
The latest version of this license is in http://www.latex-project.org/lppl.txt andversion 1.3c or later is part of all distributions of LaTeX version 2003/12/01 or
later.
Contacts Read section 6 Troubleshooting on how to submit a bug report.
Send all other comments, ideas, and additional programming languages toj.hoffmann(at)fh-aachen.de using listings as part of the subject.

2.2

Package loading

As usual in LATEX, the package is loaded by \usepackage[⟨options⟩]{listings},
where [⟨options⟩] is optional and gives a comma separated list of options. Eacheither loads an additional listings aspect, or changes default properties. Usually
you don’t have to take care of such options. But in some cases it could be necessary:
if you want to compile documents created with an earlier version of this package
or if you use special features. Here’s an incomplete list of possible options.
→ Where is a list of all of the options?
In the developer’s guide since they were introduced
to debug the package more easily. Read section 8 on how to get that guide.

0.21
invokes a compatibility mode for compiling documents written for listingsversion 0.21.
draft
The package prints no stand alone files, but shows the captions and defines
the corresponding labels. Note that a global \documentclass-option draft
is recognized, so you don’t need to repeat it as a package option.
final
Overwrites a global draft option.
savememtries to save some of TEX’s memory. If you switch between languages often,
it could also reduce compile time. But all this depends on the particular
document and its listings.
Note that various experimental features also need explicit loading via options.
Read the respective lines in section 5.
After package loading it is recommend to load all used dialects of programming
languages with the following command. It is faster to load several languages with
one command than loading each language on demand.
\lstloadlanguages{⟨comma separated list of languages⟩}
Each language is of the form [⟨dialect⟩]⟨language⟩. Without the optional[⟨dialect⟩] the package loads a default dialect. So write ‘[Visual]C++’ if
you want Visual C++ and ‘[ISO]C++’ for ISO C++. Both together can beloaded by the command \lstloadlanguages{[Visual]C++,[ISO]C++}.
Table 1 on page 13 shows all defined languages and their dialects.
11

2.3

The key=value interface

This package uses the keyval package from the graphics bundle by David Carlisle.
Each parameter is controlled by an associated key and a user supplied value. For
example, firstline is a key and 2 a valid value for this key.
The command \lstset gets a comma separated list of “key=value” pairs. The
first list with more than a single entry is on page 5: firstline=2,lastline=5.
→ So I can write ‘\lstset{firstline=2,lastline=5}’ once for all?
No. ‘firstline’ and‘lastline’ belong to a small set of keys which are only used on individual listings. However,your command is not illegal—it has no effect. You have to use these keys inside the optional
argument of the environment or input command.
→ What’s about a better example of a key=value list?

There is one in section 1.3.

→ ‘language=[77]Fortran’ does not work inside an optional argument.
You must put
braces around the value if a value with optional argument is used inside an optional argument.
In the case here write ‘language={[77]Fortran}’ to select Fortran 77.
→ If I use the ‘language’ key inside an optional argument, the language isn’t active when I
typeset the next listing.
All parameters set via ‘\lstset’ keep their values up to theend of the current environment or group. Afterwards the previous values are restored. The
optional parameters of the two pretty-printing commands and the ‘lstlisting’ environment
take effect on the particular listing only, i.e. values are restored immediately. For example, you
can select a main language and change it for special listings.
→ \lstinline has an optional argument?
Yes. And from this fact comes a limitation:
you can’t use the left bracket ‘[’ as delimiter unless you specify at least an empty optional
argument as in ‘\lstinline[][var i:integer;[’. If you forget this, you will either get a“runaway argument” error from TEX, or an error message from the keyval package.

2.4

Programming languages

You already know how to activate programming languages—at least Pascal.
An optional parameter selects particular dialects of a language. For example,
language=[77]Fortran selects Fortran 77 and language=[XSC]Pascal does thesame for Pascal XSC. The general form is language=[⟨dialect⟩]⟨language⟩. If you
want to get rid of keyword, comment, and string detection, use language={} asan argument to \lstset or as optional argument.
Table 1 shows all predefined languages and dialects. Use the listed names as⟨language⟩ and ⟨dialect⟩, respectively. If no dialect or ‘empty’ is given in the table,
just don’t specify a dialect. Each underlined dialect is default; it is selected if you
leave out the optional argument. The predefined defaults are the newest language
versions or standard dialects.
→ How can I define default dialects?

Check section 4.3.4 for ‘defaultdialect’.

→ I have C code mixed with assembler lines. Can listings pretty-print such source code, i.e. highlight keywords and comments of both languages?
‘alsolanguage=[⟨dialect⟩]⟨language⟩’selects a language additionally to the active one. So you only have to write a language definition for your assembler dialect, which doesn’t interfere with the definition of C, say. Moreover
you might want to use the key ‘classoffset’ described in section 4.3.4.
→ How can I define my own language?
This is discussed in section 4.7. And if you thinkthat other people could benefit by your definition, you might want to send it to the addressin section 2.1. Then it will be published under the LATEX Project Public License.

Note that the arguments ⟨language⟩ and ⟨dialect⟩ are case insensitive and thatspaces have no effect.

12

Table 1: Predefined languages. Note that some definitions are preliminary, forexample HTML and XML. Each underlined dialect is the default dialect.
ABAP (R/2 4.3, R/2 5.0, R/3 3.1, R/3 4.6C, R/3 6.10)
ACM
ACMscript
ACSL
Ada (2005, 83, 95)
Algol (60, 68)
Ant
Assembler (Motorola68k, x86masm) Awk (gnu, POSIX)
bash
Basic (Visual)C (ANSI, Handel, Objective, Sharp)
C++ (11, ANSI, GNU, ISO, Visual) Caml (light, Objective)
CIL
Clean
Cobol (1974, 1985, ibm)
Comal 80
command.com (WinXP)
Comsolcsh
Delphi
EiffelElanelisperlangEuphoria
Fortran (03, 08, 18, 77, 90, 95)
GAP
GCL
GnuplotGo
hansl
HaskellHTML
IDL (empty, CORBA)
InformJava (empty, AspectJ)
JVMIS
ksh
Lingo
Lisp (empty, Auto)
LLVM
Logo
make (empty, gnu)
Lua (5.0, 5.1, 5.2, 5.3)
Mathematica (1.0, 11.0, 3.0, 5.2) Matlab (empty, 5.1)
Mercury
MetaPost
MirandaMizar
ML
Modula-2
MuPAD
NASTRANOberon-2
OCL (decorative, OMG)
OctaveOORexxOz
Pascal (Borland6, Standard, XSC)
Perl
PHP
PL/I
Plasm
PostScript
POV
PrologPromela
PSTricks
Python (2, 3)
R
ReduceRexx (empty, VM/XA)
RSL
Ruby
S (empty, PLUS)
SAS
Scala (empty, 3.0)
Scilabsh
SHELXL
Simula (67, CII, DEC, IBM)SPARQLSQL
Swift
tcl (empty, tk)
TeX (AlLaTeX, common, LaTeX, plain, primitive)
VBScript
Verilog
VHDL (empty, AMS)VRML (97)
XML
XSLT

13

There is at least one language (VDM, Vienna Development Language, https://en.wikipedia.org/wiki/Vienna_Development_Method1 ) which is not directly
supported by the listings package. It needs a package for its own: vdmlisting. On
the other hand vdmlisting uses the listings package and so it should be mentioned
in this context.
2.4.1

Preferences

Sometimes authors of language support provide their own configuration preferences. These may come either from their personal experience or from thesettings in an IDE and can be defined as a listings style. From version 1.5bof the listings package on these styles are provided as files with the namelistings-⟨language⟩.prf, ⟨language⟩ is the name of the supported programming
language in lowercase letters.
So if a user of the listings package wants to use these preferences, she/he cansay for example when using Python\input{listings-python.prf}
at the end of her/his listings.cfg configuration file as long as the filelistings-python.prf resides in the TEX search path. Of course that file canbe changed according to the user’s preferences.
At the moment there are five such preferences files:
1. listings-acm.prf
2. listings-bash.prf
3. listings-fortran.prf
4. listings-lua.prf
5. listings-python.prf
All contributors are invited to supply more personal preferences.

2.5

Special characters

Tabulators You might get unexpected output if your sources contain tabulators.
The package assumes tabulator stops at columns 9, 17, 25, 33, and so on. This ispredefined via tabsize=8. If you change the eight to the number n, you will get
tabulator stops at columns n + 1, 2n + 1, 3n + 1, and so on.

1 123456789
2{ one t a b u l a t o r }3{ two t a b s }4 123{ 123 + two t a b s }1 \lstset{tabsize=2}
2 \begin{lstlisting}3 123456789
4{ one tabulator }5{ two tabs }6 123{ 123 + two tabs }7 \end{lstlisting}

1 Vladimir Nikishkin informed that the previous mentioned URL http://www.vdmportal.org
doesn’t point to a VDM specific page anymore.

14

For better illustration, the left-hand side uses tabsize=2 but the verbatim codetabsize=4. Note that \lstset modifies the values for all following listings in
the same environment or group. This is no problem here since the examples aretypeset inside minipages. If you want to change settings for a single listing, use
the optional argument.
Visible tabulators and spaces One can make spaces and tabulators visible:

1
f o r i :=maxint to 0 do
2
begin
3 −−−→{ do n o t h i n g }4
end ;1 \lstset{showspaces=true,2
showtabs=true,3
tab=\rightarrowfill}
4 \begin{lstlisting}5
for i:=maxint to 0 do
6
begin
7
{ do nothing }8end;
9 \end{lstlisting}If you request showspaces but no showtabs, tabulators are converted to visible. So youspaces. The default definition of tab produces a ‘wide visible space’might want to use $\to$, $\dashv$ or something else instead.
→ Some sort of advice: (1) You should really indent lines of source code to make listings morereadable. (2) Don’t indent some lines with spaces and others via tabulators. Changing thetabulator size (of your editor or pretty-printing tool) completely disturbs the columns. (3) As
a consequence, never share your files with differently tab sized people!
→ To make the LATEX code more readable, I indent the environments’ program listings. How canI remove that indention in the output?
Read ‘How to gobble characters’ in section 8.

Form feeds Another special character is a form feed causing an empty line bydefault. formfeed=\newpage would result in a new page every form feed. Please
note that such definitions (even the default) might get in conflict with frames.
National characters If you type in such characters directly as characters ofcodes 128–255 and use them also in listings, let the package know it—or you’ll
get really funny results. extendedchars=true allows and extendedchars=false
prohibits listings from handling extended characters in listings. If you use them,
you should load fontenc, inputenc and/or any other package which defines thecharacters.
→ I have problems using inputenc together with listings.
This could be a compatibility
problem. Make a bug report as described in section 6 Troubleshooting.

The extended characters don’t cover Arabic, Chinese, Hebrew, Japanese, and soon—specifically, any encoding which uses multiple bytes per character.
Thus, if you use the a package that supports multibyte characters, such as
the CJK or ucs packages for Chinese and UTF-8 characters, you must avoid letting listings process the extended characters. It is generally best to also specify
extendedchars=false to avoid having listings get entangled in the other package’s
extended-character treatment.
If you do have a listing contained within a CJK environment, and want tohave CJK characters inside the listing, you can place them within a commentthat escapes to LATEX– see section 4.3.13 for how to do that. (If the listing is notinside a CJK environment, you can simply put a small CJK environment within
the escaped-to-LATEXportion of the comment.)
15

Similarly, if you are using UTF-8 extended characters in a listing, they must
be placed within an escape to LATEX.
Also, section 8 has a few details on how to work with extended characters in
the context of Λ.

2.6

Line numbers

You already know the keys numbers, numberstyle, stepnumber, and numbersep
from section 1.4. Here now we deal with continued listings. You have two options
to get consistent line numbering across listings.

f o r i :=maxint to 0 do
begin
102
{ do n o t h i n g }
end ;
100

And we continue the listing:106

Write ( ’ Case i n s e n s i t i v e ’ ) ;WritE( ’ P a s c a l keywords . ’ ) ;1 \begin{lstlisting}[firstnumber=100]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6
7 \end{lstlisting}
8 And we continue the listing:
9 \begin{lstlisting}[firstnumber=last]
10 Write(’Case insensitive ’);
11 WritE(’Pascal keywords.’);
12 \end{lstlisting}In the example, firstnumber is initially set to 100; some lines later the value islast, which continues the numbering of the last listing. Note that the empty line
at the end of the first part is not printed here, but it counts for line numbering.
You should also notice that you can write \lstset{firstnumber=last} once andget consecutively numbered code lines—except you specify something different fora particular listing.
On the other hand you can use firstnumber=auto and name your listings.
Listings with identical names (case sensitive!) share a line counter.

f o r i :=maxint to 0 do
begin
{ do n o t h i n g }4 end ;
2

And we continue the listing:6

Write ( ’ Case i n s e n s i t i v e ’ ) ;WritE( ’ P a s c a l keywords . ’ ) ;1 \begin{lstlisting}[name=Test]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6
7 \end{lstlisting}
8 And we continue the listing:
9 \begin{lstlisting}[name=Test]
10 Write(’Case insensitive ’);
11 WritE(’Pascal keywords.’);
12 \end{lstlisting}

The next Test listing goes on with line number 8, no matter whether there areother listings in between.
You can also select the lines to be printed, the options ‘linerange’ and‘consecutivenumbers’ are your friend. In a presentation for example you don’t
need comments for your programs, so you prefer the line numbers being consecutively numbered, but the results should reflect the behaviour of the program—you16

omit parts of the lengthy output. So you may have the following program and its
results.

1
2#include <s t d i o . h>#include < s t d l i b . h>

3

↶

↶

↶↶

2

no .
no .
no .
no .

1
2
6
7

↷↷

Line
Line
6 Line7 Line1↷

And these are the results:↷

i n t main ( i n t argc , char∗ argv[]){
5
int i ;
6
int l i m i t ;7
i f ( argc > 1 ) {8
l i m i t = a t o i ( argv [ 1 ] ) ;9} else {10limit = 100;
11}12
f o r ( i = 1 ; i <= l i m i t ; i ++){13
p r i n t f ( ” L i n e no . %3.0d\n
”, i)
;
14
}
15
return 0 ;16 }4

1 \begin{lstlisting}[name=Test,
2
language={[ansi]C},3linerange={1-4,6-7,10-14,
4
17-19,21-22},
5
firstnumber=1]
6 #include <stdio.h>
7 #include <stdlib.h>89 int main(int argc,char* argv[]){10/* declaring variables */11
int i;
12
int limit;
13
14/* checking arguments */15
if ( argc > 1 ) {16
limit = atoi(argv[1]);17} else {18
limit = 100;
19
}
20
21
/* counting lines */22
for (i = 1;i <= limit;i++) {23
printf("Line no. %3.0d\n", i);
24
}
25
26
return 0;27 }28
29 \end{lstlisting}
30 And these are the results:
31 \begin{lstlisting}[language={},32
linerange={1-2,6-7},
33
consecutivenumbers=false]
34 Line no.
1
35 Line no.
2
36 Line no.
3
37 Line no.
4
38 Line no.
5
39 Line no.
6
40 Line no.
7
41 \end{lstlisting}→ Okay. And how can I get decreasing line numbers?
Sorry, what?
Decreasing line
numbers as on page 36.
May I suggest to demonstrate your individuality by other means?
If you differ, you should try a negative ‘stepnumber’ (together with ‘firstnumber’).

Read section 8 on how to reference line numbers.

2.7

Layout elements

It’s always a good idea to structure the layout by vertical space, horizontal lines,
or different type sizes and typefaces. The best to stress whole listings are—not all17

at once—colours, frames, vertical space, and captions. The latter are also good torefer to listings, of course.
Vertical space The keys aboveskip and belowskip control the vertical space
above and below displayed listings. Both keys get a dimension or skip as value
and are initialized to \medskipamount.
Frames The key frame takes the verbose values none, leftline, topline,
bottomline, lines (top and bottom), single for single frames, or shadowbox.
1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;

1 \begin{lstlisting}[frame=single]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6 \end{lstlisting}→ The rules aren’t aligned.
This could be a bug of this package or a problem with your .dvi
driver. Before sending a bug report to the package author, modify the parameters described in
section 4.3.10 heavily. And do this step by step! For example, begin with ‘framerule=10mm’.
If the rules are misaligned by the same (small) amount as before, the problem does not comefrom the rule width. So continue with the next parameter. Also, Adobe Acrobat sometimes
has single-pixel rounding errors which can cause small misalignments at the corners when PDF
files are displayed on screen; these are unfortunately normal.

Alternatively you can control the rules at the top, right, bottom, and left directly
by using the four initial letters for single rules and their upper case versions fordouble rules.
1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;

1 \begin{lstlisting}[frame=trBL]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6 \end{lstlisting}Note that a corner is drawn if and only if both adjacent rules are requested. Youmight think that the lines should be drawn up to the edge, but what’s about roundcorners? The key frameround must get exactly four characters as value. The firstcharacter is attached to the upper right corner and it continues clockwise. ‘t’ ascharacter makes the corresponding corner round.


1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;



1 \lstset{frameround=fttt}
2 \begin{lstlisting}[frame=trBL]
3 for i:=maxint to 0 do
4 begin5{ do nothing } 6 end;
7 \end{lstlisting}Note that frameround has been used together with \lstset and thus the value
affects all following listings in the same group or environment. Since the listing is
inside a minipage here, this is no problem.
→ Don’t use frames all the time, and in particular not with short listings. This would emphasize
nothing. Use frames for 10% or even less of your listings, for your most important ones.

18

→ If you use frames on floating listings, do you really want frames?
No, I want to separate
floats from text.
Then it is better to redefine LATEX’s ‘\topfigrule’ and ‘\botfigrule’.
For example, you could write ‘\renewcommand*\topfigrule{\hrule\kern-0.4pt\relax}’
and make the same definition for \botfigrule.

Captions Now we come to caption and label. You might guess (correctly) thatthey can be used in the same manner as LATEX’s \caption and \label commands,
although here it is also possible to have a caption regardless of whether or not thelisting is in a float:2
1 \begin{lstlisting}[caption={Useless code},label=useless]2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6 \end{lstlisting}

Listing 2: Useless code
1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;

Afterwards you could refer to the listing via \ref{useless}. By default such alisting gets an entry in the list of listings, which can be printed with the command\lstlistoflistings. The key nolol suppresses an entry for both the environment or the input command. Moreover, you can specify a short caption for thelist of listings: caption={[⟨short⟩]⟨long⟩}. Note that the whole value is enclosed
in braces since an optional value is used in an optional argument.
If you don’t want the label Listing plus number, you should use title:
1 \begin{lstlisting}[title={‘Caption’ without label}]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6 \end{lstlisting}‘Caption’ without label
1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;
→ Something goes wrong with ‘title’ in my document: in front of the title is a delimiter.
The result depends on the document class; some are not compatible. Contact the package
author for a work-around.
2 You should keep in mind that according to [Mi04] . . . if the caption’s text fits on one line,
the text is centered; if the text does not fit on a single line, it will be typeset as a paragraphwith a width equal to the line width.

19

Colours One more element. You need the color package and can then request
coloured background via backgroundcolor=⟨color command⟩.
→ Great! I love colours.
striking styles on page 7.

Fine, yes, really. And I like to remind you of the warning about

1 \lstset{backgroundcolor=\color{yellow}}

1 f o r i :=maxint to 0 do
2 begin3
j := s q u a r e ( r o o t ( i ) ) ;4 end ;

1 \begin{lstlisting}[frame=single,
2
framerule=0pt]
3 for i:=maxint to 0 do
4 begin5
j:=square(root(i));
6 end;
7 \end{lstlisting}

The example also shows how to get coloured space around the whole listing: usea frame whose rules have no width.

2.8

Emphasize identifiers

Recall the pretty-printing commands and environment. \lstinline prints codesnippets, \lstinputlisting whole files, and lstlisting pieces of code which
reside in the LATEX file. And what are these different ‘types’ of source code goodfor? Well, it just happens that a sentence contains a code fragment. Whole
files are typically included in or as an appendix. Nevertheless some books aboutprogramming also include such listings in normal text sections—to increase thenumber of pages. Nowadays source code should be shipped on disk or CD-ROM
and only the main header or interface files should be typeset for reference. So,
please, don’t misuse the listings package. But let’s get back to the topic.
Obviously ‘lstlisting source code’ isn’t used to make an executable programfrom. Such source code has some kind of educational purpose or even didactic.
→ What’s the difference between educational and didactic?
good or bad, true or false. Didactic is true by definition.

Something educational can be

Usually keywords are highlighted when the package typesets a piece of source code.
This isn’t necessary for readers who know the programming language well. The
main matter is the presentation of interface, library or other functions or variables.
If this is your concern, here come the right keys. Let’s say, you want to emphasize
the functions square and root, for example, by underlining them. Then you could
do it like this:
1 \lstset{emph={square,root},emphstyle=\underbar}

1 f o r i :=maxint to 0 do
2 begin3
j := s q u a r e ( r o o t ( i ) ) ;4 end ;

1 \begin{lstlisting}
2 for i:=maxint to 0 do
3 begin4
j:=square(root(i));
5 end;
6 \end{lstlisting}20

→ Note that the list of identifiers {square,root} is enclosed in braces. Otherwise the keyval
package would complain about an undefined key root since the comma finishes the key=value
pair. Note also that you must put braces around the value if you use an optional argument of a
key inside an optional argument of a pretty-printing command. Though it is not necessary, thefollowing example uses these braces. They are typically forgotten when they become necessary,

Both keys have an optional ⟨class number⟩ argument for multiple identifier
lists:
1 \lstset{emph={square},emphstyle=\color{red},2emph={[2]root,base},emphstyle={[2]\color{blue}}}

1 f o r i :=maxint to 0 do
2 begin3
j := s q u a r e ( r o o t ( i ) ) ;4 end ;

1 \begin{lstlisting}
2 for i:=maxint to 0 do
3 begin4
j:=square(root(i));
5 end;
6 \end{lstlisting}→ What is the maximal ⟨class number ⟩?
231 − 1 = 2 147 483 647. But TEX’s memory will
exceed before you can define so many different classes.

One final hint: Keep the lists of identifiers disjoint. Never use a keyword inan ‘emphasize’ list or one name in two different lists. Even if your source code ishighlighted as expected, there is no guarantee that it is still the case if you change
the order of your listings or if you use the next release of this package.

2.9

Indexing

Indexing is just like emphasizing identifiers—I mean the usage:
1 \lstset{index={square},index={[2]root}}

1 f o r i :=maxint to 0 do
2 begin3
j := s q u a r e ( r o o t ( i ) ) ;4 end ;

1 \begin{lstlisting}
2 for i:=maxint to 0 do
3 begin4
j:=square(root(i));
5 end;
6 \end{lstlisting}

Of course, you can’t see anything here. You will have to look at the index.
→ Why is the ‘index’ key able to work with multiple identifier lists?
This question is strongly
related to the ‘indexstyle’ key. Someone might want to create multiple indexes or want toinsert prefixes like ‘constants’, ‘functions’, ‘keywords’, and so on. The ‘indexstyle’ key
works like the other style keys except that the last token must take an argument, namely the(printable form of the) current identifier.
You can define ‘\newcommand\indexkeywords[1]{\index{keywords, #1}}’ and make similar definitions for constant or function names. Then ‘indexstyle=[1]\indexkeywords’
might meet your purpose. This becomes easier if you want to create multiple indexes with
the index package. If you have defined appropriate new indexes, it is possible to write‘indexstyle=\index[keywords]’, for example.
→ Let’s say, I want to index all keywords. It would be annoying to type in all the keywords again,
specifically if the used programming language changes frequently.
Just read ahead.

21

The index key has in fact two optional arguments. The first is the well-known⟨class number⟩, the second is a comma separated list of other keyword classes
whose identifiers are indexed. The indexed identifiers then change automaticallywith the defined keywords—not automagically, it’s not an illusion.
Eventually you need to know the names of the keyword classes. It’s usually the
key name followed by a class number, for example, emph2, emph3, . . . , keywords2
or index5. But there is no number for the first order classes keywords, emph,
directives, and so on.
→ ‘index=[keywords]’ does not work.
The package can’t guess which optional argument
you mean. Hence you must specify both if you want to use the second one. You should try‘index=[1][keywords]’.

2.10

Fixed and flexible columns

The first thing a reader notices—except different styles for keywords, etc.—is thecolumn alignment. Arne John Glenstrup invented the flexible column format in1997. Since then some efforts were made to develop this branch farther. Currently
four column formats are provided: fixed, flexible, space-flexible, and full flexible.
Take a close look at the following examples.
columns=
1
2
3
4

WOMEN

are
MEN
WOMEN arebetter MEN

fixed(at 0.6em)

flexible(at 0.48em)

fullflexible(at 0.48em)

1 WOMEN a r e
2MEN
3 WOMEN a r e
4 b e t t e r MEN

1 WOMEN are
2MEN
3 WOMEN are
4 better MEN

1 WOMEN are
2MEN
3 WOMEN are
4 better MEN→ Why are women better men?
Do you want to philosophize? Well, have I ever said thatthe statement “women are better men” is true? I can’t even remember this about “womenare men” . . . .

In the abstract one can say: The fixed column format ruins the spacing intended by
the font designer, while the flexible formats ruin the column alignment (possibly)
intended by the programmer. Common to all is that the input characters aretranslated into a sequence of basic output units like
1 i f
2

x=y

then
e l s ew r i t e ( ’ a l i g n ’ )p r i n t ( ’ a l i g n ’ ) ;Now, the fixed format puts n characters into a box of width n × ‘base width’,
where the base width is 0.6em in the example. The format shrinks and stretches
the space between the characters to make them fit the box. As shown in theexample, some character strings look b a d or worse, but the output is verticallyaligned.
If you don’t need or like this, you should use a flexible format. All characters
are typeset at their natural width. In particular, they never overlap. If a word
requires more space than reserved, the rest of the line simply moves to the right.
The difference between the three formats is that the full flexible format cares
about nothing else, while the normal flexible and space-flexible formats try to fix
the column alignment if a character string needs less space than ‘reserved’. The
normal flexible format will insert make-up space to fix the alignment at spaces,
22

before and after identifiers, and before and after sequences of other characters; thespace-flexible format will only insert make-up space by stretching existing spaces.
In the flexible example above, the two MENs are vertically aligned since somespace has been inserted in the fourth line to fix the alignment. In the full flexible
format, the two MENs are not aligned.
Note that both flexible modes printed the two blanks in the first line as asingle blank, but for different reasons: the normal flexible format fixes the columnalignment (as would the space-flexible format), and the full flexible format doesn’tcare about the second space.

3

Advanced techniques

3.1

Style definitions

It is obvious that a pretty-printing tool like this requires some kind of language
selection and definition. The first has already been described and the latter isconvered by the next section. However, it is very convenient to have the same forprinting styles: at a central place of your document they can be modified easily
and the changes take effect on all listings.
Similar to languages, style=⟨style name⟩ activates a previously defined style.
A definition is as easy: \lstdefinestyle{⟨style name⟩}{⟨key=value list⟩}. Keys
not used in such a definition are untouched by the corresponding style selection,of course. For example, you could write%%%%\lstdefinestyle{numbers}{numbers=left, stepnumber=1, numberstyle=\tiny, numbersep=10pt}\lstdefinestyle{nonumbers}{numbers=none}and switch from listings with line numbers to listings without ones and vice versa
simply by style=nonumbers and style=numbers, respectively.
→ You could even write ‘\lstdefinestyle{C++}{language=C++,style=numbers}’. Style andlanguage names are independent of each other and so might coincide. Moreover it is possible
to activate other styles.
→ It’s easy to crash the package using styles. Write ’\lstdefinestyle{crash}{style=crash}’and ’\lstset{style=crash}’. TEX’s capacity will exceed, sorry [parameter stack size]. Only
bad boys use such recursive calls, but only good girls use this package. Thus the problem isof minor interest.

3.2

Language definitions

These are like style definitions except for an optional dialect name and an optionalbase language—and, of course, a different command name and specialized keys.
In the simple case it’s \lstdefinelanguage{⟨language name⟩}{⟨key=value list⟩}.
For many programming languages it is sufficient to specify keywords and standard
function names, comments, and strings. Let’s look at an example.
1 \lstdefinelanguage{rock}2{morekeywords={one,two,three,four,five,six,seven,eight,
3nine,ten,eleven,twelve,o,clock,rock,around,the,tonight},
4
sensitive=false,5
morecomment=[l]{//},

23

6
7
8

}

morecomment=[s]{/*}{*/},
morestring=[b]",There isn’t much to say about keywords. They are defined like identifiers you wantto emphasize. Additionally you need to specify whether they are case sensitive
or not. And yes: you could insert [2] in front of the keyword one to define the
keywords as ‘second order’ and print them in keywordstyle={[2]...}.
→ I get a ‘Missing = inserted for \ifnum’ error when I select my language.
Did youforget the comma after ‘keywords={...}’? And if you encounter unexpected characters after
selecting a language (or style), you have probably forgotten a different comma or you havegiven to many arguments to a key, for example, morecomment=[l]{--}{!}.

So let’s turn to comments and strings. Each value starts with a mandatory[⟨type⟩] argument followed by a changing number of opening and closing delimiters. Note that each delimiter (pair) requires a key=value on its own, even if
types are equal. Hence, you’ll need to insert morestring=[b]’ if single quotes
open and close string or character literals in the same way as double quotes do in
the example.
Eventually you need to know the types and their numbers of delimiters. The
reference guide contains full lists, here we discuss only the most common. For
strings these are b and d with one delimiter each. This delimiter opens and closes
the string and inside a string it is either escaped by a backslash or it is doubled.
The comment type l requires exactly one delimiter, which starts a comment on
any column. This comment goes up to the end of line. The other two mostcommon comment types are s and n with two delimiters each. The first delimiter
opens a comment which is terminated by the second delimiter. In contrast to thes-type, n-type comments can be nested.
1 \lstset{morecomment=[l]{//},
2
morecomment=[s]{/*}{*/},
3
morecomment=[n]{(*}{*)},
4
morestring=[b]",5
morestring=[d]’}1 ” s t r \” i n g ”
not a s t r i n g
2 ’ s t r ’ ’ ing ’
not a s t r i n g
3 // comment l i n e
4 /∗ comment/∗ ∗/ not a comment
5 (∗ n e s t e d (∗ ∗) s t i l l comment
6comment ∗) not a comment

1 \begin{lstlisting}2 "str\"ing "not a string
3 ’str’’ing ’
not a string
4 // comment line
5 /* comment/**/ not a comment
6 (* nested (**) still comment
7comment *) not a comment
8 \end{lstlisting}→ Is it that easy?
Almost. There are some troubles you can run into. For example, if ‘-*’starts a comment line and ‘-*-’ a string (unlikely but possible), then you must define theshorter delimiter first. Another problem: by default some characters are not allowed inside
keywords, for example ‘-’, ‘:’, ‘.’, and so on. The reference guide covers this problem byintroducing some more keys, which let you adjust the standard character table appropriately.
But note that white space characters are prohibited inside keywords.

Finally remember that this section is only an introduction to language definitions.
There are more keys and possibilities.

24

3.3

Delimiters

You already know two special delimiter classes: comments and strings. However,their full syntax hasn’t been described so far. For example, commentstyle applies
to all comments—unless you specify something different. The optional [⟨style⟩]
argument follows the mandatory [⟨type⟩] argument.
1 \lstset{morecomment=[l][keywordstyle]{//},
2
morecomment=[s][\color{white}]{/*}{*/}}

1 // bold comment l i n e
2 a s i n g l e /∗ comment ∗/1 \begin{lstlisting}2 // bold comment line
3 a single /* comment */4 \end{lstlisting}As you can see, you have the choice between specifying the style explicitly by LATEX
commands or implicitly by other style keys. But, you’re right, some implicitly
defined styles have no separate keys, for example the second order keyword style.
Here—and never with the number 1—you just append the order to the base key:
keywordstyle2.
You ask for an application? Here you are: one can define different printing
styles for ‘subtypes’ of a comment, for example
1 \lstset{morecomment=[s][\color{blue}]{/*+}{*/},
2
morecomment=[s][\color{red}]{/*-}{*/}}

1 /∗ normal comment ∗/2 /∗+keep c o o l∗/
3 /∗−danger !
∗/1 \begin{lstlisting}
2 /* normal comment */3 /*+keep cool*/
4 /*danger!
*/
5 \end{lstlisting}Here, the comment style is not applied to the second and third line.
→ Please remember that both ‘extra’ comments must be defined after the normal comment,
since the delimiter ‘/*’ is a substring of ‘/*+’ and ‘/*-’.
→ I have another question. Is ‘language=⟨different language⟩’ the only way to remove such additional delimiters?
Call deletecomment and/or deletestring with the same arguments
to remove the delimiters (but you don’t need to provide the optional style argument).

Eventually, you might want to use the prefix i on any comment type. Then thecomment is not only invisible, it is completely discarded from the output!
1 \lstset{morecomment=[is]{/*}{*/}}

1 begin end
2 beginend

1 \begin{lstlisting}2 begin /* comment */ end
3 begin/* comment */end
4 \end{lstlisting}Okay, and now for the real challenges. More general delimiters can be definedby the key moredelim. Legal types are l and s. These types can be preceded by
an i, but this time only the delimiters are discarded from the output. This way
you can select styles by markers.
25

1 \lstset{moredelim=[is][\ttfamily]{|}{|}}

1 roman typewriter

1 \begin{lstlisting}
2 roman |typewriter|
3 \end{lstlisting}

You can even let the package detect keywords, comments, strings, and other delimiters inside the contents.
1 \lstset{moredelim=*[s][\itshape]{/*}{*/}}

1 /∗ begin
2(∗ comment ∗)3’ s t r i n g ’ ∗/1 \begin{lstlisting}
2 /* begin
3(* comment *)4’ string ’ */5 \end{lstlisting}Moreover, you can force the styles to be applied cumulatively.
1 \lstset{moredelim=**[is][\ttfamily]{|}{|}, % cumulative2
moredelim=*[s][\itshape]{/*}{*/}} % not so

1 /∗ begin2’ string ’
3
typewriter ∗/45 begin6 ’␣ string ␣ ’
7 /* typewriter */1 \begin{lstlisting}
2 /* begin3’ string ’
4|typewriter| */5
6 | begin
7 ’ string ’
8 /*typewriter*/ |9 \end{lstlisting}Look carefully at the output and note the differences. The second begin is notprinted in bold typewriter type since standard LATEX has no such font.
This suffices for an introduction. Now go and find some more applications.

3.4

Closing and credits

You’ve seen a lot of keys but you are far away from knowing all of them. The next
step is the real use of the listings package. Please take the following advice. Firstly,
look up the known commands and keys in the reference guide to get a notion of
the notation there. Secondly, poke around with these keys to learn some otherparameters. Then, hopefully, you’ll be prepared if you encounter any problems orneed some special things.
→ There is one question ‘you’ haven’t asked all the last pages: who is to blame. Carsten Heinz
wrote the guides, coded the listings package and wrote some language drivers. Brooks Moses
took over the maintaining for several years, Jobst Hoffmann currently maintains the package.
Other people defined more languages or contributed their ideas; many others made bug reports,
but only the first bug finder is listed. Special thanks go to (alphabetical order)
Hendri Adriaens, Andreas Bartelt, Jan Braun, Denis Girou, Arne John Glenstrup,Frank Mittelbach, Rolf Niepraschk, Rui Oliveira, Jens Schwarzer, andBoris Veytsman.

26

Moreover we wish to thankNasser M. Abbasi, Bjørn Ådlandsvik, Omair-Inam Abdul-Matin,
Gaurav Aggarwal, Jason Alexander, Andrei Alexandrescu, Holger Arndt,
Donald Arseneau, David Aspinall, Frank Atanassow, Claus Atzenbeck,Michael Bachmann, Luca Balzerani, Peter Bartke (big thankyou),
Jean-Yves Baudais, Heiko Bauke, Oliver Baum, Ralph Becket,
Andres Becerra Sandoval, Kai Below, Matthias Bethke, Javier Bezos,
Olaf Trygve Berglihn, Karl Berry, Geraint Paul Bevan, Peter Biechele,
Beat Birkhofer, Frédéric Boulanger, Byron K. Boulton, Joachim Breitner,
Martin Brodbeck, Walter E. Brown, Achim D. Brucker, Ján Buša,Thomas ten Cate, David Carlisle, Bradford Chamberlain, Brian Christensen,
Neil Conway, Patrick Cousot, Xavier Crégut, Christopher Creutzig,
Holger Danielsson, Andreas Deininger, Robert Denham, Detlev Dröge,
Anders Edenbrandt, Mark van Eijk, Norbert Eisinger, Brian Elmegaard,
Jon Ericson, Luc Van Eycken Thomas Esser, Chris Edwards, David John Evans,
Tanguy Fautré, Ulrike Fischer, Robert Frank, Michael Franke,
Ignacio Fernández Galván, Martine Gautier Daniel Gazard, Daniel Gerigk,
Dr. Christoph Giess, KP Gores, Adam Grabowski, Jean-Philippe Grivet,
Christian Gudrian, Jonathan de Halleux, Carsten Hamm, Martina Hansel,
Harald Harders, Christian Haul, Aidan Philip Heerdegen, Jim Hefferon,
Heiko Heil, Jürgen Heim, Martin Heller, Stephan Hennig, Alvaro Herrera,Richard Hoefter, Dr. Jobst Hoffmann, Torben Hoffmann, Morten Høgholm,
Berthold Höllmann, Gérard Huet, Hermann Hüttler, Ralf Imhäuser,
R. Isernhagen, Oldrich Jedlicka, Dirk Jesko, Loı̈c Joly, Christian Kaiser,
Bekir Karaoglu, Marcin Kasperski, Christian Kindinger, Steffen Klupsch,
Markus Kohm, Peter Köller (big thankyou), Reinhard Kotucha, Stefan Lagotzki,
Tino Langer, Rene H. Larsen, Olivier Lecarme, Thomas Leduc, Qing Lee,
Dr. Peter Leibner, Thomas Leonhardt (big thankyou), Magnus Lewis-Smith,
Knut Lickert, Benjamin Lings, Dan Luecking, Peter Löffler, Markus Luisser,
Kris Luyten, José Romildo Malaquias, Andreas Matthias, Patrick TJ McPhee,
Riccardo Murri, Knut Müller, Svend Tollak Munkejord, Gerd Neugebauer,
Torsten Neuer, Enzo Nicosia, Michael Niedermair, Xavier Noria, Heiko Oberdiek,
Xavier Olive, Alessio Pace, Markus Pahlow, Morten H. Pedersen, Xiaobo Peng,
Zvezdan V. Petkovic, Michael Piefel, Michael Piotrowski, Manfred Piringer,
Ivo Pletikosić, Vincent Poirriez, Adam Prugel-Bennett, Ralf Quast,
Aslak Raanes, Venkatesh Prasad Ranganath, Tobias Rapp, Jeffrey Ratcliffe,
Georg Rehm, Fermin Reig, Detlef Reimers, Stephen Reindl, Franz Rinnerthaler,Peter Ruckdeschel, Magne Rudshaug, Jonathan Sauer, Vespe Savikko,
Mark Schade, Gunther Schmidl, Andreas Schmidt, Walter Schmidt,
Christian Schneider, Jochen Schneider, Sven Schreiber, Benjamin Schubert,
Sebastian Schubert, Uwe Siart, Axel Sommerfeldt, Richard Stallman,
Nigel Stanger, Martin Steffen, Andreas Stephan, Stefan Stoll, Enrico Straube,
Werner Struckmann, Martin Süßkraut, Gabriel Tauro, Winfried Theis,Jens T. Berger Thielemann, William Thimbleby, Arnaud Tisserand,
Jens Troeger, Kalle Tuulos, Gregory Van Vooren, Timothy Van Zandt,Jörg Viermann, Thorsten Vitt, Herbert Voss (big thankyou), Edsko de Vries,
Herfried Karl Wagner, Dominique de Waleffe, Bernhard Walle, Jared Warren,
Michael Weber, Sonja Weidmann, Andreas Weidner, Herbert Weinhandl,
Robert Wenner, Michael Wiese, James Willans, Jörn Wilms, Kai Wollenweber,
Ulrich G. Wortmann, Cameron H.G. Wright, Joseph Wright, Andrew Zabolotny,
and Florian Zähringer.
There are probably other people who contributed to this package. If I’ve missed your name,send an email.

27

Reference guide4Main referenceYour first training is completed. Now that you’ve left the User’s guide, the friend
telling you what to do has gone. Get more practice and become a journeyman!
→ Actually, the friend hasn’t gone. There are still some advices, but only from time to time.

4.1

How to read the reference

Commands, keys and environments are presented as follows.
hints

command, environment or key with ⟨parameters⟩

default

This field contains the explanation; here we describe the other fields.
If present, the label in the left margin provides extra information: ‘addon’
indicates additionally introduced functionality, ‘changed’ a modified key,‘data’ a command just containing data (which is therefore adjustable via\renewcommand), and so on. Some keys and functionality are ‘bug’-marked
or with a †-sign. These features might change in future or could be removed,
so use them with care.
If there is verbatim text touching the right margin, it is the predefined value.
Note that some keys default to this value every listing, namely the keys which
can be used on individual listings only.
Regarding the parameters, please keep in mind the following:
1. A list always means a comma separated list. You must put braces aroundsuch a list. Otherwise you’ll get in trouble with the keyval package; it complains about an undefined key.
2. You must put parameter braces around the whole value of a key if you usean [⟨optional argument⟩] of a key inside an optional [⟨key=value list⟩]:\begin{lstlisting}[caption={[one]two}].
3. Brackets ‘[ ]’ usually enclose optional arguments and must be typed inverbatim. Normal brackets ‘[ ]’ always indicate an optional argument andmust not be typed in. Thus [*] must be typed in exactly as is, but [*] justgets * if you use this argument.
4. A vertical rule indicates an alternative, e.g. ⟨true|false⟩ allows either trueor false as arguments.
5. If you want to enter one of the special characters {}#%\, this character mustbe escaped with a backslash. This means that you must write \} for the
single character ‘right brace’—but of course not for the closing paramater
character.

28

4.2

Typesetting listings\lstset{⟨key=value list⟩}sets the values of the specified keys, see also section 2.3. The parameters
keep their values up to the end of the current group. In contrast, all optional⟨key=value list⟩s below modify the parameters for single listings only.
\lstinline[⟨key=value list⟩]⟨character⟩⟨source code⟩⟨same character⟩works like \verb but respects the active language and style. These listings use flexible columns unless requested differently in the optional argument, and do not support frames or background colors. You can write‘\lstinline!var i:integer;!’ and get ‘var i : integer;’.
Since the command first looks ahead for an optional argument, you must
provide at least an empty one if you want to use [ as ⟨character⟩.
† An experimental implementation has been done to support the syntax\lstinline[⟨key=value list⟩]{⟨source code⟩}. Try it if you want and reportsuccess and failure. A known limitation is that inside another argument thelast source code token must not be an explicit space token—and, of course,
using a listing inside another argument is itself experimental, see section 5.1.
Another limitation is that this feature can’t be used in cells of a tabularenvironment. See section 7.1 for a workaround.
See also section 4.6 for commands to create short analogs for the \lstinline
command.
\begin{lstlisting}[⟨key=value list⟩]\end{lstlisting}typesets the code in between as a displayed listing.
In contrast to the environment of the verbatim package, LATEX code on thesame line and after the end of environment is typeset respectively executed.
\lstinputlisting[⟨key=value list⟩]{⟨file name⟩}
typesets the stand alone source code file as a displayed listing.

4.3

Options

The following sections describe all the keys that can be used to influence theappearance of the listing.
4.3.1

Searching for files

inputpath=⟨path⟩{}defines the path, where the file given by ⟨file name⟩ resides.
inputpath overrules the TEXINPUTS environment variable, which means thata file residing on one of the paths given by TEXINPUTS isn’t found anymore,
if ⟨path⟩ isn’t part of TEXINPUTS.
inputpath set as option of \lstinputlisting overrules the value set by\lstset.
29

4.3.2

Space and placement

float=[*]⟨subset of tbph⟩

or

float

floatplacement

makes sense on individual displayed listings only and lets them float. The
argument controls where LATEX is allowed to put the float: at the top or
bottom of the current/next page, on a separate page, or here where thelisting is.
The optional star can be used to get a double-column float in a two-column
document.
floatplacement=⟨place specifiers⟩

tbp

is used as place specifier if float is used without value.
aboveskip=⟨dimension⟩\medskipamount

belowskip=⟨dimension⟩\medskipamountdefine the space above and below displayed listings.
†

lineskip=⟨dimension⟩

0pt

specifies additional space between lines in listings.
†

boxpos=⟨b|c|t⟩cSometimes the listings package puts a \hbox around a listing—or it couldn’t
be printed or even processed correctly. The key determines the verticalalignment to the surrounding material: bottom baseline, centered or top
baseline.
4.3.3

The printed range

print=⟨true|false⟩

or

print

true

controls whether an individual displayed listing is typeset. Even if set false,
the respective caption is printed and the label is defined.
Note: If the package is loaded without the draft option, you can use thiskey together with \lstset. In the other case the key can be used to typeset
particular listings despite using the draft option.
firstline=⟨number⟩1

lastline=⟨number⟩

9999999

can be used on individual listings only. They determine the physical input
lines used to print displayed listings.
linerange={⟨first1 ⟩-⟨last1 ⟩,⟨first2 ⟩-⟨last2 ⟩, and so on}
can be used on individual listings only. The given line ranges of the listing
are displayed. The intervals must be sorted and must not intersect.
In fact each part of the triplet ⟨first⟩-⟨last⟩ may be omitted. Omitting ⟨first⟩
or ⟨last⟩ means, that the range begins at line no. 1 and ends at ⟨last⟩ or
begins at ⟨first⟩ ends at the last line of the file, a single number means, thatthe range begins and ends at the line given by the number, whereas omitting⟨first⟩ or ⟨last⟩ means the range begins at line no. 1 and ends at the lastline of the file.
30

consecutivenumbers=⟨true|false⟩

orconsecutivenumberstrue

can be used on individual listings only. Its use makes sense only if also
linerange is used. The default (true) value means that the line numbering
for all lineranges happens to be consecutively, e g. 1, 2, 3,. . . . If it is set tofalse, different ranges get their own numbering (see sec. 2.6).
showlines=⟨true|false⟩orshowlines

false

If true, the package prints empty lines at the end of listings. Otherwise theselines are dropped (but they count for line numbering).
emptylines=[*]⟨number⟩sets the maximum of empty lines allowed. If there is a block of more than⟨number⟩ empty lines, only ⟨number⟩ ones are printed. Without the optionalstar, line numbers can be disturbed when blank lines are omitted; with thestar, the lines keep their original numbers.
gobble=⟨number⟩0

gobbles ⟨number⟩ characters at the beginning of each environment code line.
This key has no effect on \lstinline or \lstinputlisting.
Tabulators expand to tabsize spaces before they are gobbled. Code lines
with fewer than gobble characters are considered empty. Never indent theend of environment by more characters.
4.3.4

Languages and styles

Please note that the arguments ⟨language⟩, ⟨dialect⟩, and ⟨style name⟩ are caseinsensitive and that spaces have no effect.
style=⟨style name⟩{}activates the key=value list stored with \lstdefinestyle.
\lstdefinestyle{⟨style name⟩}{⟨key=value list⟩}stores the key=value list.
language=[⟨dialect⟩]⟨language⟩{}

activates a (dialect of a) programming language. The ‘empty’ default language detects no keywords, no comments, no strings, and so on; it may
be useful for typesetting plain text. If ⟨dialect⟩ is not specified, the packagechooses the default dialect, or the empty dialect if there is no default dialect.
Table 1 on page 13 lists all languages and dialects provided by lstdrvrs.dtx.
The predefined default dialects are underlined.
alsolanguage=[⟨dialect⟩]⟨language⟩
activates a (dialect of a) programming language in addition to the current
active one. Note that some language definitions interfere with each otherand are plainly incompatible; for instance, if one is case sensitive and theother is not.
Take a look at the classoffset key in section 4.3.5 if you want to highlightthe keywords of the languages differently.
31

defaultdialect=[⟨dialect⟩]⟨language⟩
defines ⟨dialect⟩ as default dialect for ⟨language⟩. If you have defined adefault dialect other than empty, for example defaultdialect=[iama]fool,
you can’t select the empty dialect, even not with language=[]fool.
Finally, here’s a small list of language-specific keys.
optional

printpod=⟨true|false⟩

false

prints or drops PODs in Perl.
renamed,optional

usekeywordsintag=⟨true|false⟩true

The package either use the first order keywords in tags or prints all identifiers
inside <> in keyword style.
optional

tagstyle=⟨style⟩{}determines the style in which tags and their content is printed.
optional

markfirstintag=⟨style⟩false

prints the first name in tags with keyword style.
optional

makemacrouse=⟨true|false⟩true

Make specific: Macro use of identifiers, which are defined as first order keywords, also prints the surrounding $( and ) in keyword style. e.g. you could
get $(strip $(BIBS)). If deactivated you get $(strip $(BIBS)).
4.3.5

Figure out the appearance

basicstyle=⟨basic style⟩{}is selected at the beginning of each listing. You could use \footnotesize,\small, \itshape, \ttfamily, or something like that. The last token of⟨basic style⟩ must not read any following characters.
identifierstyle=⟨style⟩{}commentstyle=⟨style⟩\itshape

stringstyle=⟨style⟩{}determines the style for non-keywords, comments, and strings. The last
token can be an one-parameter command like \textbf or \underbar.
addon

keywordstyle=[⟨number⟩][∗]⟨style⟩\bfseries

is used to print keywords. The optional ⟨number⟩ argument is the classnumber to which the style should be applied.
Add-on: If you use the optional star after the (optional) class number, thekeywords are printed uppercase — even if a language is case sensitive anddefines lowercase keywords only. Maybe there should also be an option forlowercase keywords . . .
deprecatedndkeywordstyle=⟨style⟩keywordstyleis equivalent to keywordstyle=2⟨style⟩.
32

classoffset=⟨number⟩0is added to all class numbers before the styles, keywords, identifiers, etc. areassigned. The example below defines the keywords directly; you could do it
indirectly by selecting two different languages.
1 \lstset{classoffset=0,2
morekeywords={one,three,five},keywordstyle=\color{red},3
classoffset=1,4
morekeywords={two,four,six},keywordstyle=\color{blue},
5classoffset=0}% restore default
1 \begin{lstlisting}
2 one two three
3 four five six
4 \end{lstlisting}

1 one two t h r e e
2 four f i v e six

addon,bug,optional
optional

texcsstyle=[*][⟨class number⟩]⟨style⟩keywordstyle

directivestyle=⟨style⟩keywordstyle

determine the style of TEX control sequences and directives. Note that thesekeys are present only if you’ve chosen an appropriate language.
The optional star of texcsstyle also highlights the backslash in front of thecontrol sequence name. Note that this option is set for all texcs lists.
Bug: texcs... interferes with other keyword lists. If, for example, emph
contains the word foo, then the control sequence \foo will show up inemphstyle.
emph=[⟨number⟩]{⟨identifier list⟩}
moreemph=[⟨number⟩]{⟨identifier list⟩}deleteemph=[⟨number⟩]{⟨identifier list⟩}
emphstyle=[⟨number⟩]{⟨style⟩}
respectively define, add or remove the ⟨identifier list⟩ from ‘emphasize class⟨number⟩’, or define the style for that class. If you don’t give an optional
argument, the package assumes ⟨number⟩ = 1.
These keys are described more detailed in section 2.8.
delim=[*[*]][⟨type⟩][[⟨style⟩]]⟨delimiter(s)⟩moredelim=[*[*]][⟨type⟩][[⟨style⟩]]⟨delimiter(s)⟩deletedelim=[*[*]][⟨type⟩]⟨delimiter(s)⟩define, add, or remove user supplied delimiters. (Note that this does notaffect strings or comments.)
In the first two cases ⟨style⟩ is used to print the delimited code (and thedelimiters). Here, ⟨style⟩ could be something like \bfseries or \itshape, or
it could refer to other styles via keywordstyle, keywordstyle2, emphstyle,etc.
33

Supported types are l and s, see the comment keys in section 3.2 for an
explanation. If you use the prefix i, i.e. il or is, the delimiters are notprinted, which is some kind of invisibility.
If you use one optional star, the package will detect keywords, comments,and strings inside the delimited code. With both optional stars, aditionallythe style is applied cumulatively; see section 3.3.
4.3.6

Getting all characters right

extendedchars=⟨true|false⟩or

extendedchars

true

allows or prohibits extended characters in listings, that means (national)
characters of codes 128–255. If you use extended characters, you shouldload fontenc and/or inputenc, for example.
inputencoding=⟨encoding⟩{}determines the input encoding. The usage of this key requires the inputenc
package; nothing happens if it’s not loaded.
upquote=⟨true|false⟩

false

determines whether the left and right quote are printed ‘’ (false) or `'(true). This key requires the textcomp package if true, for more information
have a look at page 62.
tabsize=⟨number⟩

8sets tabulator stops at columns ⟨number⟩+1, 2·⟨number⟩+1, 3·⟨number⟩+1,
and so on. Each tabulator in a listing moves the current column to the next
tabulator stop.
showtabs=⟨true|false⟩

false

, but
make tabulators visible or invisible. A visible tabulator looks likethat can be changed. If you choose invisible tabulators but visible spaces,
tabulators are converted to an appropriate number of spaces.
tab=⟨tokens⟩⟨tokens⟩ is used to print a visible tabulator. You might want to use $\to$,$\mapsto$, $\dashv$ or something like that instead of the strange default
definition.
showspaces=⟨true|false⟩
lets all blank spaces appear

false
or as blank spaces.

showstringspaces=⟨true|false⟩truelets blank spaces in strings appear

or as blank spaces.

formfeed=⟨tokens⟩\bigbreak

Whenever a listing contains a form feed, ⟨tokens⟩ is executed.

34

4.3.7

Line numbers

numbers=⟨none|left|right⟩

none

makes the package either print no line numbers, or put them on the left or
the right side of a listing.
stepnumber=⟨number⟩

1

All lines with “line number ≡ 0 modulo ⟨number⟩” get a line number. If you
turn line numbers on and off with numbers, the parameter stepnumber willkeep its value. Alternatively you can turn them off via stepnumber=0 andon with a nonzero number, and keep the value of numbers.
numberfirstline=⟨true|false⟩

false

The first line of each listing gets numbered (if numbers are on at all) even if
the line number is not divisible by stepnumber.
numberstyle=⟨style⟩{}determines the font and size of the numbers.
numbersep=⟨dimension⟩

10pt

is the distance between number and listing.
numberblanklines=⟨true|false⟩true

If this is set to false, blank lines get no printed line number.
firstnumber=⟨auto|last|⟨number⟩⟩

auto

auto lets the package choose the first number: a new listing starts withnumber one, a named listing continues the most recent same-named listing(see below), and a stand alone file begins with the number corresponding to
the first input line.
last continues the numbering of the most recent listing and ⟨number⟩ sets
it to the (logical) number.
name=⟨name⟩names a listing. Displayed environment-listings with the same name sharea line counter if firstnumber=auto is in effect.
data\thelstnumber\arabic{lstnumber}prints the lines’ numbers.
We show an example on how to redefine \thelstnumber. But if you test it, you
won’t get the result shown on the left.
1 \renewcommand*\thelstnumber{\oldstylenums{\the\value{lstnumber}}}35

1 \begin{lstlisting}[numbers=left,2
firstnumber=753]
3 begin { empty lines }
4
5
6
7
8
9
10 end; { empty lines }11 \end{lstlisting}753 begin { empty l i n e s }
752
751
750
749
748
747
746 end ; { empty l i n e s }→ The example shows a sequence n, n + 1, . . . , n + 7 of 8 three-digit figures such that thesequence contains each digit 0, 1, . . . , 9. But 8 is not minimal with that property. Find theminimal number and prove that it is minimal. How many minimal sequences do exist?
Now look at the generalized problem: Let k ∈ {1, . . . , 10} be given. Find the minimal numberm ∈ {1, . . . , 10} such that there is a sequence n, n + 1, . . . , n + m − 1 of m k-digit figures
which contains each digit {0, . . . , 9}. Prove that the number is minimal. How many minimal
sequences do exist?
If you solve this problem with a computer, write a TEX program!

4.3.8

Captions

In despite of LATEX standard behaviour, captions and floats are independent fromeach other here; you can use captions with non-floating listings.
title=⟨title text⟩
is used for a title without any numbering or label.
caption={[⟨short⟩]⟨caption text⟩}
The caption is made of \lstlistingname followed by a running number, aseparator, and ⟨caption text⟩. Either the caption text or, if present, ⟨short⟩
will be used for the list of listings.
label=⟨name⟩makes a listing referable via \ref{⟨name⟩}.
\lstlistoflistings
prints a list of listings. Each entry is with descending priority either the
short caption, the caption, the file name, or the name of the listing, see also
the key name in section 4.3.7. From version v1.10 of this package on thelist of listings can be prepared by means of the tocbasic package [Koh23,
Chapter 15], for more information have a look at page 62.
nolol=⟨true|false⟩

or

nolol

If true, the listing does not make it into the list of listings.
data\lstlistlistingname

Listings

The header name for the list of listings.
data\lstlistingname

Listing

The caption label for listings.
36

data

\lstlistingnamestyle{}customizes the style of the caption label for program listings in a simple way,something like \small, \bfseries or a combination of several commands.
If there is a need for a complete customization of the label (justification,
fonts, margins, . . . ), one should use the caption package by A. Sommerfeldt[Som11].
data\thelstlisting\arabic{lstlisting}prints the running number of the caption.
numberbychapter=⟨true|false⟩true

If true, and \thechapter exists, listings are numbered by chapter. Otherwise, they are numbered sequentially from the beginning of the document.
This key can only be used before \begin{document}.
\lstnameprints the name of the current listing which is either the file name or thename defined by the name key. This command can be used to define a caption
or title template, for example by \lstset{caption=\lstname}.
captionpos=⟨subset of tb⟩

t

specifies the positions of the caption: top and/or bottom of the listing.
abovecaptionskip=⟨dimension⟩\smallskipamount

belowcaptionskip=⟨dimension⟩\smallskipamountis the vertical space respectively above or below each caption.
4.3.9

Margins and line shape

linewidth=⟨dimension⟩\linewidthdefines the base line width for listings. The following three keys are taken
into account additionally.
xleftmargin=⟨dimension⟩

0pt

xrightmargin=⟨dimension⟩

0pt

The dimensions are used as extra margins on the left and right. Line numbers
and frames are both moved accordingly.
resetmargins=⟨true|false⟩

false

If true, indention from list environments like enumerate or itemize is reset,
i.e. not used.
breaklines=⟨true|false⟩or

breaklines

false

activates or deactivates automatic line breaking of long lines.
breakatwhitespace=⟨true|false⟩or

breakatwhitespace

false

If true, it allows line breaks only at white space.
prebreak=⟨tokens⟩{}
37

postbreak=⟨tokens⟩{}⟨tokens⟩ appear at the end of the current line respectively at the beginningof the next (broken part of the) line.
You must not use dynamic space (in particular spaces) since internally we use\discretionary. However \space is redefined to be used inside ⟨tokens⟩.
breakindent=⟨dimension⟩

20pt

is the indention of the second, third, . . . line of broken lines.
breakautoindent=⟨true|false⟩or

breakautoindenttrue

activates or deactivates automatic indention of broken lines. This indention
is used additionally to breakindent, see the example below. Visible spaces
or visible tabulators might set this auto indention to zero.
In the following example we use tabulators to create long lines, but the verbatim
part uses tabsize=1.
1 \lstset{postbreak=\space, breakindent=5pt, breaklines}{ Now a u t oindention is o f f . }4.3.10↷

1↷

2”A l o n g s t r i n g
i s broken ! ”” Anotherlong l i n e . ”↷

1

1 \begin{lstlisting}2"A long string is broken!"3"Another long line."
4 \end{lstlisting}5
6 \begin{lstlisting}[breakautoindent
7=false]8{ Now auto indention is off. }9 \end{lstlisting}

Framesframe=⟨none|leftline|topline|bottomline|lines|single|shadowbox⟩

none

draws either no frame, a single line on the left, at the top, at the bottom, at
the top and bottom, a whole single frame, or a shadowbox.
Note that fancyvrb supports the same frame types except shadowbox. The
shadow color is rulesepcolor, see below.
frame=⟨subset of trblTRBL⟩{}

The characters trblTRBL designate lines at the top and bottom of a listing
and to lines on the right and left. Upper case characters are used to draw
double rules. So frame=tlrb draws a single frame and frame=TL doublelines at the top and on the left.
Note that frames usually reside outside the listing’s space.
frameround=⟨t|f⟩⟨t|f⟩⟨t|f⟩⟨t|f⟩

ffff

The four letters designate the top right, bottom right, bottom left and top
left corner. In this order. t makes the according corner round. If you use
round corners, the rule width is controlled via \thinlines and \thicklines.
Note: The size of the quarter circles depends on framesep and is independentof the extra margins of a frame. The size is possibly adjusted to fit LATEX’s
circle sizes.
38framesep=⟨dimension⟩

3pt

rulesep=⟨dimension⟩

2pt

control the space between frame and listing and between double rules.
framerule=⟨dimension⟩

0.4pt

controls the width of the rules.
framexleftmargin=⟨dimension⟩

0pt

framexrightmargin=⟨dimension⟩

0pt

framextopmargin=⟨dimension⟩

0pt

framexbottommargin=⟨dimension⟩

0pt

are the dimensions which are used additionally to framesep to make up the
margin of a frame.
backgroundcolor=⟨color command⟩
rulecolor=⟨color command⟩
fillcolor=⟨color command⟩
rulesepcolor=⟨color command⟩
specify the colour of the background, the rules, the space between ‘text box’and first rule, and of the space between two rules, respectively. Note that thevalue requires a \color command, for example rulecolor=\color{blue}.
frame does not work with fancyvrb=true or when the package internally makes
a \hbox around the listing! And there are certainly more problems with othercommands; please take the time to make a (bug) report.
↶↷

1 \lstset{framexleftmargin=5mm, frame=shadowbox, rulesepcolor=\color{blue}}1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;

1 \begin{lstlisting}[numbers=left]
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6 \end{lstlisting}Note here the use of framexleftmargin to include the line numbers inside theframe.
Do you want exotic frames? Try the following key if you want, for example,

1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;



 1 \begin{lstlisting}

2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
 6 \end{lstlisting}39

†frameshape={⟨top shape⟩}{⟨left shape⟩}{⟨right shape⟩}{⟨bottom shape⟩}
gives you full control over the drawn frame parts. The arguments are notcase sensitive.
Both ⟨left shape⟩ and ⟨right shape⟩ are ‘left-to-right’ y|n character sequences(or empty). Each y lets the package draw a rule, otherwise the rule isblank. These vertical rules are drawn ‘left-to-right’ according to the specified
shapes. The example above uses yny.
⟨top shape⟩ and ⟨bottom shape⟩ are ‘left-rule-right’ sequences (or empty).
The first ‘left-rule-right’ sequence is attached to the most inner rule, thesecond to the next, and so on. Each sequence has three characters: ‘rule’ iseither y or n; ‘left’ and ‘right’ are y, n or r (which makes a corner round).
The example uses RYRYNYYYY for both shapes: RYR describes the most inner(top and bottom) frame shape, YNY the middle, and YYY the most outer.
To summarize, the example above used%\lstset{frameshape={RYRYNYYYY}{yny}{yny}{RYRYNYYYY}}

Note that you are not resticted to two or three levels. However you’ll get in trouble
if you use round corners when they are too big.
4.3.11

Indexing

index=[⟨number⟩][⟨keyword classes⟩]{⟨identifiers⟩}
moreindex=[⟨number⟩][⟨keyword classes⟩]{⟨identifiers⟩}
deleteindex=[⟨number⟩][⟨keyword classes⟩]{⟨identifiers⟩}
define, add and remove ⟨identifiers⟩ and ⟨keyword classes⟩ from the index
class list ⟨number⟩. If you don’t specify the optional number, the package
assumes ⟨number⟩ = 1.
Each appearance of the explicitly given identifiers and each appearance of
the identifiers of the specified ⟨keyword classes⟩ is indexed. For example, you
could write index=[1][keywords] to index all keywords. Note that [1] isrequired here—otherwise we couldn’t use the second optional argument.
indexstyle=[⟨number⟩]⟨tokens (one-parameter command)⟩\lstindexmacro⟨tokens⟩ actually indexes the identifiers for the list ⟨number⟩. In contrast
to the style keys, ⟨tokens⟩ must read exactly one parameter, namely theidentifier. Default definition is\lstindexmacro%\newcommand\lstindexmacro[1]{\index{{\ttfamily#1}}}

which you shouldn’t modify. Define your own indexing commands and use
them as argument to this key.
Section 2.9 describes this feature in detail.

40

4.3.12

Column alignment

columns=[⟨c|l|r⟩]⟨alignment⟩[c]fixed

selects the column alignment. The ⟨alignment⟩ can be fixed, flexible,
spaceflexible, or fullflexible; see section 2.10 for details.
The optional c, l, or r controls the horizontal orientation of smallest output
units (keywords, identifiers, etc.). The arguments work as follows, wherevertical bars visualize the effect: | l i s t i n g |, |l i s t i n g |, and | l i s t i n g| in
fixed column mode, | listing |, |listing |, and | listing| with flexible columns,
and |listing|, |listing|, and |listing| with space-flexible or full flexible columns(which ignore the optional argument, since they do not add extra spacearound printable characters).
flexiblecolumns=⟨true|false⟩or

flexiblecolumns

false

selects the most recently selected flexible or fixed column format, refer tosection 2.10.
†

keepspaces=⟨true|false⟩

false

keepspaces=true tells the package not to drop spaces to fix column alignment and always converts tabulators to spaces.
basewidth=⟨dimension⟩orbasewidth={⟨fixed⟩,⟨flexible mode⟩}{0.6em,0.45em}

sets the width of a single character box for fixed and flexible column mode(both to the same value or individually).
fontadjust=⟨true|false⟩orfontadjust

false

If true the package adjusts the base width every font selection. This makes
sense only if basewidth is given in font specific units like ‘em’ or ‘ex’—
otherwise this boolean has no effect.
After loading the package, it doesn’t adjust the width every font selection:
it looks at basewidth each listing and uses the value for the whole listing.
This is possibly inadequate if the style keys in section 4.3.5 make heavy fontsize changes, see the example below.
Note that this key might disturb the column alignment and might have aneffect on the keywords’ appearance!

1 { scriptsize font
2
doesn ’ t look good }3 f o r i :=maxint to 0 do
4 begin5{ do n o t h i n g }6 end ;

1 \lstset{commentstyle=\scriptsize}
2 \begin{lstlisting}3 { scriptsize font
4
doesn’t look good }5 for i:=maxint to 0 do
6 begin7{ do nothing }8 end;
9 \end{lstlisting}41

1 \begin{lstlisting}[fontadjust]2 { scriptsize font3
looks better now }4 for i:=maxint to 0 do
5 begin6{ do nothing }7 end;
8 \end{lstlisting}1 { s c r i p t s i z e font2
l o o k s b e t t e r now }3 f o r i := maxint t o 0 do
4 begin5{ do n o t h i n g }6 end ;
4.3.13

Escaping to LATEX

Note: Any escape to LATEX may disturb the column alignment since the package
can’t control the spacing there.
texcl=⟨true|false⟩

or

texcl

false

activates or deactivates LAT X comment lines.

If activated, comment lineEdelimiters are printed as usual, but the comment line text (up to the end ofline) is read as LATEX code and typeset in comment style.
The example uses C++ comment lines (but doesn’t say how to define them). Without \upshape we would get calculate since the comment style is \itshape.
1 // calculate aij
2
A[ i ] [ j ] = A[ j ] [ j ] /A[ i ] [ j ] ;1 \begin{lstlisting}[texcl]
2 // \upshape calculate $a_{ij}$3
A[i][j] = A[j][j]/A[i][j];4 \end{lstlisting}mathescape=⟨true|false⟩

false

activates or deactivates special behaviour of the dollar sign. If activated adollar sign acts as TEX’s text math shift.
This key is useful if you want to typeset formulas in listings.
escapechar=⟨character⟩orescapechar={}{}If not empty the given character escapes the user to LATEX: all code between
two such characters is interpreted as LATEX code. Note that TEX’s special
characters must be entered with a preceding backslash, e.g. escapechar=\%.
escapeinside=⟨character⟩⟨character⟩orescapeinside={}{}Is a generalization of escapechar. If the value is not empty, the package
escapes to LATEX between the first and second character.
escapebegin=⟨tokens⟩{}

escapeend=⟨tokens⟩{}

The tokens are executed at the beginning respectively at the end of each
escape, in particular for texcl. See section 8 for an application.
1 // c a l c u l a t e aij2
aij = ajj /aij ;1 \begin{lstlisting}[mathescape]2 // calculate $a_{ij}$3$a_{ij} = a_{jj}/a_{ij}$;
4 \end{lstlisting}42

1 // c a l c ulate aij2
aij = ajj /aij ;1 \begin{lstlisting}[escapechar=\%]2 // calc%ulate $a_{ij}$%3%$a_{ij} = a_{jj}/a_{ij}$%;
4 \end{lstlisting}1 // c a l c ulate aij2
aij = ajj /aij ;1 \lstset{escapeinside=‘’}2 \begin{lstlisting}3 // calc‘ulate $a_{ij}$’4‘$a_{ij} = a_{jj}/a_{ij}$’;
5 \end{lstlisting}In the first example the comment line up to aij has been typeset by the listings
package in comment style. The aij itself is typeset in ‘TEX math mode’ without
comment style. About half of the comment line of the second example has beentypeset by this package, and the rest is in ‘LATEX mode’.
To avoid problems with the current and future version of this package:
1. Don’t use any commands of the listings package when you have escaped to
LATEX.
2. Any environment must start and end inside the same escape.
3. You might use \def, \edef, etc., but do not assume that the definitions arepresent later, unless they are \global.
4. \if \else \fi, groups, math shifts $ and $$, . . . must be balanced withineach escape.
5. . . .
Expand that list yourself and mail me about new items.

4.4Interface to fancyvrb

The fancyvrb package—fancy verbatims—from Timothy van Zandt provides
macros for reading, writing and typesetting verbatim code. It has some remarkable features the listings package doesn’t have. (Some are possible, but you mustfind somebody who will implement them ;-).
fancyvrb=⟨true|false⟩
activates or deactivates the interface. If active, verbatim code is read by
fancyvrb but typeset by listings, i.e. with emphasized keywords, strings,
comments, and so on. Internally we use a very special definition of\FancyVerbFormatLine.
This interface works with Verbatim, BVerbatim and LVerbatim. But you
shouldn’t use fancyvrb’s defineactive. (As far as I can see it doesn’t matter
since it does nothing at all, but for safety . . . .) If fancyvrb and listings provide
similar functionality, you should use fancyvrb’s.
fvcmdparams=⟨command1 ⟩⟨number1 ⟩. . .

43\overlay1morefvcmdparams=⟨command1 ⟩⟨number1 ⟩. . .
If you use fancyvrb’s commandchars, you must tell the listings package how
many arguments each command takes. If a command takes no arguments,
there is nothing to do.
The first (third, fifth, . . . ) parameter to the keys is the command and thesecond (fourth, sixth, . . . ) is the number of arguments that command takes.
So, if you want to use \textcolor{red}{keyword} with the fancyvrb-listingsinterface, you should write \lstset{morefvcmdparams=\textcolor 2}.

First verbatim line.
Second verbatim line.

First verbatim line .
Second verbatim line .

1 \lstset{morecomment=[l]\ }% :-)2 \fvset{commandchars=\\\{\}}
3
4 \begin{BVerbatim}
5 First verbatim line.
6 \fbox{Second} verbatim line.
7 \end{BVerbatim}
89 \par\vspace{72.27pt}
10
11 \lstset{fancyvrb}
12 \begin{BVerbatim}
13 First verbatim line.
14 \fbox{Second} verbatim line.
15 \end{BVerbatim}
16 \lstset{fancyvrb=false}

The lines typeset by the listings package are wider since the default basewidth
doesn’t equal the width of a single typewriter type character. Moreover, note thatthe first space begins a comment as defined at the beginning of the example.

4.5

Environments

If you want to define your own pretty-printing environments, try the following
command. The syntax comes from LATEX’s \newenvironment.
\lstnewenvironment{⟨name⟩}[⟨number⟩][⟨opt. default arg.⟩]{⟨starting code⟩}{⟨ending code⟩}
As a simple example we could just select a particular language.
1 \lstnewenvironment{pascal}2{\lstset{language=pascal}}3{}

1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;

1 \begin{pascal}
2 for i:=maxint to 0 do
3 begin4{ do nothing }5 end;
6 \end{pascal}

44

Doing other things is as easy, for example, using more keys and adding an optional
argument to adjust settings each listing:%\lstnewenvironment{pascalx}[1][]%{\lstset{language=pascal,numbers=left,numberstyle=\tiny,float,#1}}
%
{}

4.6

Short Inline Listing Commands

Short equivalents of \lstinline can also be defined, in a manner similar to theshort verbatim macros provided by shortvrb.
\lstMakeShortInline[[⟨options⟩]]⟨character⟩defines ⟨character⟩ to be an equivalent of \lstinline[[⟨options⟩]]⟨character⟩,allowing for a convenient syntax when using lots of inline listings.
\lstDeleteShortInline⟨character⟩removes a definition of ⟨character⟩ created by \lstMakeShortInline, andreturns ⟨character⟩ to its previous meaning.

4.7

Language definitions

You should first read section 3.2 for an introduction to language definitions. Otherwise you’re probably unprepared for the full syntax of \lstdefinelanguage.
\lstdefinelanguage[[⟨dialect⟩]]{⟨language⟩}[[⟨base dialect⟩]{⟨and base language⟩}]{⟨key=value list⟩}[[⟨list of required aspects (keywordcomments,texcs,etc.)⟩]]
defines the (given dialect of the) programming language ⟨language⟩. If thelanguage definition is based on another definition, you must specify the whole[⟨base dialect⟩]{⟨and base language⟩}. Note that an empty ⟨base dialect⟩
uses the default dialect!
The last optional argument should specify all required aspects. This is adelicate point since the aspects are described in the developer’s guide. Youmight use existing languages as templates. For example, ANSI C uses keywords, comments, strings and directives.
\lst@definelanguage has the same syntax and is used to define languages
in the driver files.
→ Where should I put my language definition?
If you need the language for one particular document, put it into the preamble of that document. Otherwise create the local file‘lstlang0.sty’ or add the definition to that file, but use ‘\lst@definelanguage’ insteadof ‘\lstdefinelanguage’. However, you might want to send the definition to the addressin section 2.1. Then it will be included with the rest of the languages distributed with the
package, and published under the LATEX Project Public License.

\lstalias{⟨alias⟩}{⟨language⟩}defines an alias for a programming language. Each ⟨alias⟩ is redirected tothe same dialect of ⟨language⟩. It’s also possible to define an alias for one
particular dialect only:45

\lstalias[⟨alias dialect⟩]{⟨alias⟩}[⟨dialect⟩]{⟨language⟩}
Here all four parameters are nonoptional and an alias with empty ⟨dialect⟩
will select the default dialect. Note that aliases cannot be chained: The
two aliases ‘\lstalias{foo1}{foo2}’ and ‘\lstalias{foo2}{foo3}’ will
not redirect foo1 to foo3.
All remaining keys in this section are intended for building language definitions.
No other key should be used in such a definition!
Keywords We begin with keyword building keys. Note: If you want to enter\, {, }, %, # or & as (part of) an argument to the keywords below, you must do itwith a preceding backslash!
†bugkeywordsprefix=⟨prefix⟩
All identifiers starting with ⟨prefix⟩ will be printed as first order keywords.
Bugs: Currently there are several limitations. (1) The prefix is always casesensitive. (2) Only one prefix can be defined at a time. (3) If used ‘standalone’ outside a language definition, the key might work only after selecting
a nonempty language (and switching back to the empty language if necessary). (4) The key does not respect the value of classoffset and has no
optional class ⟨number⟩ argument.
keywords=[⟨number⟩]{⟨list of keywords⟩}
morekeywords=[⟨number⟩]{⟨list of keywords⟩}
deletekeywords=[⟨number⟩]{⟨list of keywords⟩}
define, add to or remove the keywords from keyword list ⟨number⟩. The useof keywords is discouraged since it deletes all previously defined keywords
in the list and is thus incompatible with the alsolanguage key.
Please note the keys alsoletter and alsodigit below if you use unusual
charaters in keywords.

deprecatedndkeywords={⟨list of keywords⟩}

deprecatedmorendkeywords={⟨list of keywords⟩}

deprecateddeletendkeywords={⟨list of keywords⟩}
define, add to or remove the keywords from keyword list 2; note that thisis equivalent to keywords=[2]. . . etc. The use of ndkeywords is strongly
discouraged.

addon,optional

texcs=[⟨class number⟩]{⟨list of control sequences (without backslashes)⟩}

addon,optional

moretexcs=[⟨class number⟩]{⟨list of control sequences (without backslashes)⟩}

addon,optionaldeletetexcs=[⟨class number⟩]{⟨list of control sequences (without backslashes)⟩}
Ditto for control sequences in TEX and LATEX.

optional

directives={⟨list of compiler directives⟩}

optional

moredirectives={⟨list of compiler directives⟩}
46

classletter
digit
other
space
tabulator
form feed

Table 2: Standard character tablecharacters
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z@ $ _0 1 2 3 4 5 6 7 8 9! " # % & ’ ( ) * + , - . / : ; < = > ?
[ \ ] ˆ { | } ˜chr(32)3chr(9)
chr(12)

Note: Extended characters of codes 128–255 (if defined) are currently letters.
optional

deletedirectives={⟨list of compiler directives⟩}
defines compiler directives in C, C++, Objective-C, and POV.
sensitive=⟨true|false⟩
makes the keywords, control sequences, and directives case sensitive andinsensitive, respectively. This key affects the keywords, control sequences,and directives only when a listing is processed. In all other situations they arecase sensitive, for example, deletekeywords={save,Test} removes ‘save’and ‘Test’, but neither ‘SavE’ nor ‘test’.
alsoletter={⟨character sequence⟩}
alsodigit={⟨character sequence⟩}alsoother={⟨character sequence⟩}
All identifiers (keywords, directives, and such) consist of a letter followedby alpha-numeric characters (letters and digits). For example, if you write
keywords={one-two,\#include}, the minus sign must become a digit andthe sharp a letter since the keywords can’t be detected otherwise.
Table 2 show the standard configuration of the listings package. The threekeys overwrite the default behaviour. Each character of the sequence becomes a letter, digit and other, respectively.
otherkeywords={⟨keywords⟩}
Defines keywords that contain other characters, or start with digits. Eachgiven ‘keyword’ is printed in keyword style, but without changing the ‘letter’,‘digit’ and ‘other’ status of the characters. This key is designed to define
keywords like =>, ->, -->, --, ::, and so on. If one keyword is a subsequenceof another (like -- and -->), you must specify the shorter first.

renamed,optionaltag=⟨character⟩⟨character⟩or

tag={}

The first order keywords are active only between the first and second character. This key is used for HTML.
3 Here and at other places chr(⟨number⟩) means a Pascal function which returns the character
which has ASCII value ⟨number⟩.

47

Strings
string=[⟨b|d|m|bd|s⟩]{⟨delimiter (character)⟩}morestring=[⟨b|d|m|bd|s⟩]{⟨delimiter⟩}deletestring=[⟨b|d|m|bd|s⟩]{⟨delimiter⟩}define, add to or delete the delimiter from the list of string delimiters. Starting and ending delimiters are the same, i.e. in the source code the delimiters
must match each other.
The optional argument is the type and controls the how the delimiter itself
is represented in a string or character literal: it is escaped by a backslash,doubled (or both is allowed via bd). Alternately, the type can refer to an
unusual form of delimiter: string delimiters (akin to the s comment type) or
matlab-style delimiters. The latter is a special type for Ada and Matlab andpossibly other languages where the string delimiters are also used for otherpurposes. It is equivalent to d, except that a string does not start after aletter, a right parenthesis, a right bracket, or some other characters.
Comments
comment=[⟨type⟩]⟨delimiter(s)⟩morecomment=[⟨type⟩]⟨delimiter(s)⟩deletecomment=[⟨type⟩]⟨delimiter(s)⟩Ditto for comments, but some types require more than a single delimiter.
The following overview uses morecomment as the example, but the examples
apply to comment and deletecomment as well.
morecomment=[l]⟨delimiter⟩
The delimiter starts a comment line, which in general starts with the delimiter and ends at end of line. If the character sequence // should start acomment line (like in C++, Comal 80 or Java), morecomment=[l]// is thecorrect declaration. For Matlab it would be morecomment=[l]\%—note thepreceding backslash.
morecomment=[s]{⟨delimiter⟩}{⟨delimiter⟩}Here we have two delimiters. The second ends a comment startingwith the first delimiter. If you require two such comments you can
use this type twice. C, Java, PL/I, Prolog and SQL all define single comments via morecomment=[s]{/*}{*/}, and Algol does it with
morecomment=[s]{\#}{\#}, which means that the sharp delimits both beginning and end of a single comment.
morecomment=[n]{⟨delimiter⟩}{⟨delimiter⟩}is similar to type s, but comments can be nested. Identical arguments
are not allowed—think a while about it! Modula-2 and Oberon-2 use
morecomment=[n]{(*}{*)}.
morecomment=[f]⟨delimiter⟩48

morecomment=[f][commentstyle][⟨n=preceding columns⟩]⟨delimiter⟩
The delimiter starts a comment line if and only if it appears on a fixedcolumn-number, namely if it is in column n (zero based).
optional

keywordcomment={⟨keywords⟩}

optional

morekeywordcomment={⟨keywords⟩}

optional

deletekeywordcomment={⟨keywords⟩}
A keyword comment begins with a keyword and ends with the same keyword.
Consider keywordcomment={comment,co}. Then ‘comment. . . comment’and ‘co. . . co’ are comments.

optional

keywordcommentsemicolon={⟨keywords⟩}{⟨keywords⟩}{⟨keywords⟩}
The definition of a ‘keyword comment semicolon’ requires three keyword
lists, e.g. {end}{else,end}{comment}. A semicolon always ends such acomment. Any keyword of the first argument begins a comment and any
keyword of the second argument ends it (and a semicolon also); a comment
starting with any keyword of the third argument is terminated with thenext semicolon only. In the example all possible comments are ‘end. . . else’,‘end. . . end’ (does not start a comment again) and ‘comment. . . ;’ and‘end. . . ;’. Maybe a curious definition, but Algol and Simula use such comments.
Note: The keywords here need not to be a subset of the defined keywords.
They won’t appear in keyword style if they aren’t.

optional

podcomment=⟨true|false⟩
activates or deactivates PODs—Perl specific.

4.8

Installation

Software installation
1. Following the TEX directory structure (TDS), you should put the files of thelistings package into directories as follows:
listings.pdf
listings.dtx, listings.ins,
listings.ind, lstpatch.sty,
lstdrvrs.dtx→

texmf/doc/latex/listings→

texmf/source/latex/listings

Note that you may not have a patch file lstpatch.sty. If you don’t use the
TDS, simply adjust the directories below.
2. Create the directory texmf/tex/latex/listings or, if it exists already,remove all files except lst⟨whatever⟩0.sty and lstlocal.cfg from it.
3. Change the working directory to texmf/source/latex/listings and runlistings.ins through TEX.
4. Move the generated files to texmf/tex/latex/listings if this is not already
done.
49

listings.sty, lstmisc.sty,
listings.cfg,
lstlang⟨number⟩.sty,
lstpatch.sty→(kernel and add-ons)(configuration file)(language drivers)
texmf/tex/latex/listings

5. If your TEX implementation uses a file name database, update it.
6. If you receive a patch file later on, put it where listings.sty is (and update
the file name database).
Note that listings requires at least version 1.10 of the keyval package included in
the graphics bundle by David Carlisle.
Software configuration Read this only if you encounter problems with thestandard configuration or if you want the package to suit foreign languages, forexample.
Never modify a file from the listings package, in particular not the configuration
file. Each new installation or new version overwrites it. The software license allows
modification, but I can’t recommend it. It’s better to create one or more of thefileslstmisc0.sty
lstlang0.sty
lstlocal.cfg

for
for
as

local add-ons (see the developer’s guide),local language definitions (see 4.7), andlocal configuration fileand put them in the same directory as the other listings files. These three files
are not touched by a new installation unless you remove them. If lstlocal.cfg
exists, it is loaded after listings.cfg. You might want to change one of thefollowing parameters.
data\lstaspectfiles contains lstmisc0.sty,lstmisc.sty

data\lstlanguagefiles

contains lstlang0.sty,lstlang1.sty,lstlang2.sty,lstlang3.sty

The package uses the specified files to find add-ons and language definitions.
Moreover, you might want to adjust \lstlistlistingname, \lstlistingname,\lstlistingnamestyle, defaultdialect, \lstalias, or \lstalias as describedin earlier sections.

5

Experimental features

This section describes the more or less unestablished parts of this package. It’s
unlikely that they will all be removed (unless stated explicitly), but they are liable
to (heavy) changes and improvements. Such features have been †-marked in thelast sections. So, if you find anything †-marked here, you should be very, very
careful.

5.1

Listings inside arguments

There are some things to consider if you want to use \lstinline or the listing
environment inside arguments. Since TEX reads the argument before the ‘lstmacro’ is executed, this package can’t do anything to preserve the input: spaces
50

shrink to one space, the tabulator and the end of line are converted to spaces,
TEX’s comment character is not printable, and so on. Hence, you must work a bit
more. You have to put a backslash in front of each of the following four characters:\{}%. Moreover you must protect spaces in the same manner if: (i) there are two
or more spaces following each other or (ii) the space is the first character in theline. That’s not enough: Each line must be terminated with a ‘line feed’ ˆˆJ. And
you can’t escape to LATEX inside such listings!
The easiest examples are with \lstinline since we need no line feed.
%\footnote{\lstinline{var i:integer;} and%\lstinline!protected\ \ spaces! and%\fbox{\lstinline!\\\{\}\%!}}
yields4 if the current language is Pascal. Note that this example shows anotherexperimental feature: use of argument braces as delimiters. This is described in
section 4.2.
And now an environment example:

1
2
3
4
5
6

1 \fbox{%
2 \begin{lstlisting}ˆˆJ
3 \ !"#$\%&’()*+,-./ˆˆJ
4 0123456789:;<=>?ˆˆJ
5 @ABCDEFGHIJKLMNOˆˆJ
6 PQRSTUVWXYZ[\\]ˆ_ˆˆJ
7 ‘abcdefghijklmnoˆˆJ
8 pqrstuvwxyz\{|\}˜ˆˆJ
9 \end{lstlisting}}!”# $ %&’() ∗+ , −./0123456789:; <= >?
@ABCDEFGHIJKLMNOPQRSTUVWXYZ[ \ ] ˆ‘ abcdefghijklmno
pqrstuvwxyz { | } ˜→ You might wonder that this feature is still experimental. The reason: You shouldn’t use listings
inside arguments; it’s not always safe.

5.2† Export of identifiers

It would be nice to export function or procedure names. In general that’s a dreamso far. The problem is that programming languages use various syntaxes forfunction and procedure declaration or definition. A general interface is completely
out of the scope of this package—that’s the work of a compiler and not of apretty-printing tool. However, it is possible for particular languages: in Pascal, forinstance, each function or procedure definition and variable declaration is precededby a particular keyword. Note that you must request the following keys with theprocnames option: \usepackage[procnames]{listings}.
†optional

procnamekeys={⟨keywords⟩}{}†optional

moreprocnamekeys={⟨keywords⟩}†optional

deleteprocnamekeys={⟨keywords⟩}
each specified keyword indicates a function or procedure definition. Any
identifier following such a keyword appears in ‘procname’ style. For Pascal
you might use%

procnamekeys={program,procedure,function}

4 var i : integer; and protected

spaces and \{}%

51

†optional

procnamestyle=⟨style⟩keywordstyledefines the style in which procedure and function names appear.
†optional

indexprocnames=⟨true|false⟩false

If activated, procedure and function names are also indexed.
To do: The procnames aspect is unsatisfactory (and has been unchanged at least
since 2000). It marks and indexes the function definitions so far, but it would bepossible to mark also the following function calls, for example. A key could control
whether function names are added to a special keyword class, which then appearsin ‘procname’ style. But should these names be added globally? There are goodreasons for both. Of course, we would also need a key to reset the name list.

5.3† Hyperlink references

This very small aspect must be requested via the hyper option since it is experimental. One possibility for the future is to combine this aspect with procnames.
Then it should be possible to click on a function name and jump to its definition,for example.
†optional

hyperref={⟨identifiers⟩}†optional

morehyperref={⟨identifiers⟩}†optional

deletehyperref={⟨identifiers⟩}
hyperlink the specified identifiers (via hyperref package). A ‘click’ on suchan identifier jumps to the previous occurrence.

†optional

hyperanchor=⟨two-parameter macro⟩†optional

hyperlink=⟨two-parameter macro⟩\hyper@@anchor\hyperlink

set a hyperlink anchor and link, respectively. The defaults are suited for thehyperref package.

5.4

Literate programming

We begin with an example and hide the crucial key=value list.
1 var i : integer ;2
3 i f ( i≤0 ) i ← 1 ;4 i f ( i≥0 ) i ← 0 ;5 i f ( i̸=0 ) i ← 0 ;1 \begin{lstlisting}2 var i:integer;3
4 if (i<=0) i := 1;
5 if (i>=0) i := 0;
6 if (i<>0) i := 0;
7 \end{lstlisting}Funny, isn’t it? We could leave i := 0 in our listings instead of i ← 0, but that’s
not literate! Now you might want to know how this has been done. Have a close
look at the following key.
†literate=[*]⟨replacement item⟩. . . ⟨replacement item⟩
First note that there are no commas between the items. Each item consistsof three arguments: {⟨replace⟩}{⟨replacement text⟩}{⟨length⟩}. ⟨replace⟩ is52the original character sequence. Instead of printing these characters, weuse ⟨replacement text⟩, which takes the width of ⟨length⟩ characters in the
output.
Each ‘printing unit’ in ⟨replacement text⟩ must be in braces unless it’s a single
character. For example, you must put braces around $\leq$. If you want toreplace <-1-> by $\leftarrow1\rightarrow$, the replacement item wouldbe {<-1->}{{$\leftarrow$}1{$\rightarrow$}}3. Note the braces aroundthe arrows.
If one ⟨replace⟩ is a subsequence of another ⟨replace⟩, you must define theshorter sequence first. For example, {-} must be defined before {--} andthis before {-->}.
The optional star indicates that literate replacements should not be madein strings, comments, and other delimited text.
In the example above, I’ve used%literate={:=}{{$\gets$}}1 {<=}{{$\leq$}}1 {>=}{{$\geq$}}1 {<>}{{$\neq$}}1
To do: Of course, it’s good to have keys for adding and removing single ⟨replacement
item⟩s. Maybe the key(s) should work in the same fashion as the string and comment definitions, i.e. one item per key=value. This way it would be easier to provide
better auto-detection in case of a subsequence.

5.5

LGrind definitions

Yes, it’s a nasty idea to steal language definitions from other programs. Nevertheless, it’s possible for the LGrind definition file—at least partially. Please notethat this file must be found by TEX.
optionallgrindef=⟨language⟩scans the lgrindef language definition file for ⟨language⟩ and activates it if
present. Note that not all LGrind capabilities have a listings analogue.
Note that ‘Linda’ language doesn’t work properly since it defines compiler
directives with preceding ‘#’ as keywords.

data,optional\lstlgrindeffile

lgrindef.

contains the (path and) name of the definition file.

5.6† Automatic formatting

The automatic source code formatting is far away from being good. First of all,there are no general rules on how source code should be formatted. So ‘format definitions’ must be flexible. This flexibility requires a complex interface, a powerful‘format definition’ parser, and lots of code lines behind the scenes. Currently, format definitions aren’t flexible enough (possibly not the definitions but the results).
A single ‘format item’ has the form
⟨input chars⟩=[⟨exceptional chars⟩]⟨pre⟩[⟨\string ⟩]⟨post⟩53

Whenever ⟨input chars⟩ aren’t followed by one of the ⟨exceptional chars⟩, formatting is done according to the rest of the value. If \string isn’t specified, the input
characters aren’t printed (except it’s an identifier or keyword). Otherwise ⟨pre⟩is ‘executed’ before printing the original character string and ⟨post⟩ afterwards.
These two are ‘subsets’ of• \newline —ensuring a new line;• \space —ensuring a whitespace;• \indent —increasing indention;• \noindent —descreasing indention.
Now we can give an example.
1 \lstdefineformat{C}{%2\{=\newline\string\newline\indent,%
3\}=\newline\noindent\string\newline,%4;=[\ ]\string\space}
1 f o r ( i n t i =0; i < 1 0 ; i ++)2 {3/∗ wait ∗/4 }5 ;1 \begin{lstlisting}[format=C]
2 for (int i=0;i<10; i++){/* wait */};
3 \end{lstlisting}Not good. But there is a (too?) simple work-around:
1 \lstdefineformat{C}{%2\{=\newline\string\newline\indent,%3\}=[;]\newline\noindent\string\newline,%4\};=\newline\noindent\string\newline,%5;=[\ ]\string\space}
1 f o r ( i n t i =0; i < 1 0 ; i ++)2 {3/∗ wait ∗/4 };1 \begin{lstlisting}[format=C]
2 for (int i=0;i<10; i++){/* wait */};
3 \end{lstlisting}Sometimes the problem is just to find a suitable format definition. Further formatting is complicated. Here are only three examples with increasing level ofdifficulty.
1. Insert horizontal space to separate function/procedure name and following
parenthesis or to separate arguments of a function, e.g. add the space after
a comma (if inside function call).
2. Smart breaking of long lines. Consider long ‘and/or’ expressions. Formatting
should follow the logical structure!
3. Context sensitive formatting rules. It can be annoying if empty or small
blocks take three or more lines in the output—think of scrolling down all
the time. So it would be nice if the block formatting was context sensitive.
54

Note that this is a very first and clumsy attempt to provide automatic formatting—clumsy since the problem isn’t trivial. Any ideas are welcome. Implementations
also. Eventually you should know that you must request format definitions at
package loading, e.g. via \usepackage[formats]{listings}.

5.7

Arbitrary linerange markers

Instead of using linerange with line numbers, one can use text markers. Each
such marker consists of a ⟨prefix⟩, a ⟨text⟩, and a ⟨suffix⟩. You once (or more)define prefixes and suffixes and then use the marker text instead of the line numbers.
1 \lstset{rangeprefix=\{\ ,% curly left brace plus space2
rangesuffix=\ \}}% space plus curly right brace

7 { loop 2 }8 f o r i :=maxint to 0 do
9 begin10{ do n o t h i n g }11 end ;12 { end }1 \begin{lstlisting}%
2[linerange=loop\ 2-end]
3 { loop 1 }4 for i:=maxint to 0 do
5 begin6{ do nothing }7 end;
8 { end }9 { loop 2 }10 for i:=maxint to 0 do
11 begin
12{ do nothing }13 end;14 { end }15 \end{lstlisting}Note that TEX’s special characters like the curly braces, the space, the percent
sign, and such must be escaped with a backslash.
rangebeginprefix=⟨prefix⟩
rangebeginsuffix=⟨suffix⟩
rangeendprefix=⟨prefix⟩
rangeendsuffix=⟨suffix⟩
define individual prefixes and suffixes for the begin- and end-marker.
rangeprefix=⟨prefix⟩
rangesuffix=⟨suffix⟩
define identical prefixes and suffixes for the begin- and end-marker.
includerangemarker=⟨true|false⟩trueshows or hides the markers in the output.
Remark: If firstnumber is set, it refers to the line which contains themarker. So if one wants to start a range with the number 1, one has to set
includerangemarker=false, firstnumber=0.
55

2 f o r i :=maxint to 0 do
3 begin4{ do n o t h i n g }5 end ;

5.8

1 \begin{lstlisting}%
2[linerange=loop\ 1-end,
3
includerangemarker=false,
4
frame=single]
5 { loop 1 }6 for i:=maxint to 0 do
7 begin8{ do nothing }9 end;
10 { end }11 \end{lstlisting}Multicolumn Listings

When the multicol package is loaded, it can be used to typeset multi-column
listings. These are specified with the multicols key. For example:

1 i f ( i < 0)
2
i = 0
3
j = 1

4 end i f
5 i f ( j < 0)
6
j = 0
7 end i f

1 \begin{lstlisting}[multicols=2]
2 if (i < 0)
3
i = 0
4
j = 1
5 end if
6 if (j < 0)
7
j = 0
8 end if
9 \end{lstlisting}

The multicolumn option is known to fail with some keys.
→ Which keys?
Unfortunately, I don’t know. Carsten left the code for this option in theversion 1.3b patch file with only that cryptic note for documentation. Bug reports would be
welcome, though I don’t promise that they’re fixable. —Brooks

Tips and tricks
Note: This part of the documentation is under construction. Section 8 must be
sorted by topic and ordered in some way. Moreover a new section ‘Examples’ isplanned, but not written. Lack of time is the main problem . . .

6Troubleshooting

If you’re faced with a problem with the listings package, there are some steps
you should undergo before you make a bug report. First you should consult thereference guide to see whether the problem is already known. If not, create aminimal file which reproduces the problem. Follow these instructions:
1. Start from the minimal file in section 1.1.
2. Add the LATEX code which causes the problem, but keep it short. In particular, keep the number of additional packages small.

56

3. Remove some code from the file (and the according packages) until the problem disappears. Then you’ve found a crucial piece.
4. Add this piece of code again and start over with step 3 until all code and all
packages are substantial.
5. You now have a minimal file. Send a bug report to the address on the firstpage of this documentation and include the minimal file together with thecreated .log-file. If you use a very special package (i.e. one not on CTAN),
also include the package if its software license allows it.

7

Bugs and workarounds

7.1

Listings inside arguments

A long time it wasn’t possible to use \lstinline{...} in a cell of a table, butthere was a recommended workaround. This workaround is still functional, but
now one can use \lstinline{...} and of course \lstinline|...| directly:
1 \newcommand\foo{\lstinline{t}}2 \newcommand\foobar[2][]{\lstinline[#1]{#2}}3
4 \begin{tabular}{ll}5 \lstinline|r| & a first variable (standard)\\
6 \lstinline[language=java]|int s;| & a standard declaration \\7 \foo & a second variable (workaround)\\8 \foobar[language=java]{int u;} & a (workaraond) declaration \\9 \lstinline{v} & another variable using braces\\
10 \lstinline[language=java]{int w;} & an additional braced declaration
11 \end{tabular}r
int s ;t
int u;v
int w;

7.2

a first variable (standard)a standard declarationa second variable (workaround)a (workaraond) declaration
another variable using braces
an additional braced declaration

Listings with a background colour and LATEX escaped
formulasIf there is any text escaped to LATEX with some coloured background and surrounding frames, then there are gaps in the background as well as in the lines
making up the frame.
1 \begin{lstlisting}[language=C, mathescape,2
backgroundcolor=\color{yellow!10}, frame=tlb]
3 /* the following code computes $\displaystyle\sum_{i=1}ˆ{n}i$ */4 for (i = 1; i <= limit; i++) {5
sum += i;
6 }7 \end{lstlisting}57

1 /∗ t h e f o l l o w i n g code computes
2 f o r ( i = 1 ; i <= l i m i t ; i ++) {3
sum += i ;
4 }

n
X

i ∗/

i=1

At the moment there is only one workaround:• Write your code into an external file ⟨filename⟩.
• Input your code by \lstinputlisting⟨filename⟩ into your document andsurround it with a frame generated by \begin{mdframed} . . . \end{mdframed}.
1 \begin{verbatimwrite}{temp.c}
2 /* the following code computes $\displaystyle\sum_{i=1}ˆ{n}i$ */3 for (i = 1; i <= limit; i++) {4
sum += i;
5 }6 \end{verbatimwrite}
7 \begin{mdframed}[backgroundcolor=yellow!10, rightline=false]
8\lstinputlisting[language=C,mathescape,frame={}]{./temp.c}
9 \end{mdframed}

1 /∗ t h e f o l l o w i n g code computesnX

2 f o r ( i = 1 ; i <= l i m i t ; i ++) {3
sum += i ;
4 }

i ∗/

i=1

For more information about the verbatimwrite environment have a look at[Fai11], the mdframed environment is deeply discussed in [DS13].

8

How tos

How to reference line numbers
Perhaps you want to put \label{⟨whatever⟩} into a LATEX escape which is inside
a comment whose delimiters aren’t printed? If you did that, the compiler won’t
see the LATEX code since it would be inside a comment, and the listings package
wouldn’t print anything since the delimiters would be dropped and \label doesn’t
produce any printable output, but you could still reference the line number. Well,
your wish is granted.
In Pascal, for example, you could make the package recognize the ‘special’comment delimiters (*@ and @*) as begin-escape and end-escape sequences. Then
you can use this special comment for \labels and other things.

58

1 \lstset{escapeinside={(*@}{@*)}}
2
3 \begin{lstlisting}
4 for i:=maxint to 0 do
5 begin6{ comment }(*@\label{comment}@*)7 end;
8 \end{lstlisting}
9 Line \ref{comment} shows a comment.

f o r i :=maxint to 0 do
begin
3
{ comment }end ;1Line 3 shows a comment.

→ Can I use ‘(*@’ and ‘*)’ instead?

Yes.

→ Can I use ‘(*’ and ‘*)’ instead?

Sure. If you want this.

→ Can I use ‘{@’ and ‘@}’ instead?
No, never! The second delimiter is not allowed. The
character ‘@’ is defined to check whether the escape is over. But reading the lonely ‘endargument’ brace, TEX encounters the error ‘Argument of @ has an extra }’. Sorry.
→ Can I use ‘{’ and ‘}’ instead?
No. Again the second delimiter is not allowed. Here now
TEX would give you a ‘Runaway argument’ error. Since ‘}’ is defined to check whether theescape is over, it won’t work as ‘end-argument’ brace.
→ And how can I use a comment line?
For example, write ‘escapeinside={//*}{\ˆˆM}’.
Here \ˆˆM represents the end of line character.

How to gobble characters
To make your LATEX code more readable, you might want to indent yourlstlisting listings. This indention should not show up in the pretty-printed
listings, however, so it must be removed. If you indent each code line by threecharacters, you can remove them via gobble=3:
1 f o r i :=maxint to 0 do
2 begin3{ do n o t h i n g }4 end ;
5
6 Write ( ’ Case i n s e n s i t i v e ’ ) ;7 WritE( ’ P a s c a l keywords . ’ ) ;1 \begin{lstlisting}[gobble=3]
2 1␣␣for␣i:=maxint␣to␣0␣do
3 ␣2␣begin
4 ␣␣3␣␣␣␣{␣do␣nothing␣}5 123end;
6
7 ␣␣␣Write(’Case␣insensitive␣’);8 ␣␣␣WritE(’Pascal␣keywords.’);
9 \end{lstlisting}Note that empty lines and the beginning and the end of the environment need
not respect the indention. However, never indent the end by more than ‘gobble’
characters. Moreover note that tabulators expand to tabsize spaces before wegobble.
→ Could I use ‘gobble’ together with ‘\lstinputlisting’?

Yes, but it has no effect.

→ Note that ‘gobble’ can also be set via ‘\lstset’.

How to include graphics
Herbert Weinhandl found a very easy way to include graphics in listings. Thanks
for contributing this idea—an idea I would never have had.
Some programming languages allow the dollar sign to be part of an identifier.
But except for intermediate function names or library functions, this character ismost often unused. The listings package defines the mathescape key, which lets59‘$’ escape to TEX’s math mode. This makes the dollar character an excellent
candidate for our purpose here: use a package which can include a graphic, setmathescape true, and include the graphic between two dollar signs, which are
inside a comment.
The following example is originally from a header file I got from Herbert. For
the presentation here I use the lstlisting environment and an excerpt from theheader file. The \includegraphics command is from David Carlisle’s graphics
bundle.
%
%
%
%
%
%
%
%
%

\begin{lstlisting}[mathescape=true]/*$ \includegraphics[height=1cm]{defs-p1.eps} $*/typedef struct {Atom_T*V_ptr;/* pointer to Vacancy in grid*/
Atom_T*x_ptr;/* pointer to (A|B) Atom in grid */} ABV_Pair_T;\end{lstlisting}

The result looks pretty good. Unfortunately you can’t see it, because the graphic
wasn’t available when the manual was typeset.
How to get closed frames on each pageThe package supports closed frames only for listings which don’t cross pages. If
a listing is split on two pages, there is neither a bottom rule at the bottom of apage, nor a top rule on the following page. If you insist on these rules, you mightwant to use framed.sty by Donald Arseneau. Then you could write
%
%
%
%
%

\begin{framed}\begin{lstlisting}or \lstinputlisting{...}\end{lstlisting}\end{framed}

The package also provides a shaded environment. If you use it, you shouldn’t
forget to define shadecolor with the color package.
How to print national characters with Λ and listings
Apart from typing in national characters directly, you can use the ‘escape’ featuredescribed in section 4.3.13. The keys escapechar, escapeinside, and texcl
allow partial usage of LATEX code.
Now, if you use Λ (Lambda, the LATEX variant for Omega) and want, forexample, Arabic comment lines, you need not write \begin{arab} . . . \end{arab}each escaped comment line. This can be automated:
%
%
%
%
%
%

\lstset{escapebegin=\begin{arab},escapeend=\end{arab}}\begin{lstlisting}[texcl]// Replace text by Arabic comment.
for (int i=0; i<1; i++) { };\end{lstlisting}60

If your programming language doesn’t have comment lines, you’ll have to use
escapechar or escapeinside:
%
%
%
%
%
%

\lstset{escapebegin=\begin{greek},escapeend=\end{greek}}\begin{lstlisting}[escapeinside=‘’]/* ‘Replace text by Greek comment.’ */for (int i=0; i<1; i++) { };\end{lstlisting}Note that the delimiters ‘ and ’ are essential here. The example doesn’t workwithout them. There is a more clever way if the comment delimiters of the programming language are single characters, like the braces in Pascal:
%
%
%
%
%
%
%
%
%

\lstset{escapebegin=\textbraceleft\begin{arab},
escapeend=\end{arab}\textbraceright}\begin{lstlisting}[escapeinside=\{\}]
for i:=maxint to 0 do
begin
{ Replace text by Arabic comment. }end;\end{lstlisting}

Please note that the ‘interface’ to Λ is completely untested. Reports are welcome!
How to get bold typewriter type keywords
Use the LuxiMono package.
How to work with plain text
If you want to use listings to set plain text (perhaps with line numbers, orlike verbatim but with line wrapping, or so forth, use the empty language:\lstset{language=}.
How to get the developer’s guideIn the source directory of the listings package, i.e. where the .dtx files are, create
the file ltxdoc.cfg with the following contents.
%\AtBeginDocument{\AlsoImplementation}

Then run listings.dtx through LATEX twice, run Makeindex (with the -s gind.ist
option), and then run LATEX one last time on listings.dtx. This creates thewhole documentation including User’s guide, Reference guide, Developer’s guide,and Implementation.
If you can run the (GNU) make program, executing the command%

make allor%

make listings-devel.pdf
61

or
%

make pdf-devel

gives the same result—it is called listings-devel.pdf.
How to copy and paste from a document
If you want to provide a document containing listings formatted by this package(listings) as source for copy and paste, you should be sure to set the key upquote totrue and have \usepackage{textcomp} in the preamble of the document. Otherwise the pair ‘’ of curly quotation marks is associated with Unicode positions
U+2018 and U+2019 [CMK12]. These characters are seldom used as delimiters
in modern programming languages.
How to change the layout of the list of listings
If you put the command \lstlistoflistings into your document, the list oflistings is automatically generated and printed at that point. If you are using thestandard LATEX classes the list is prepared by \addtocontents commands or avariation, if you also load the package float. In both cases the layout is the one
defined by L. Lamport.
If you want to change the layout of this list, you can use the package tocbasic
as described in [Koh23, Chapter 15.3]. tocbasic is automatically loaded, if you areusing one of the KOMA classes.

References[CMK12] Michael A. Covington, Frank Mittelbach and Markus G. Kuhn. upquote– upright-quote and grave-accent glyphs in verbatim, 2012.
[DS13]

Marco Daniel and Elke Schubert. The mdframed package, 2013.

[Fai11]Robin Fairbairns. The moreverb package, 2011.

[Koh23]Markus Kohm. KOMA-Script – The Guide, 2023.

[MF23]

Frank Mittelbach and Ulrike Fischer. The LATEX-Companion Part I andII, 2023.

[Mi04]

Frank Mittelbach, Michel Goossens, Johannes Braams, David P.
Carlisle, and Chris Rowley. The LATEX-Companion, 2004.

[Som11]

Axel Sommerfeldt. Customizing captions of floating environments, 2011.

Index
square . . . . . . . . . . . . . . . . . . . . .

Symbolsroot......................

20

62

20

C
comment styles
b . . . . . . . . . . . . . . . . . . . . . . 23
d . . . . . . . . . . . . . . . . . . . . . . 23
is . . . . . . . . . . . . . . . . . . . . . 24
l . . . . . . . . . . . . . . . . . . . . . . 23
n . . . . . . . . . . . . . . . . . . . . . . 23
s . . . . . . . . . . . . . . . . . . . . . . 23
comments
commentstyle . . . . . . . . 5, 24, 31
comment . . . . . . . . . . . . . . . . . 47
deletecomment . . . . . . . . . 24, 47
morecomment . . . . 22, 23, 47, 48
D
directives
deletedirectives . . . . . . . . . .
directivestyle . . . . . . . . . . .
directives . . . . . . . . . . . . . . .
moredirectives . . . . . . . . . . .

46
32
45
45

E
emph
deleteemph . . . . . . . . . . . . . . . 32
emphstyle . . . . . . . . . . 19, 20, 32
emph . . . . . . . . . . . . . . 19, 20, 32
moreemph . . . . . . . . . . . . . . . . 32
escapeescapebegin . . . . . . . . . . . . . . 41
escapechar . . . . . . . . . 41, 59, 60
escapeend . . . . . . . . . . . . . . . . 41
escapeinside . . . . . . . 41, 59, 60
mathescape . . . . . . . . . 41, 58, 59
texcl . . . . . . . . . . . . . . . . 41, 59
experimental
includerangemarker . . . . . . . . 54
rangebeginprefix . . . . . . . . . . 54
rangebeginsuffix . . . . . . . . . . 54
rangeendprefix . . . . . . . . . . . 54
rangeendsuffix . . . . . . . . . . . 54
rangeprefix . . . . . . . . . . . . . . 54
rangesuffix . . . . . . . . . . . . . . 54
F
fancyvrb
fancyvrb . . . . . . . . . . . . . . . . 42
fvcmdparams . . . . . . . . . . . . . . 42
morefvcmdparams . . . . . . . . . . . 43
formats\lstdefineformat . . . . . . . . . . 53
format . . . . . . . . . . . . . . . . . . 53
framesbackgroundcolor . . . . . . . . 19, 38
fillcolor . . . . . . . . . . . . . . . . 38

63

frameround . . . . . . . . . . . . 17, 37
framerule . . . . . . . . . . . . . . . . 38
framesep . . . . . . . . . . . . . . . . 38
frameshape . . . . . . . . . . . . . . . 39
framexbottommargin . . . . . . . . 38
framexleftmargin . . . . . . . . . . 38
framexrightmargin . . . . . . . . . 38
framextopmargin . . . . . . . . . . . 38
frame . . . . . . . . . . . . . 17, 37, 38
rulecolor . . . . . . . . . . . . . . . . 38
rulesepcolor . . . . . . . . . . . . . 38
rulesep . . . . . . . . . . . . . . . . . 38
H
html
markfirstintag . . . . . . . . . . .
tagstyle . . . . . . . . . . . . . . . .
tag . . . . . . . . . . . . . . . . . . . . .
usekeywordsintag . . . . . . . . . .
hyperdeletehyperref . . . . . . . . . . .
hyperanchor . . . . . . . . . . . . . .
hyperlink . . . . . . . . . . . . . . . .
hyperref . . . . . . . . . . . . . . . .
morehyperref . . . . . . . . . . . . .

31
31
46
31
51
51
51
51
51

I
index
\lstindexmacro . . . . . . . . . . . 39
deleteindex . . . . . . . . . . . . . . 39
indexstyle . . . . . . . . . . . . 20, 39
index . . . . . . . . . . . . . 20, 21, 39
moreindex . . . . . . . . . . . . . . . . 39
K
kernel\lstDeleteShortInline . . . . . . 44
\lstMakeShortInline . . . . . . . 44
\lstaspectfiles . . . . . . . . . . . 49
\lstinline . . . . . . . . . . . . 11, 28\lstinputlisting . . . . . . . . 4, 28\lstlistingnamestyle . . . 36, 49\lstlistingname . . . . . . . . 35, 49\lstlistlistingname . . . . 35, 49\lstlistoflistings . . . . . 18, 35\lstname . . . . . . . . . . . . . . . . 36
\lstnewenvironment . . . . . . . . 43
\lstset . . . . . . . . . . . . . . 11, 28\thelstlisting . . . . . . . . . . . 36
abovecaptionskip . . . . . . . . . . 36
aboveskip . . . . . . . . . . . . . 17, 29
alsodigit . . . . . . . . . . . . . 45, 46
alsoletter . . . . . . . . . . . . 45, 46
alsoother . . . . . . . . . . . . . . . . 46

basewidth . . . . . . . . . . . . . 40, 43
basicstyle . . . . . . . . . . . . . 5, 31
belowcaptionskip . . . . . . . . . . 36
belowskip . . . . . . . . . . . . . 17, 29
boxpos . . . . . . . . . . . . . . . . . . 29
captionpos . . . . . . . . . . . . . . . 36
caption . . . . . . . . . . . . 6, 18, 35
columns . . . . . . . . . . . . . . 21, 40
consecutivenumbers . . . . . 15, 30
deletedelim . . . . . . . . . . . . . . 32
delim . . . . . . . . . . . . . . . . . . . 32
emptylines . . . . . . . . . . . . . . . 30
extendedchars . . . . . . . . . 14, 33
firstline . . . . . . . . . . . 4, 11, 29
flexiblecolumns . . . . . . . . . . . 40
floatplacement . . . . . . . . . . . 29
float . . . . . . . . . . . . . . . . . . . 29
fontadjust . . . . . . . . . . . . . . . 40
formfeed . . . . . . . . . . . . . 14, 33
gobble . . . . . . . . . . . . . . . 30, 58
identifierstyle . . . . . . . . . 5, 31
inputencoding . . . . . . . . . . . . 33
inputpath . . . . . . . . . . . . . . . . 28
keepspaces . . . . . . . . . . . . . . . 40
label . . . . . . . . . . . . . . . . 18, 35
lastline . . . . . . . . . . . . . 11, 29
linerange . . . . . . . . . . 15, 29, 30
literate . . . . . . . . . . . . . . . . 51
lstlisting . . . . . . . . . . . . . 4, 56
moredelim . . . . . . . . . . . . . 24, 32
name . . . . . . . . . . . . . . 15, 16, 34
nolol . . . . . . . . . . . . . . . . 18, 35
numberbychapter . . . . . . . . . . . 36
print . . . . . . . . . . . . . . . . . . . 29
showlines . . . . . . . . . . . . . . 4, 30
showspaces . . . . . . . . . . . . 14, 33
showtabs . . . . . . . . . . . . . 14, 33
tabsize . . . . . . . . . . . 13, 30, 33
tab . . . . . . . . . . . . . . . . . . 14, 33
title . . . . . . . . . . . . . . . . 18, 35
upquote . . . . . . . . . . . . . . . . . 33
keywordcomments
deletekeywordcomment . . . . . . 48
keywordcommentsemicolon . . . . 48
keywordcomment . . . . . . . . . . . 48
morekeywordcomment . . . . . . . . 48
keywords
classoffset . . . . . . . . . . . 30, 32
deletekeywords . . . . . . . . . . . 45
deletendkeywords . . . . . . . . . . 45
keywordsprefix . . . . . . . . . . . 45
keywordstyle . . . . . . . . . . . 5, 31
keywords . . . . . . . . . . . . . . . . 45
morekeywords . . . . . . . . . . 22, 45

morendkeywords . . . . . . . . . . . 45
ndkeywordstyle . . . . . . . . . . . 31
ndkeywords . . . . . . . . . . . . . . . 45
otherkeywords . . . . . . . . . . . . 46
sensitive . . . . . . . . . . . . . 22, 46
Llabels\thelstnumber . . . . . . . . . . . . 34
firstnumber . . . . . . . . 15, 16, 34
numberblanklines . . . . . . . . . . 34
numberfirstline . . . . . . . . . . . 34
numbersep . . . . . . . . . . . 6, 15, 34
numberstyle . . . . . . . . . 6, 15, 34
numbers . . . . . . . . . . . . 6, 15, 34
stepnumber . . . . . . 6, 15, 16, 34
language\lst@definelanguage . . . . . . . 44
\lstalias . . . . . . . . . . 44, 45, 49\lstdefinelanguage . . . . . . . . 44
\lstlanguagefiles . . . . . . . . . 49
\lstloadlanguages . . . . . . . . . 10
alsolanguage . . . . . . . . . . 11, 30
defaultdialect . . . . . . . . 31, 49
language . . . . . . . . . . . . . 11, 30
lgrind\lstlgrindeffile . . . . . . . . . . 52
lgrindef . . . . . . . . . . . . . . . . 52
lineshape
breakatwhitespace . . . . . . . . . 36
breakautoindent . . . . . . . . . . . 37
breakindent . . . . . . . . . . . . . . 37
breaklines . . . . . . . . . . . . . . . 36
lineskip . . . . . . . . . . . . . . . . 29
linewidth . . . . . . . . . . . . . . . . 36
postbreak . . . . . . . . . . . . . . . . 37
prebreak . . . . . . . . . . . . . . . . 36
resetmargins . . . . . . . . . . . . . 36
xleftmargin . . . . . . . . . . . . . . 36
xrightmargin . . . . . . . . . . . . . 36
M
makemakemacrouse . . . . . . . . . . . . .

31

P
pod

podcomment . . . . . . . . . . . . . . .
printpod . . . . . . . . . . . . . . . .
procnames
deleteprocnamekeys . . . . . . . .
indexprocnames . . . . . . . . . . .
moreprocnamekeys . . . . . . . . . .
procnamekeys . . . . . . . . . . . . .
procnamestyle . . . . . . . . . . . .

64

48
31
50
51
50
50
51

S
strings
deletestring . . . . . . . . . . 24, 47
morestring . . . . . . . . . . . . 23, 47
showstringspaces . . . . . . . . 5, 33
stringstyle . . . . . . . . . . . . 5, 31
string . . . . . . . . . . . . . . . . . . 47
style
\lstdefinestyle . . . . . . . . . . . 30

style . . . . . . . . . . . . . . . . 22, 30
T
tex
deletetexcs . . . . . . . . . . . . . .
moretexcs . . . . . . . . . . . . . . . .
texcsstyle . . . . . . . . . . . . . . .
texcs . . . . . . . . . . . . . . . . . . .

65

45
45
32
45