Listings.dtx Version 0.19

Copyright 1996–1998 Carsten Heinz

Abstract

Listings.dtx is a source code printer for L^{A}TEX — which always means L^{A}TEX 2ε in this documentation. You can typeset stand alone files as well as enter listings using an environment similar to verbatim as well as you can print fragments using a command similar to \verb. The package supports a wide spectrum of programming languages — some come already with lstdrvrs.dtx. Finally: Many parameters control the output.

User’s guide 2

1 Preface 2 2 Software license 2 3 Getting started 3

3.1 Package loading . . . . . . 3 3.2 Typesetting listings …. 4 3.3 The ”key=value” interface 5 3.4 Figure out the appearance 5 3.5 Line numbers . . . . . . . 6 3.6 Tabulators and form feeds 7 3.7 Indent the listing . . . . . 8 3.8 Fixed and flexible columns 9 3.9 Selecting other languages 10

4 Main reference 11 4.1 Typesetting listings …. 11 4.2 List of listings . . . . . . . 12 4.3 Basic style keys . . . . . . 13 4.4 Fixed and flexible columns 14 4.5 Listing alignment . . . . . 14 4.6 Escaping to L^{A}TEX …. 15 4.7 Some special keys . . . . . 16 4.8 Languages and styles … 17 4.9 Language definitions … 17

5 Experimental features 20 5.1 Interface to fancyvrb … 21 5.2 Listings inside arguments 21 5.3 Frames . . . . . . . . . . . 22 5.4 Export of identifiers … 23

6 Troubleshooting 23 6.1 Problems with .fd files . 23 6.2 Language definitions … 24 7 Forthcoming 24

Again incompatibilities! And there are certainly teething troubles since the complete kernel has been rewritten. So read this manual with care.

User’s guide

1 Preface

The files listings.dtx and listings.ins and all files generated from only these two files are referred as ’the listings package’ or simply ’the package’. A driver file is any file generated mainly from lstdrvrs.dtx.

Alternatives. The listings package is certainly not the final utility for typesetting source code listings. Other programs do their jobs very well if you are not satiesfied with listings. I should mention a2ps and the LGrind package. Let me know if you’re using none of these solutions; I’d like to extend my suggestions.

Reading this manual. In any case you should read section ”3. Getting started” step by step. You either start from the scratch there or you get in touch with the new user interface and other changes. That section is an introduction and doesn’t cover all of the listings package, but the most common. After reading it you are prepared for the main reference if you need more details, more control or more features.

Sorry! On 1998/11/02 I decided to make major changes to the user interface, which were planned for version 0.2. But it’s better to get the interface stable as soon as possible. In particular I must say sorry to all people I posted a pre-version of listings 0.19.

Thanks. There are many people I have to thank for fruitful communication, posting their ideas, giving error reports (first bug finder is listed), adding programming languages to lstdrvrs.dtx, etc.. If you want to know that in detail, search for the names in the implementation part. Special thanks go to (alphabetical order)

Andreas Bartelt, Jan Braun, Denis Girou, Arne John Glenstrup, Rolf Niepraschk, Rui Oliveira and Boris Veytsman.

Moreover I wish to thank

Bjørn Ådlandsvik, Gaurav Aggarwal, Kai Below, Detlev Dröge, Anders Edenbrandt, Harald Harders, Christian Haul, Jürgen Heim, Dr. Jobst Hoffmann, Knut Müller, Zvezdan V. Petkovic, Michael Piotrowski, Ralf Quast, Aslak Raanes, Detlef Reimers, Magne Rudshaug, Andreas Stephan, Dominique de Waleffe, Herbert Weinhandl, Jörn Wilms and Kai Wollenweber.

2 Software license

Copyright. The listings package is copyright 1996–1998 Carsten Heinz. The driver files are copyright 1997, 1998 or 1997–1998 any individual author listed in these files.

Distribution. The listings package as well as lstdrvrs.dtx and all driver files are distributed freely. You are not allowed to take money for the distribution, except for a nominal charge for copying etc..

Use of the package. The listings package is free for any non-commercial use. Commercial use needs (i) explicit permission of the author of this package and (ii) the payment of a license fee. This fee is to be determined in each instance by the commercial user and the package author and is to be payed as donation to the L^{A}TEX3 project.

No warranty. The listings package as well as lstdrvrs.dtx and all driver files are distributed without any warranty, express or implied, as to merchantability or fitness for any particular purpose.

Modification advice. Permission is granted to change the listings package as well as lstdrvrs.dtx. You are not allowed to distribute any changed version of the package or any changed version of lstdrvrs.dtx, neither under the same name nor under a different one. Tell the author of the package about your local changes: other users will welcome removed bugs, new features and additional programming languages.

Contacts. Send comments and ideas on the package, error reports and additional programming languages to Carsten Heinz, Tellweg 6, 42275 Wuppertal, Germany or preferably to cheinz@gmx.de.

Trademarks appear throughout this documentation without any trademark symbol, so you can’t assume that a name is free. There is no intention of infringement; the usage is to the benefit of the trademark owner.

3 Getting started

3.1 Package loading

As usual in L^{A}TEX the package is loaded by \usepackage[⟨options⟩]{listings}, where [⟨options⟩] is optional. Note that listings 0.19 needs more save stack size than any previous version. The following options are available:

0.17 Use this option to compile documents created with version 0.17 of the listings package. Note that you can’t use old driver files and that the option does not guarantee full compatibility. If you want to polish up an old document, use this option together with new commands and keys. There shouldn’t be many problems, but I haven’t made deep tests.

index and procnames define the ’index’ respectively ’procnames’ aspect, whatever that means.

ndkeywords and rdkeywords define second respectively third order keywords.

Note: Each option slows down the package, so it becomes quite slow if you use all options, for example. Note also that you can’t activate any optional feature after package loading — except you’re a hacker and read the implementation part.

Here is some kind of minimal file.

    \documentclass{article}
    \usepackage{listings}
    %\usepackage[ndkeywords,index]{listings}% with some options

    \begin{document}
    \lstset{language=Pascal}
    % Any example may be inserted here.
    \end{document}

It loads the listings package without any option, but shows how the package is loaded with index option and second order keywords. Moreover we select Pascal as programming language.

If you need more than one programming language in your document, I recommend the preamble command \lstloadlanguages, which loads the given pro-

gramming languages only, e.g. \lstloadlanguages{Pascal,Fortran,C++}. You

find more details in section 4.8.

3.2 Typesetting listings

You can print (a) stand alone files, (b) source code from .tex files or (c) code fragments within a paragraph. The difference between (b) and (c) is something like between display and text formulas ($$ and $).

We begin with code fragments. If you want ’var i:integer;’, you can simply write ’\lstinline!var i:integer;!’. The exclamation marks delimit the code fragment. They could be replaced by any character not in the code fragment, i.e. ’\lstinline$var i:integer;$’ would produce the same output.

The lstlisting environment typesets the source code in between. It has one parameter, which we leave empty for the moment.

for i :=maxint to 0 do

begin

{ do nothing }
end;
Write( ’ Keywords are case ’ ) ;
WritE( ’ i n s e n s i t i v e here . ’ ) ;

                                        \begin{lstlisting}{}
                                        for i:=maxint to 0 do

                                        begin

                                            { do nothing }
                                        end;
                                        Write('Keywords are case ');
                                        WritE('insensitive here.');
                                        \end{lstlisting}

Like most examples this shows the L^{A}TEX source code on the right and the result on the left. If you insert the L^{A}TEX code in the minimal file and run it through TEX, the listing uses the whole text width.

Finally examples for stand alone files:

 \lstinputlisting {listings .tmp}  \lstinputlisting{listings.tmp}

Do you wonder about the left hand side? Well, the file listings.tmp contains the current example. This is exactly the line you see on the right. If you want this line to be typeset in Pascal mode, you get what you’ve got. If you want the lines 3, 4, …, 10 of testfile.pas, write

    \lstinputlisting[first=3,last=10]{testfile.pas}

But be sure that the first line does exist, or you will get a ”runaway argument” error.

Problems could arise if you (try to) put a listing in a box, tabular environment or something similar. The \lstbox command in section 4.1 might solve this. If you use an extended character table in your listings, you must use the extendedchars key, see section 4.7.

3.3 The ”key=value” interface

The listings package uses keyval.sty from the graphics bundle by David Carlisle. Each ’aspect’ or ’parameter’ you can control has an associated key. To select a programming language, for example, you need the key language, the sign = and the name of the language as value. The command \lstset gets this construction as argument. You have seen this in the minimal file on page 4. You can set more than one parameter with a single \lstset if you separate two or more ”key=value” constructions by commas:

    \lstset{language=Pascal,keywordstyle=\bfseries}

If the value itself contains a comma, you must enclose the value in braces:

    \lstset{keywords={one,two,three}}
\lstset{keywords=one,two,three} would set the one and only keyword one and

gives an error message since the parameters two and three do not exist.

Two final notes: (1) Some keys has default values, e.g. flexiblecolumns=true turns flexible columns on, but flexiblecolumns without any =true would do the same since the value true is default for that key. But you must use the value false if you want to turn them off. (2) \lstset sets the values local to the current group. Just forget it if you don’t know what that means. The command \lstinputlisting (as seen above) and the environment (as you see below) both have optional arguments. If you use a key=value list as optional argument, these selections are valid for the particular listing only and the previous values are restored afterwards. For example, if the current language is Pascal, but you want testfile.f95 from line 3 on, write

    \lstinputlisting[first=3,language=Fortran]{testfile.f95}

Afterwards Pascal is still the current language. Note that \lstinline has no optional parameter.

3.4 Figure out the appearance

Keywords are typeset bold, comments in italic shape and spaces in strings appear as ’ ’ (without the two quotes). You can change that default behaviour:

\lstset{
    basicstyle=\small,              % print whole listing small
    keywordstyle=\bfseries\underbar,% 'underlined' bold keywords
    nonkeywordstyle={},             % nothing happens to other identifiers
    commentstyle=\itshape,          % default
    stringstyle=\ttfamily,          % typewriter font for strings
    blankstring=true}               % blank spaces are blank in strings

We typeset a previous example with these styles again.

\underline{for} i :=\underline{maxint} \underline{to} 0 \underline{do}

\underline{begin}

{ do nothing }
\underline{end};

  \underline{Write}( 'Keywords  are  case ' ) ;
 \underline{WritE}( 'insensitive  here.' ) ;

                                        \begin{lstlisting}{}
                                        for i:=maxint to 0 do

                                        begin

                                            { do nothing }
                                        end;
                                        Write('Keywords are case ');
                                        WritE('insensitive here.');
                                        \end{lstlisting}

The style definitions above use two kind of commands; on the one hand \ttfamily or \bfseries taking no arguments and on the other \underline, which gets exactly one argument. The very last token of keywordstyle, nonkeywordstyle and labelstyle (see below) may be a macro getting exactly one argument, namely the (non)keyword or label. All other tokens must not take any arguments — or you will get deep in trouble.

Warning: You shouldn’t use striking styles too often, but ’too often’ depends on how many keywords the source code contains, for example. Your eyes would concentrate on the framed, bold red printed keywords only, and your brain must compensate this. Reading such source code could be very exhausting. If it were longer, the last example would be quite good in this sense. Believe me.

3.5 Line numbers

You want tiny line numbers each second line? Here you are:

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;
6 Write( ’ Keywords are case ’ ) ;
WritE( ’ i n s e n s i t i v e here . ’ ) ;

                                        \lstset{labelstyle=\tiny,%   <===
                                                labelstep=2}%        <===
                                        \begin{lstlisting}{}
                                        for i:=maxint to 0 do

                                        begin

                                            { do nothing }
                                        end;
                                        Write('Keywords are case ');
                                        WritE('insensitive here.');
                                        \end{lstlisting}

labelstep=0 turns line numbering off. In the sequel we use labelstyle=\tiny and labelstep=2, even if it doesn’t appear in the verbatim part. And now we try to interrupt (continue) a listing. For this purpose we use { } as argument to the environment.

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;

And we continue the listing:

6 Write( ’ Keywords are case ’ ) ;
WritE( ’ i n s e n s i t i v e here . ’ ) ;

                                        \begin{lstlisting}{}
                                        for i:=maxint to 0 do

                                        begin

                                            { do nothing }
                                        end;
                                        \end{lstlisting}
                                        And we continue the listing:
                                        \begin{lstlisting}{ }%       <===
                                        Write('Keywords are case ');
                                        WritE('insensitive here.');
                                        \end{lstlisting}

Note that the empty line at the end of the first part is not printed, but it is responsible for correct line numbering. { } continued the previous ’{}’-listing. In general the argument is the name of the listing. An empty (= {}) named listing always starts with line number one, no matter whether line numbers are printed or not. A space (= { }) named listing continues the last empty or space named one. That’s easy. And this mechanism becomes easier if you use real names for your listings. In that case all listings with the same name use a common line counter: the second (same named) listing continues automatically the first. Even if there are other listings in between.

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;

And we continue the listing:

6 Write( ’ Keywords are case ’ ) ;
WritE( ’ i n s e n s i t i v e here . ’ ) ;

                                        \begin{lstlisting}{Test}%    <===
                                        for i:=maxint to 0 do

                                        begin

                                            { do nothing }
                                        end;
                                        \end{lstlisting}
                                        And we continue the listing:
                                        \begin{lstlisting}{Test}%    <===
                                        Write('Keywords are case ');
                                        WritE('insensitive here.');
                                        \end{lstlisting}

The next Test listing goes on with line number 8. Note that listing names are case sensitive.

3.6 Tabulators and form feeds

You might get some unexpected output if your source code contains a tabulator or form feed. The package assumes tabulator stops at columns 9,17,25,33,…, and a form feed prints an empty line. This is predefined via

    \lstset{tabsize=8,formfeed=\bigbreak}

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. If you want a new page every form feed, use

formfeed=\newpage.

123456789

{ one t a b u l a t o r }
{ two tabs }
123  { 123 and two tabs }

\lstset{tabsize=4}
\begin{lstlisting}{}

123456789

    { one tabulator }
        { two tabs }
123     { 123 and two tabs }
\end{lstlisting}

Unfortunately both sides are typeset with tabsize=4.

3.7 Indent the listing

The examples are typeset with centered minipages. That’s the reason why you can’t see that line numbers are printed in the margin (default). Now we separate the ’minipage margin’ and the minipage by a vertical rule:

Some text before

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;

Some text before
\begin{lstlisting}{}
for i:=maxint to 0 do

begin

    { do nothing }
end;
\end{lstlisting}

The listing is lined up with the normal text. You can change this if you want. The parameter indent ’moves’ the listing to the right (or left if the skip is negative).

Some text before

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;
Write( ’ Keywords are case ’ ) ;
6 WritE( ’ i n s e n s i t i v e here . ’ ) ;

Some text before
\lstset{indent=2em}%         <===
\begin{lstlisting}{}
for i:=maxint to 0 do

begin

    { do nothing }
end;
\end{lstlisting}
\begin{lstlisting}{ }
Write('Keywords are case ');
WritE('insensitive here.');
\end{lstlisting}

Note that \lstset{indent=2em} also changes the indent for the second listings. If you want to indent a single listing only, use the argument of \lstset as optional argument to the listing environment:

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;
Write( ’ Keywords are case ’ ) ;
6 WritE( ’ i n s e n s i t i v e here . ’ ) ;

\begin{lstlisting}[indent=2em]{}
for i:=maxint to 0 do

begin

    { do nothing }
end;
\end{lstlisting}
\begin{lstlisting}{ }
Write('Keywords are case ');
WritE('insensitive here.');
\end{lstlisting}

Such local changes apply to all supported parameters.

If you use environments like itemize or enumerate, there is ’natural’ indention coming from these environments. By default the listings package respects this. But you might use wholeline=true (or false) to make your own decision.

• First item:

for i :=maxint to 0 do
2 begin
{ do nothing }
4 end;

• Second item:

Write( ’ Keywords are case ’ ) ;
6 WritE( ’ i n s e n s i t i v e here . ’ ) ;

                                        \begin{itemize}
                                        \item First item:
                                        \begin{lstlisting}{}
                                        for i:=maxint to 0 do

                                        begin

                                            { do nothing }
                                        end;
                                        \end{lstlisting}
                                        \item Second item:
                                        \lstset{wholeline=true}%     <===
                                        \begin{lstlisting}{ }
                                        Write('Keywords are case ');
                                        WritE('insensitive here.');
                                        \end{lstlisting}
                                        \end{itemize}

You can use wholeline together with indent, of course. Refer section 4.5 for a description of spread.

3.8 Fixed and flexible columns

The first thing a reader notices is — except different styles for keywords etc. — the column alignment of a listing. The problem: I don’t like listings in typewriter fonts and other fonts need not to have a fixed width. But we don’t want

if x=y then write(’alignment’) else print(’alignment’);

only because spaces are not wide enough. There is a simple trick to avoid such things. We make boxes of the same width and put one character in each box:

i f  x = y  t h e n  w r i t e  …
e l s e  p r i n t  …

Going this way the alignment of columns can’t be disturbed. But if the boxes are not wide enough, we get ’i f x=y then … ’, and choosing the width so that the widest character fits in leads to ’ i f x = y t h e n w r i t e … ’. Both are not acceptable. Since all input will be cut up in units, we can put each unit in a box, which width is multiplied by the number of characters we put in, of course. The result is i f x = y t h e n w r i t e . Since we put wide and thin characters in the same box, the width of a single character box need not to be the width of the widest character. The empirical value 0.6em (which is called ’base em’ later) is a compromise between overlapping characters and the number of boxes not exceeding the text width, i.e. how many characters fit a line without getting an overfull \hbox.

But overlapping characters are a problem if you use many upper case letters, e.g. WOMEN — blame me and not the women, in fact MEN doesn’t look better. To go around this problem the listings package supports more ’flexible columns’ in contrast to the fixed columns above. Arne John Glenstrup (whose idea the format is) pointed out that he had good experience with flexible columns and assembler listings. The differences can be summed up as follows: The fixed column format ruins the nice spacing intended by the font designer, and the flexible format ruins the column alignment (possibly) intended by the programmer. We illustrate that:

verbatim  fixed columns  flexible columns
with 0.6em  with 0.45em

           WOMEN  are MEN WOMEN are better MEN

WOMEN are

MEN

WOMEN are
better MEN

WOMEN are MEN WOMEN are better MEN

Hope this helps. Note the varying numbers of spaces between ’WOMEN’ and ’are’ and look at the different outputs. The flexible column format typesets all characters at their natural width. In particular characters never overlap. If a word needs more space than reserved (’WOMEN’), the rest of the line moves to the right. Sometimes a following word needs less space than reserved, or there are spaces following each other. Such ’surplus’ space is used to fix the column alignment: The blank space in the third line have been printed properly, but the two blanks in the first line have been printed as one blank space. We can show all this more drastic if we reduce the width of a single character box:

0.3em  0.0em

WOMEN  are MEN WOMEN are better MEN     WOMEN are MEN WOMEN are better MEN  WOMEN are MEN WOMEN are better MEN

In flexible column mode the first ’MEN’ moves to the left since the blanks before are 7 · 0.0em= 0em wide. Even in flexible mode you shouldn’t reduce ’base em’ to less than 0.33333em (≈ width of a single space).

You want to know how to select the flexible column format and how to reset

to fixed columns? Try flexiblecolumns=true and flexiblecolumns=false.

3.9 Selecting other languages

You already know that language=⟨language name⟩ selects programming languages — at least Pascal and Fortran. But that’s not the whole truth. Both languages know different dialects (= version or implementation), for example Fortran 77 and Fortran 90. You can choose such special versions with the optional argument of

language. Write
    \lstset{language=[77]Fortran}% Fortran 77
    \lstset{language=[XSC]Pascal}% Pascal XSC

to select Fortran 77 and Pascal XSC, respectively.

We give a list of all languages and dialects supported by lstdrvrs.dtx. Use the given names as (optional) values to language. An ’empty’ language is also defined: \lstset{language={}} detects no keywords, no comments, no strings, …

Ada  Lisp
Algol (68,60)  Logo

       C (ANSI,Objective)  Matlab

Cobol (1985,1974,ibm) Mercury
Comal 80  Modula-2
C++ (ANSI,Visual)  Oberon-2

       csh  Pascal (Standard,XSC,Borland6)

Delphi  Perl
Eiffel  PL/I
Elan  Prolog
Euphoria  Simula (67,CII,DEC,IBM)
Fortran (95,90,77)  SQL

       IDL  TeX (plain,primitive,LaTeX,alLaTeX)

HTML  VHDL

Java

The configuration file listings.cfg defines each first dialect as default dialect, i.e. \lstset{language=C} selects ANSI C. After

    \lstset{defaultdialect=[Objective]C}

Objective-C becomes default dialect for C, but the language is not selected with that command.

Remark: The driver files define the languages with \lstdefinelanguage. The languages have all ’bugs’ coming from the language commands, e.g. in Ada and Matlab it is still possible that the package assumes a string where none exists. See lstdrvrs.dtx for more remarks on special programming languages.

4 Main reference

In this section we list all user environments, commands and keys together with their parameters and possible values. Sometimes there are examples or more detailed information at the end of the subsections. All user macros have the prefix lst. This avoids naming conflicts with other packages or document classes.

In the sequel the label changed indicates any change in behaviour or syntax of a command, environment or key, so read these items carefully. Keys strongly related to special programming languages have the label lang.spec.. Usually they are available only if you have loaded the corresponding programming language. All other labels should be clear. The numbers in the right margin give the version number of introduction (either as internal or as user macro/key).

Note that commands, environments and keys can be distinguished easily: A command begins with a backslash and a key is presented in ”key=⟨value⟩” fashion. All the rest are environments, which is in fact a single one.

4.1 Typesetting listings

changed 0.1 \lstinputlisting[⟨key=value list⟩]{⟨file name⟩}

typesets the source code file using the active language and style (locally modified by the key=value list). Empty lines at the end of listing are dropped.

The keys first and last determines the printed line range. Default is always 1–9999999, where ’always’ means that you can’t set first and last globally. If you don’t want a whole file, you must specify the line range. The

example \lstinputlisting[first=3,last=10]{testfile.pas} would print

lines 3,4,…,10 of testfile.pas if file and lines are present.

The boolean key print controls whether or not \lstinputlisting typesets a listing: print=false speed up things for draft versions of your document and print=true typesets the stand alone files.

Note: The keys first, last and print only apply to \lstinputlisting.

changed 0.15 lstlisting[⟨key=value list⟩]{⟨name⟩}

typesets source code between \begin{lstlisting}{⟨name⟩} (+ line break) and \end{lstlisting}, but empty lines at the end of listing are dropped. Characters on the same line as the end of environment are not dropped, i.e. source code right before and L^{A}TEX code after the end of environment is typeset respectively executed. If ⟨name⟩ is not empty and the listing is not continued, the name appears in the list of listings. Same named listings have common line counter, i.e. the second (same named) listing continues the first, the third continues the second, and so on. There are two exceptions: An empty named listing always starts with line number 1 and is continued with listings named { } (single blank space).

The key resetlineno (given without any value) sets the line number of the first line to 1. You can also specify a number, e.g. resetlineno=10. advancelineno=⟨number⟩ advances the number of the first line by ⟨number⟩. These two keys take also effect on {} and { } named listings.

Note: The keys resetlineno and advancelineno only apply to the environment and must be used in the optional key=value list.

new  0.18 \lstinline

works like \verb, but uses the active language and style, of course. You can write ’\lstinline!var i:integer;!’ and get ’var i:integer;’. Note that these listings always use flexible columns and that \lstinline has no optional key=value list.

new 0.18 \lstbox[⟨b|c|t⟩]

is used right before \lstinputlisting or a listing environment. Without \lstbox the listing uses a new paragraph and the complete line width, even if the listing is one character wide. \lstbox returns the listing as a \hbox, which has the necessary width only (line numbers possibly not included). Use this command within explicit \hboxes, $$… $$, etc.. The optional argument gives the vertical position of the listing: bottom, center (default) or top.

4.2 List of listings

0.16 \listoflistings

prints a list of listings. The names are the file names or names of the listings.

0.16 \listlistingsname

contains the header name, which is ’Listings’ by default. You may adjust it

via \renewcommand\listlistingsname{whatever}.
new  0.19 \lstname

contains the name of the current (last) listing in printable form. After pre=\subsubsection{\lstname} each listing begins a new subsubsection, which name is the listing name. The key pre is described in section 4.7. You can also use it to index all listings, but then you must expand the con-

tent first. Simply write \expandafter\index\expandafter{\lstname} (as

value to pre if you want).

new  0.19 \lstintname

contains the name of the current (last) listing possibly in nonprintable form. Use this macro inside \label and \ref for example. But be aware that a reference counter must be defined — or the label is the current section, subsection, and so on. You might use it like this:

    \lstset{pre=\caption{\lstname}\label{lst\lstintname}}
    \begin{figure}
    \begin{lstlisting}{Empty}
    \end{lstlisting}
    \end{figure}
    Figure \ref{lstEmpty} shows an empty listing.

Here all listings get a caption and a label (unless pre is redefined).

4.3 Basic style keys

new 0.18 basicstyle=⟨basic style and size⟩

0.11 keywordstyle=⟨style for keywords⟩

new,optional 0.19 ndkeywordstyle=⟨style for second keywords⟩

new,optional 0.19 rdkeywordstyle=⟨style for third keywords⟩

new  0.18 nonkeywordstyle=⟨style⟩
0.11 commentstyle=⟨style⟩
0.12 stringstyle=⟨style⟩
0.16 labelstyle=⟨style⟩

Each value of these keys determines the font and size (or more general style) in which special parts of a listing appear. The last token of the (non,nd,rd) keyword and label style might be an one-parameter command like \textbf

or \underline.

bug 0.16 labelstep=⟨step⟩

No line numbers are printed if ⟨step⟩ is zero. Otherwise all lines with ”line number ≡ 0 modulo ⟨step⟩” get a label, which appearance is controlled by the label style.

Bug: If a comment (or string) goes over several lines, the line numbers (if on) also have comment (string) style. The easiest work-around is possibly

the use of \normalfont in \lstlabelstyle.

0.12 blankstring=⟨true|false⟩

let blank spaces in strings appear as blank spaces respectively as . The latter is predefined.

0.12 tabsize=⟨number⟩

sets tabulator stops at columns n + 1, 2n + 1, 3n + 1, etc. if n =⟨number⟩. Each tabulator in a listing moves the current column to the next tabulator stop. It is initialized with tabsize=8.

new 0.19 formfeed=⟨token sequence⟩

Whenever a listing contains a form feed ⟨token sequence⟩ is executed. It is

initialized with formfeed=\bigbreak.

4.4 Fixed and flexible columns

new 0.18 flexiblecolumns=⟨true|false⟩

selects the flexible respectively the fixed column format.

addon 0.16 baseem=⟨width in units of em⟩ or baseem={⟨fixed⟩,⟨flexible mode⟩}

sets the width of a single character box for fixed and flexible mode (both to the same value or individually). It’s pre-defined via baseem={0.6,0.45}.

4.5 Listing alignment

new 0.19 indent=⟨dimension⟩

indents each listing by ⟨dimension⟩, which is initialized with 0pt. This command is the best way to move line numbers (and the listing) to the right.

new 0.19 wholeline=⟨true|false⟩

prevents or lets the package use indention from list environments like

enumerate or itemize.

bug,addon 0.16 spread=⟨dimension⟩ or spread={⟨inner⟩,⟨outer⟩}

defines additional line width for listings, which may avoid overfull \hboxes if a listing has long lines. The inner and outer spread is given explicitly or is equally shared. It is initialized via spread=0pt. For one sided documents ’inner’ and ’outer’ have the effect of ’left’ and ’right’. Note that \lstbox doesn’t use this spread but indent (which is always ’left’).

Bug (two sided documents): At top of page it’s possible that the package uses inner instead of outer spread or vice versa. This happens when TEX finally moves one or two source code lines to the next page, but hasn’t decided it when the listings package processes them. Work-around: interrupt the listing and/or use an explicit \newpage.

0.17 lineskip=⟨additional space between lines⟩

specifies the additional space between lines in listings. You may write

lineskip=-1pt plus 1pt minus 0.5pt for example, but 0pt is the default.

new 0.19 outputpos=⟨c|l|r⟩

controls horizontal orientation of smallest output units (keywords, identifiers, etc.). The arguments work as follows, where vertical 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 resp. | listing |, |listing | and | listing| with flexible columns (using pre-defined baseem). By default the output is centered. To make all things clear: You may write

outputpos=c, outputpos=l or outputpos=r.

4.6 Escaping to L^{A}TEX

Note: Any escape to L^{A}TEX may disturb the column alignment since the package can’t control the spacing there.

new 0.18 texcl=⟨true|false⟩

activates or deactivates L^{A}TEX comment lines, see the example below.

new 0.19 mathescape=⟨true|false⟩

activates or deactivates special behaviour of the dollar sign. If activated, a dollar sign acts as TEX’s text math shift (not display style!).

new 0.19 escapechar=⟨single character⟩ (or empty)

The given character escapes the user to L^{A}TEX: All code between two such characters is interpreted as L^{A}TEX code. Note that TEX’s special characters must be entered with a preceding backslash, e.g. escapechar=\%.

Some examples clarify these commands. Since texcl only makes sense with comment lines, we will use C++ comment lines here (without saying how to define them). Note that only the first example runs through a C++ compiler if the source code is placed in a separate file. All L^{A}TEX escapes are local here, but you can also use \lstset.

// calculate a_{ij}

A[ i ] [ j ] = A[ j ] [ j ]/ A[ i ] [ j ] ;

                                   \begin{lstlisting}[texcl]{}
                                   // calculate $a_{ij}$
                                     A[i][j] = A[j][j]/A[i][j];
                                   \end{lstlisting}

// c a l c u l a t e a_{ij} a_{ij} = a_{jj}/a_{ij};

                                   \begin{lstlisting}[mathescape]{}
                                   // calculate $a_{ij}$
                                     $a_{ij} = a_{jj}/a_{ij}$;
                                   \end{lstlisting}

// calc ulate a_{ij} a_{ij} = a_{jj}/a_{ij};

                                   \lstset{escapechar=\%}
                                   \begin{lstlisting}{}
                                   // calc%ulate $a_{ij}$%
                                     %$a_{ij} = a_{jj}/a_{ij}$%;
                                   \end{lstlisting}

In the first example the whole comment line is typset in ’L^{A}TEX mode’ — except the comment line indicators //. Note that texcl uses comment style. In the second example the comment line upto a_{ij} have been typeset in comment style and by the listings package. The ’a_{ij}’ itself is typeset in ’TEX math mode’ without comment style. About the half comment line of the third example have been typeset by this package. The rest is in ’L^{A}TEX mode’ without comment style.

To avoid problems with the current and future version of this package:

1. Don’t use any command of the listings package when you have escaped to L^{A}TEX.

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 are present later — except they are \global.

4. \if \else \fi, groups, math shifts $ and $$, … must be balanced each escape.

5….

Expand that list yourself and mail me about new items.

4.7 Some special keys

new 0.18 extendedchars=⟨true|false⟩

allows or prohibits extended characters in listings, i.e. characters with codes 128–255. If you use extended characters, you should load the inputenc or fontenc package!

new,lang.spec. 0.19 printpod=⟨true|false⟩

prints or drops PODs in Perl.

addon 0.12 pre=[⟨continue⟩]{⟨commands to execute⟩}

addon 0.12 post=[⟨continue⟩]{⟨commands to execute⟩}

The given control sequences are executed before and after typesetting resp. when continuing a listing, but in all cases inside a group. The commands are not executed if you use \lstbox or \lstinline (since the user given pre and post commands are assumed to be unsave inside \hbox). By default ⟨continue⟩ is empty. The other arguments are pre-set empty.

A simple prelisting example.

{ Get listings .dtx . Now! }

We continue the listing.

{ You have it already? Good. }

We continue the listing.

{ Tell your friends about it . }

                                   \lstset{flexiblecolumns}
                                   \lstset{pre=[%
                                       We continue the listing.
                                     ]A simple prelisting example.}
                                   \begin{lstlisting}{}
                                   { Get listings.dtx. Now! }
                                   \end{lstlisting}
                                   \begin{lstlisting}{ }
                                   { You have it already? Good. }
                                   \end{lstlisting}
                                   \begin{lstlisting}{ }
                                   { Tell your friends about it. }
                                   \end{lstlisting}

4.8 Languages and styles

changed 0.17 language=[⟨dialect⟩]⟨language name⟩

activates a (dialect of a) programming language. All arguments are case insensitive here.

new 0.19 \lstloadlanguages{⟨list of languages⟩}

can only be used in the preamble. It loads all specified languages, where each language is given in the form [⟨dialect⟩]⟨language⟩. List of languages means a comma separated list.

new 0.18 style=⟨style name⟩

activates a style. The arguments is case insensitive.

new 0.19 \lstdefinestyle{⟨style name⟩}{⟨key=value list⟩}

stores the key=value list: You can select the style via style using te style name as argument.

After package loading a ’standard’ style and an ’empty’ language are active. The style is defined as follows.

\lstdefinestyle{}
{basicstyle={},
keywordstyle=\bfseries,nonkeywordstyle={},
commentstyle=\itshape,
stringstyle={},
labelstyle={},labelstep=0
}

4.9 Language definitions

new 0.19 \lstdefinelanguage[⟨dialect⟩]{⟨language⟩}{⟨key=value list⟩}

defines a programming language. Use any ’language’ key=value list and the definition is yours. new 0.19 \lstdefinedrvlanguage[⟨dialect⟩]{⟨language⟩}{⟨key=value list⟩}

defines a programming language only if the user has requested the language. Thus this command can only be used in driver files.

new 0.19 defaultdialect=[⟨dialect⟩]⟨language⟩

defines a default dialect for a language, that means a dialect which is selected whenever you leave out the optional dialect. If you have defined a default dialect other than empty, for example defaultdialect=[iama]fool, you can’t select the ’empty’ dialect, even not with language=[]fool.

Note that a configuration file possibly defines some default dialects.

new 0.18 \lstalias{⟨alias⟩}{⟨language⟩}

defines an alias for a programming language. Any dialect of ⟨alias⟩ selects in fact the same dialect of ⟨language⟩. It’s also possible to define an alias for one dialect: \lstalias[⟨dialect alias⟩]{⟨alias⟩}[⟨dialect⟩]{⟨language⟩}. Here all four parameters are nonoptional. An alias with empty ⟨dialect⟩ will select the default dialect. Note that aliases can’t be nested: The two aliases

\lstalias{foo1}{foo2} and \lstalias{foo2}{foo3} redirect foo1 not to
foo3.

Note that a configuration file possibly defines some aliases.

new 0.18 \lststorekeywords⟨macro⟩{⟨keywords⟩}

stores ⟨keywords⟩ in ⟨macro⟩ for use with keyword keys. This command can’t be used in a language definition since it is a command and not a key.

Now come all the language keys, which might be used in the key=value list of \lstdefinelanguage. Note: If you want to enter \, {, }, %, # or & inside or as an argument here, you must do it with a preceding backslash!

0.11 keywords={⟨keywords⟩}

0.11 morekeywords={⟨additional keywords⟩}

new 0.18 deletekeywords={⟨keywords to remove⟩}

new,optional 0.19 ndkeywords={⟨second keywords⟩}

new,optional 0.19 morendkeywords={⟨additional second keywords⟩}

new,optional 0.19 deletendkeywords={⟨second keywords to remove⟩}

new,optional 0.19 rdkeywords={⟨third keywords⟩}

new,optional 0.19 morerdkeywords={⟨additional third keywords⟩}

new,optional 0.19 deleterdkeywords={⟨third keywords to remove⟩}

Each ’keyword’ argument (here and below) is a list of keywords separated by commas. You might use macros defined with \lststorekeywords as elements (i.e. also separated by commas). keywords={save,Test,test} defines three keywords (if keywords are case sensitive). If you want to remove them all, simply write keywords={} — in \lstset’s argument, in an optional argument or in a language definition. The characters \, {, and } (entered as \\, \{ and \}) are not allowed within a keyword. You might use each of !”#$%&’()+−./:;?[]‘. But note that you must enter \#, \% and \& instead of #, % and &.

0.14 sensitive=⟨true|false⟩

makes the keywords (first, second and third) case sensitive resp. insensitive. This key affect the keywords only in the phase of typesetting. In all other situations keywords are case sensitive, i.e. deletekeywords={save,Test} removes ’save’ and ’Test’, but neither ’SavE’ nor ’test’.

new 0.19 alsoletters={⟨character sequence⟩}

new 0.19 alsodigits={⟨character sequence⟩}

new 0.19 alsoother={⟨character sequence⟩}

These keys support the ’special character’ auto-detection of the keyword commands. For our purpose here, identifiers are out of letters (A–Z,a– z,_,@,$) and digits (0–9), but an identifier must begin with a letter. If you write keywords={one-two,\#include}, the minus becomes necessarily a digit and the sharp a letter since the keywords can’t be detected otherwise. The three keys overwrite such default behaviour. Each character of the sequence becomes a letter, digit and other, respectively. Note that the auto-detection might fail if you remove keywords and always fails if you use special characters not listed above.

new 0.19 stringtest=⟨true|false⟩

enables or disables string tests: If activated, line exceeding strings issue warnings and the package exits string mode.

addon 0.12 stringizer=[⟨b|d|m|bd⟩]{⟨character sequence⟩}

Each character might start a string or character literal. ’Stringizers’ match each other, i.e. starting and ending delimiters are the same. The optional argument controls how the stringzier(s) itself is/are represented in a string or character literal: It is preceded by a backslash, doubled (or both is allowed via bd) or it is matlabed. The latter one is a special type for Ada and Matlab and possibly more languages, where the stringizers are also used for other purposes. In general the stringizer is also doubled, but a string does not start after a letter or a right parenthesis.

new,lang.spec. 0.19 texcs={⟨list of control sequences (without backslashes)⟩}

defines control sequences for TEX and L^{A}TEX.

new,lang.spec. 0.18 cdirectives={⟨list of compiler directives⟩}

defines compiler directives in C, C++ and Objective-C.

If you have already defined any of the following comments and you want to remove it, let all arguments to the comment key empty.

changed 0.13 commentline=⟨1or2 chars⟩

The characters (in the given order) start a comment line, which in general starts with the comment separator and ends at end of line. If the character sequence // starts a comment line (like in C++, Comal 80 or Java), commentline=// is the correct declaration. For Matlab it would be commentline=\% — note the preceding backslash.

new 0.18 fixedcommentline=[⟨n=preceding columns⟩]{⟨character sequence⟩}

Each given character becomes a ’fixed comment line’ separator: It starts a comment line if and only if it is in column n + 1. Fortran 77 declares its comments via fixedcommentline={*Cc} (n = 0 is default).

changed 0.13 singlecomment={⟨1or2 chars⟩}{⟨1or2 chars⟩}

changed 0.13 doublecomment={⟨1or2 chars⟩}{⟨1or2 chars⟩}{⟨1or2 chars⟩}{⟨1or2 chars⟩}

Here we have two or four comment separators. The first starts and the second ends a comment, and similarly the third and fourth separator for double comments. If you need three such comments use singlecomment and doublecomment at the same time. C, Java, PL/I, Prolog and SQL all define single comments via singlecomment={/*}{*/}, and Algol does it with singlecomment={\#}{\#}, which means that the sharp delimits both beginning and end of a single comment.

changed 0.13 nestedcomment={⟨1or2 chars⟩}{⟨1or2 chars⟩}

is similar to singlecomment, but comments can be nested. Identical arguments are not allowed — think a while about it! Modula-2 and Oberon-2

use nestedcomment={(*}{*)}.

lang.spec. 0.17 keywordcomment={⟨keywords⟩}

lang.spec. 0.17 doublekeywordcommentsemicolon={⟨keywords⟩}{⟨keywords⟩}{⟨keywords⟩}

A (paired) keyword comment begins with a keyword and ends with the same keyword. Consider keywordcomment={comment,co}. Then ’comment … comment’ and ’co… co’ are comments. Defining a double keyword comment (semicolon) needs three keyword lists, e.g. {end}{else,end}{comment}. A semicolon always ends such a comment. 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 the next 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.

5 Experimental features

This section describes the more or less unestablished parts of the listings package. It’s unlikely that they are removed, but they are liable to (heavy) changes and maybe improvements.

5.1 Interface 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 also possible with listings, but you must find somebody who implements them ; – ). The fancyvrb package is

available from CTAN: macros/latex/contrib/supported/fancyvrb.

new 0.19 fancyvrb=⟨true|false⟩

activates or deactivates the interface. This defines an appropiate version of \FancyVerbFormatLine to make the two packages work together. If active, the verbatim code read by the fancyvrb package is typeset by the listings package, i.e. with emphasized keywords, strings, comments, and so on. — You should know that \FancyVerbFormatLine is responsible for the typesetting a single code line.

If fancyvrb and listings provide similar functionality, use fancyvrb’s.

Note that this is the first interface. It works only with Verbatim, neither with BVerbatim nor LVerbatim. And you shouldn’t use defineactive. (As I can see it doesn’t matter since it does nothing at all.) I hope to remove some restrictions in future.

 First verbatim line.
  Second  verbatim line.

  First  verbatim  line.
  Second  verbatim  line.

                                        \lstset{commentline=\ }% :-)
                                        \begin{Verbatim}[commandchars=\\\{\}]
                                        First verbatim line.
                                        \fbox{Second} verbatim line.
                                        \end{Verbatim}
                                        \lstset{fancyvrb}
                                        \begin{Verbatim}[commandchars=\\\{\}]
                                        First verbatim line.
                                        \fbox{Second} verbatim line.
                                        \end{Verbatim}
                                        \lstset{fancyvrb=false}

The last two lines are wider than the first two since baseem equals not the width of a single typewriter character.

5.2 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 shrink to one space, the tabulator and the end of line are converted to spaces, the comment character is not printable, and so on. Hence, you must work a little 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 the line. That’s not enough: Each line must be terminated with a ’line feed’ ^^J. Finally you can’t escape to L^{A}TEX 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!\\\{\}\%!}}

yields^{1} if the current language is Pascal. The environment possibly needs a preceding \lstbox, as the following examples show.

!”#$ %&’()∗+,−./

0123456789:;<=>? @ABCDEFGHIJKLMNO

PQRSTUVWXYZ[ \] ˆ
‘ abcdefghijklmno
pqrstuvwxyz {|}˜

                                   \fbox{\lstbox
                                   \begin{lstlisting}{}^^J
                                   \ !"#$\%&'()*+,-./^^J
                                   0123456789:;<=>?^^J
                                   @ABCDEFGHIJKLMNO^^J
                                   PQRSTUVWXYZ[\\]^_^^J
                                   `abcdefghijklmno^^J
                                   pqrstuvwxyz\{|\}~^^J
                                   \end{lstlisting}}

We need no p r o t e c t i o n here ,
but in t h i s l i n e .

                                   \fbox{\lstbox
                                   \begin{lstlisting}{}^^J
                                   We need no protection here,^^J
                                   \ but\ \ in\ \ this\ \ line.^^J
                                   \end{lstlisting}}

5.3 Frames

new 0.19 frame=⟨any subset of tlrbTLRB⟩

The characters tlrbTLRB are attached to lines at the top of a listing, on the left, right and at the bottom. There are two lines if you use upper case letters. If you want a single frame around a listing, write frame=tlrb or frame=bltr for example (but as optional argument or argument to \lstset, of course). If you want double lines at the top and on the left and no other lines, write frame=TL. Note that frames reside outside the listing’s space. Use spread if you want to shrink frames (to \linewidth for example) and use indent if you want to move line number inside frames.

new 0.19 framerulewidth=⟨dimension⟩

new 0.19 framerulesep=⟨dimension⟩

These keys control the width of the rules and the space between double rules. The predefined values are .4pt width and 2pt separation.

frame does not work with \lstbox or fancyvrb=true! And there are certainly more problems with other commands. Take the time to report in.

                                   \begin{lstlisting}[frame=tLBr]{}
                                   for i:=maxint to 0 do

                                   begin

                                       { do nothing }
                                   end;
                                   \end{lstlisting}

for i :=maxint to 0 do begin

{ do nothing } end; 1var i:integer; and protected spaces and \{}%

5.4 Export of identifiers

It would be nice to export function or procedure names, for example to index them automatically or to use them in \listoflistings instead of a listing name. In general that’s a dream so far. The problem is that programming languages use various syntaxes for function 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 a pretty printing tool. However, it is possible for particular languages: in Pascal each function or procedure definition and variable declaration is preceded by a particular keyword.

new,optional 0.19 index={⟨identifiers⟩}

⟨identifiers⟩ is a comma-separated list of identifiers. Each appearance of such an identifier is indexed.

new,optional 0.19 indexmacro=⟨’one parameter’ macro⟩

The specified macro gets exactly one parameter, namely the identifier, and must do the indexing. It is predefined as indexmacro=\lstindexmacro, which definition is

         \newcommand\lstindexmacro[1]{\index{{\ttfamily#1}}}

new,optional 0.19 prockeywords={⟨keywords⟩}

⟨keywords⟩ is a comma-separated list of keywords, which indicate a function or procedure definition. Any identifier following such a keyword appears in ’procname’ style. For Pascal you might use

         prockeywords={program,procedure,function}

new,optional 0.19 procnamestyle=⟨style for procedure names⟩

defines the style in which procedure and function names appear.

new,optional 0.19 indexprocnames=⟨true|false⟩

If activated, procedure and function names are also indexed (if used with index option).

6 Troubleshooting

The known bugs have already been described. This section deals with problems concerning not only the listings package.

6.1 Problems with .fd files

You probably get the following error message with a different font definition file:

! LaTeX Error: Command textparagraph unavailable in encoding T1.
See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.68 \P
       rovidesFile{omscmr.fd}
?

So, what happened? (a) The listings package redefines the character table to print listings. (b) L^{A}TEX loads the font definition files on demand. (a) plus (b) gives the error: L^{A}TEX loads the .fd files with modified character table. And that goes wrong. The work-around is quite easy: Input the .fd file before typesetting the listing.

6.2 Language definitions

Language definitions and also some style definitions tend to have long definition parts. This is why we tend to forget commas between the key=value elements. If you select a language and get a Missing = inserted for \ifnum error, this is surely due to a missing comma after keywords=value. If you encounter unexspected characters after selecting a language (or style), you have either forgotten a comma or you have given to many arguments to a key, for example

commentline={--}{!}.

7 Forthcoming

• I’d like to support more languages, for example Maple, Mathematica, PostScript, Reduce and so on. Fortunately my lifetime is limited, so other people may do that work. Write a language definition and (e-)mail it to me (with a proposal in which file to place the definition).

• There will possibly a boolean blanklisting=⟨true|false⟩ or a ∗-version of the environment.

• ’procnames’ is already interesting, but marks (and indexes) only the function definitions so far. It would be quite easy to mark also the following function calls: Write another ’keyword class’ which is empty at the very beginning (and can be reset with a key); each function definition appends a ’keyword’ which will appear in ’procnamestyle’. But this would be another ’keyword test’ within an inner loop.

• I plan to put all language definitions in a single file.