3.4. Simulating typed text

It is often necessary to display information verbatim—that is, “as entered at the terminal”. This ability is provided by the standard LaTeX environment verbatim. However, to guide the reader it might be useful to highlight certain textual strings in a particular way, such as by numbering the lines. Over time a number of packages have appeared that addressed one or the other extra feature—unfortunately, each with its own syntax.

In this section we will review a few such packages. Since they have been used extensively in the past, you may come across them in document sources on the Internet or perhaps have used them yourself in the past. But we then concentrate on the package fancyvrb written by Timothy Van Zandt, which combines all such features and many more under the roof of a single, highly customizable package.

This coverage is followed by a discussion of the listings package, which provides a versatile environment in which to pretty print computer listings for a large number of computer languages.

3.4.1. Simple verbatim extensions

The package alltt (by Leslie Lamport) defines the alltt environment. It acts like a verbatim environment except that the backslash “\” and braces “{” and “}” retain their usual meanings. Thus, other commands and environments can appear inside an alltt environment. A similar functionality is provided by the fancyvrb environment keyword commandchars (see page 161).

3-4-1

In documents where a lot of \verb commands are needed the source soon becomes difficult to read. For this reason the doc package, described in Chapter 14, introduces a shortcut mechanism that lets you use a special character to denote the start and stop of verbatim text, without having to repeatedly write \verb in front of it. This feature is also available in a stand-alone package called shortvrb. With fancyvrb the same functionality is provided, unfortunately using a slightly different syntax (see page 168).

3-4-2

The variant form, \MakeShortVerb*, implements the same shorthand mechanism for the \verb* command. This is shown in the next example.

3-4-3

The package verbatim (by Rainer Schöpf) reimplements the LaTeX environments verbatim and verbatim*. One of its major advantages is that it allows arbitrarily long verbatim texts, something not possible with the basic LaTeX versions of the environments. It also defines a comment environment that skips all text between the commands \begin{comment} and \end{comment}. In addition, the package provides hooks to implement user extensions for defining customized verbatim-like environments.

A few such extensions are realized in the package moreverb (by Angus Duggan). It offers some interesting verbatim-like commands for writing to and reading from files as well as several environments for the production of listings and dealing with tab characters. All of these extensions are also available in a consistent manner with the fancyvrb package, so here we only give a single example to show the flavor of the syntax used by the moreverb package.

3-4-4

3.4.2. upquote—Computer program style quoting

The Computer Modern Typewriter font that is used by default for typesetting “verbatim” is a very readable monospaced typeface. Due to its small running length it is very well suited for typesetting computer programs and similar material. See Section 7.7.4 for a comparison of this font with other monospaced typefaces.

There is, however, one potential problem when using this font to render computer program listings and similar material: most people expect to see a (right) quote in a computer listing represented with a straight quote character (i.e., ') and a left or back quote as a kind of grave accent on its own (i.e., `). The Computer Modern Typewriter font, however, displays real left and right curly quote characters (as one would expect in a normal text font). In fact, most other typewriter fonts when set up for use with LaTeX follow this pattern. This produces somewhat unconventional results that many people find difficult to understand. Consider the following example, which shows the standard behavior for three major typewriter fonts: LuxiMono, Courier, and Computer Modern Typewriter.

3-4-5

This behavior can be changed by loading the package upquote (written by Michael Covington), which uses the glyphs \textasciigrave and \textquotesingle from the textcomp package instead of the usual left and right curly quote characters within \verb or the verbatim environment. Normal typewriter text still uses the curly quotes, as shown in the last line of the example.

3-4-6

The package works well together with “verbatim” extensions as described in this chapter, except for the listings package; it conflicts with the scanning mechanism of that package. If you want this type of quoting with listings simply use the \lstset keyword upquote.

3-4-7

3.4.3. fancyvrb—Highly customizable verbatim environments

The fancyvrb package by Timothy Van Zandt (these days maintained by Denis Girou and Sebastian Rahtz) offers a highly customizable set of environments and commands to typeset and manipulate verbatim text.

It works by parsing one line at a time from an environment or a file (a concept pioneered by the verbatim package), thereby allowing you to preprocess lines in various ways. By incorporating features found in various other packages it provides a truly universal production environment under a common set of syntax rules.

The main environment provided by the package is the Verbatim environment, which, if used without customization, is much like standard LaTeX’s verbatim environment. The main difference is that it accepts an optional argument in which you can specify customization information using a key/value syntax. However, there is one restriction to bear in mind: the left bracket of the optional argument must appear on the same line as \begin. Otherwise, the optional argument will not be recognized but instead typeset as verbatim text.

More than 30 keywords are available, and we will discuss their use and possible values in some detail.

A number of variant environments and commands will be discussed near the end of this section as well. They also accept customization via the key/value method. Finally, we cover possibilities for defining your own variants in a straightforward way.

Customization keywords for typesetting

To manipulate the fonts used by the verbatim environments of the fancyvrb package, four environment keywords, corresponding to the four axes of NFSS, are available. The keyword fontfamily specifies the font family to use. Its default is Computer Modern Typewriter, so that when used without keywords the environments behave in a fashion similar to standard LaTeX’s verbatim. However, the value of this keyword can be any font family name in NFSS notation, such as pcr for Courier or cmss for Computer Modern Sans, even though the latter is not a monospaced font as would normally be used in a verbatim context. The keyword also recognizes the special values tt, courier, and helvetica and translates them internally into NFSS nomenclature.

Because typesetting of verbatim text can include special characters like “\” you must be careful to ensure that such characters are present in the font. This should be no problem when a font encoding such as T1 is active, which could be loaded using the fontenc package. It is, however, not the case for LaTeX’s default font encoding OT1, in which only some monospaced fonts, such as the default typewriter font, contain all such special characters. The type of incorrect output you might encounter is shown in the second line of the next example.

3-4-8

Since all examples in this book are typeset using the T1 encoding this kind of problem will not show up elsewhere in the book. Nevertheless, you should be aware of this danger. It represents another good reason to use T1 in preference to TeX’s original font encoding; for a more in-depth discussion see Section 7.2.4 on page 336.

The other three environment keywords related to the font set-up are fontseries, fontshape, and fontsize. They inherit the current NFSS settings from the surrounding text if not specified. While the first two expect values that can be fed into \fontseries and \fontshape, respectively (e.g., bx for a bold extended series or it for an italic shape), the fontsize is special. It expects one of the higher-level NFSS commands for specifying the font size—for example, \small. If the relsize package is available then you could alternatively specify a change of font size relative to the current text font by using something like \relsize{-2}.

3-4-9

A more general form for customizing the formatting is available through the environment keyword formatcom, which accepts any LaTeX code and executes it at the start of the environment. For example, to color the verbatim text you could pass it something like \color{blue}. It is also possible to operate on each line of text by providing a suitable redefinition for the command \FancyVerbFormatLine. This command is executed for every line, receiving the text from the line as its argument. In the next example every second line is colored in blue, a result achieved by testing the current value of the counter FancyVerbLine. This counter is provided automatically by the environment and holds the current line number.

3-4-10

As shown in the previous example the keyword gobble can be used to remove a number of characters or spaces (up to nine) from the beginning of each line. This is mainly useful if all lines in your environments are indented and you wish to get rid of the extra space produced by the indentation. Sometimes the opposite goal is desired: every line should be indented by a certain space. For example, in this book all verbatim environments are indented by 24pt. This indentation is controlled by the keyword xleftmargin. There also exists a keyword xrightmargin to specify the right indentation, but its usefulness is rather limited, since verbatim text is not broken across lines. Thus, its only visible effect (unless you use frames, as discussed below) is potentially more overfull box messages1 that indicate that your text overfloods into the right margin. Perhaps more useful is the Boolean keyword resetmargins, which controls whether preset indentations by surrounding environments are ignored.

1 Whether overfull boxes inside a verbatim environment are shown is controlled the hfuzz keyword, which has a default value of 2pt. A warning is issued only if boxes protrude by more than the keywords’s value into the margin.

3-4-11

The previous example demonstrates one use of the frame keyword: to draw a frame around verbatim text. By providing other values for this keyword, different-looking frames can be produced. The default is none, that is, no frame. With topline, bottomline, or leftline you get a single line at the side indicated;1lines produces a line at top and bottom; and single, as we saw in Example 3-4-11, draws the full frame. In each case, the thickness of the rules can be customized by specifying a value via the framerule keyword (default is 0.4pt). The separation between the lines and the text can be controlled with framesep (default is the current value of \fboxsep).

If the color package is available, you can color the rules using the environment keyword rulecolor (default is black). If you use a full frame, you can also color the separation between the frame and the text via fillcolor.

3-4-12

Unfortunately, there is no direct way to fill the entire background. The closest you can get is by using \colorbox inside \FancyVerbFormatLine. But this approach will leave tiny white rules between the lines and—without forcing the lines to be of equal length, such as via \makebox—will also result in colored blocks of different widths.

3-4-13

It is possible to typeset text as part of a frame by supplying it as the value of the label keyword. If this text contains special characters, such as brackets, equals sign, or comma, you have to hide them by surrounding them with a brace group. Otherwise, they will be mistaken for part of the syntax. The text appears by default at the top, but is printed only if the frame set-up would produce a line in that position. Alternate positions can be specified by using labelposition, which accepts none, topline, bottomline, or all as values. In the last case the text is printed above and below. If the label text is unusually large you may need to increase the separation between the frame and the verbatim text by using the keyword framesep. If you want to cancel a previously set label string, use the value none—if you really need “none” as a label string, enclose it in braces.

3-4-14

You can, in fact, provide different texts to be placed at top and bottom by surrounding the text for the top position with brackets, as shown in the next example. For this scheme to work frame needs to be set to either single or lines.

3-4-15

By default, the typeset output of the verbatim environments can be broken across pages by LaTeX if it does not fully fit on a single page. This is even true in cases where a frame surrounds the text. If you want to ensure that this cannot happen, set the Boolean keyword samepage to true.

The vertical spacing between lines in a verbatim environment is the same as in normal text, but if desired you can enlarge it by a factor using the keyword baselinestretch. Shrinking so that lines overlap is not possible. If you want to revert to the default line separation, use the string auto as a value.

3-4-16

When presenting computer listings, it is often helpful to number some or all of the lines. This can be achieved by using the keyword numbers, which accepts none, left, or right as a value to control the position of the numbers. The distance between the number and the verbatim text is 12pt by default but it can be adjusted by specifying a different value via the keyword numbersep. Usually, numbering restarts at 1 with each environment, but by providing an explicit number with the keyword firstnumber you can start with any integer value, even a negative one. Alternatively, this keyword accepts the word last to indicate that numbering should resume where it had stopped in the previous Verbatim instance.

3-4-17

Some people prefer to number only some lines, and the package caters to this possibility by providing the keyword stepnumber. If this keyword is assigned a positive integer number, then only line numbers being an integer multiple of that number will get printed. We already learned that the counter that is used internally to count the lines is called FancyVerbLine, so it comes as no surprise that the appearance of the numbers is controlled by the command \theFancyVerbLine. By modifying this command, special effects can be obtained; a possibility where the current chapter number is prepended is shown in the next example. It also shows the use of the Boolean keyword numberblanklines, which controls whether blank lines are numbered (default is false, i.e., to not number them).

3-4-18

In some situations it helps to clearly identify white space characters by displaying all blanks as ⊔. This can be achieved with the Boolean keyword showspaces or, alternatively, the Verbatim* variant of the environment.

Another white space character, the tab, plays an important rôle in some programming languages, so there may be a need to identify it in your source. This is achieved with the Boolean keyword showtabs. The tab character displayed is defined by the command \FancyVerbTab and can be redefined, as seen below. By default, tab characters simply equal eight spaces, a value that can be changed with the keyword tabsize. However, if you set the Boolean keyword obeytabs to true, then each tab character produces as many spaces as necessary to move to the next integer multiple of tabsize. The example input contains tabs in each line that are displayed on the right as spaces with the default tabsize of 8. Note in particular the difference between the last input and output line.

3-4-19

If you wish to execute commands within the verbatim text, then you need one character to act as an escape character (i.e., to denote the beginning of a command name) and two characters to serve as argument delimiters (i.e., to play the rôle that braces normally play within LaTeX). Such special characters can be specified with the commandchars keyword as shown below; of course, these characters then cannot appear as part of the verbatim text. The characters are specified by putting a backslash in front of each one so as to mask any special meaning they might normally have in LaTeX. The keyword commentchar allows you to define a comment character, which will result in ignoring everything following it until and including the next new line. Thus, if this character is used in the middle of a line, this line and the next will be joined together. If you wish to cancel a previous setting for commandchars or commentchar, use the string value “none”.

3-4-20

If you use \label within the verbatim environment, as was done in the previous example, it will refer to the internal line number whether or not that number is displayed. This requires the use of the commandchars keyword, a price you might consider too high because it deprives you of the use of the chosen characters in your verbatim text.

Two other keywords let you change the parsing and manipulation of verbatim data: codes and defineactive. They allow you to play some devious tricks but their use is not so easy to explain: one needs a good understanding of TeX’s inner workings. If you are interested, please check the documentation provided with the fancyvrb package.

Limiting the displayed data

Normally, all lines within the verbatim environment are typeset. But if you want to display only a subset of lines, you have a number of choices. With the keywords firstline and lastline, you can specify the start line and (if necessary) the final line to typeset. Alternatively, you can specify a start and stop string to search for within the environment body, with the result that all lines between (but this time not including the special lines) will be typeset. The strings are specified in the macros \FancyVerbStartString and \FancyVerbStopString. To make this work you have to be a bit careful: the macros need to be defined with \newcommand* and redefined with \renewcommand*. Using \newcommand will not work! To cancel such a declaration is even more complicated: you have to \let the command to \relax, for example,

or ensure that your definition is confined to a group—everything else fails.

3-4-21

You may wonder why one would want to have such functionality available, given that one could simply leave out the lines that are not being typeset. With an environment like Verbatim they are indeed of only limited use. However, when used together with other functions of the package that write data to files and read it back again, they offer powerful solutions to otherwise unsolvable problems.

How the book examples have been produced

For instance, all examples in this book use this method. The example body is written to a file together with a document preamble and other material, so that the resulting file will become a processable LaTeX document. This document is then externally processed and included as an EPS graphic image into the book. Beside it, the sample code is displayed by reading this external file back in but displaying only those lines that lie between the strings \begin{document}and \end{document}. This accounts for the example lines you see being typeset in black. The preamble part, which is shown in blue, is produced in a similar fashion: for this the start and stop strings are redefined to include only those lines lying between the strings \StartShownPreambleCommands and \StopShownPreambleCommands. When processing the example externally, these two commands are simply no-ops; that is, they are defined by the “example” class (which is otherwise close to the article document class) to do nothing. As a consequence, the example code will always (for better or worse) correspond to the displayed result.1

1 In the first edition we unfortunately introduced a number of mistakes when showing code in text that was not directly used.

To write data verbatim to a file the environment VerbatimOut is available. It takes one mandatory argument: the file name into which to write the data. There is, however, a logical problem if you try to use such an environment inside your own environments: the moment you start the VerbatimOut environment, everything is swallowed without processing and so the end of your environment is not recognized. As a solution the fancyvrb package offers the command \VerbatimEnvironment, which, if executed within the \begin code of your environment, ensures that the end tag of your environment will be recognized in verbatim mode and the corresponding code executed.

To read data verbatim from a file, the command \VerbatimInput can be used. It takes an optional argument similar to the one of the Verbatim environment (i.e., it accepts all the keywords discussed previously) and a mandatory argument to specify the file from which to read. The variant \BVerbatimInput puts the typeset result in a box without space above and below. The next example demonstrates some of the possibilities: it defines an environment example that first writes its body verbatim to a file, reads the first line back in and displays it in blue, reads the file once more, this time starting with the second line, and numbers the lines starting with the number 1. As explained above, a similar, albeit more complex definition was used to produce the examples in this book.

3-4-22

An interesting set of sample environments can be found in the package fvrb-ex written by Denis Girou, which builds on the features provided by fancyvrb.

Variant environments and commands

So far, all examples have used the Verbatim environment, but there also exist a number of variants that are useful in certain circumstances. BVerbatim is similar to Verbatim but puts the verbatim lines into a box. Some keywords discussed above (notably those dealing with frames) are not supported, but two additional ones are available. The first, baseline, denotes the alignment point for the box; it can take the values t (for top), c (for center), or b (for bottom—the default). The second, boxwidth, specifies the desired width of the box; if it is missing or given the value auto, the box will be as wide as the widest line present in the environment. We already encountered \BVerbatimInput; it too, supports these additional keywords.

3-4-23

All environments and commands for typesetting verbatim text also have star variants, which, as in the standard LaTeX environments, display blanks as ⊔. In other words, they internally set the keyword showspaces to true.

Defining your own variants

Defining customized variants of verbatim commands and environments is quite simple. For starters, the default settings built into the package can be changed with the help of the \fvset command. It takes one argument, a comma-separated list of key/value pairs. It applies them to every verbatim environment or command. Of course, you can still overwrite the new defaults with the optional argument on the command or environment. For example, if nearly all of your verbatim environments are indented by two spaces, you might want to remove them without having to deploy gobble on each occasion.

3-4-24

However, \fvset applies to all environments and commands, which may not be what you need. So the package offers commands to define your own verbatim environments and commands or to modify the behavior of the predefined ones.

These declarations take three arguments: the name of the new environment or command being defined, the name of the environment or command (without a leading backslash) on which it is based, and a comma-separated list of key/value pairs that define the new behavior. To define new structures, you use \CustomVerbatimEnvironment or \CustomVerbatimCommand and to change the behavior of existing environments or commands (predefined ones as well as those defined by you), you use \RecustomVerbatimEnvironment or \RecustomVerbatimCommand. As shown in the following example, the default values, set in the third argument, can be overwritten as usual with the optional argument when the environment or command is instantiated.

3-4-25

Miscellaneous features

LaTeX’s standard \verb command normally cannot be used inside arguments, because in such places the parsing mechanism would go astray, producing incorrect results or error messages. A solution to this problem is to process the verbatim data outside the argument, save it, and later use the already parsed data in such dangerous places. For this purpose the fancyvrb package offers the commands \SaveVerb and \UseVerb.

The command \SaveVerb takes one mandatory argument, a label denoting the storage bin in which to save the parsed data. It is followed by the verbatim data surrounded by two identical characters (= in the syntax example above), in the same way that \verb delimits its argument. To use this data you call \UseVerb with the label as the mandatory argument. Because the data is only parsed but not typeset by \SaveVerb, it is possible to influence the typesetting by applying a list of key/value pairs or a star as with the other verbatim commands and environments. Clearly, only a subset of keywords make sense, irrelevant ones being silently ignored. The \UseVerb command is unnecessarily fragile, so you have to \protect it in moving arguments.

3-4-26

It is possible to reuse such a storage bin when it is no longer needed, but if you use \UseVerb inside commands that distribute their arguments over a large distance you have to be careful to ensure that the storage bin still contains the desired contents when the command finally typesets it. In the previous example we placed \SaveVerb into the preamble because the use of its storage bin inside the \section command eventually results in an execution of \UseVerb inside the \tableofcontents command.

\SaveVerb also accepts an optional argument in which you can put key/value pairs, though again only a few are relevant (e.g., those dealing with parsing). There is one additional keyword aftersave, which takes code to execute immediately after saving the verbatim text into the storage bin. The next example shows an application of this keyword: the definition of a special variant of the \item command that accepts verbatim text for display in a description environment. It also supports an optional argument in which you can put a key/value list to influence the formatting. The definition is worth studying, even though the amount of mixed braces and brackets seems distressingly complex at first. They are necessary to ensure that the right brackets are matched by \SaveVerb, \item, and \UseVerb—the usual problem, since brackets do not nest like braces do in TeX.1 Also note the use of \textnormal, which is needed to cancel the \bfseries implicitly issued by the \item command. Otherwise, the \emph command in the example would not show any effect since no Computer Modern bold italic face exists.

1 The author confesses that it took him three trials (close to midnight) to make this example work.

3-4-27

In the same way you can save whole verbatim environments using the environment SaveVerbatim, which takes the name of a storage bin as the mandatory argument. To typeset them, \UseVerbatim or \BUseVerbatim (boxed version) with the usual key/value machinery can be used.

Even though verbatim commands or environments are normally not allowed inside footnotes, you do not need to deploy \SaveVerb and the like to get verbatim text into such places. Instead, place the command \VerbatimFootnotes at the beginning of your document (following the preamble!) and from that point onward, you can use verbatim commands directly in footnotes. However, this was only implemented for footnotes—for other commands, such as \section, you still need the more complicated storage bin method described above.

3-4-28

The fancyvrb version of \verb is called \Verb, and it supports all applicable keywords, which can be passed to it via an optional argument as usual. The example below creates \verbx as a variant of \Verb with a special setting of commandchars so that we can execute commands within its argument. We have to use \CustomVerbatimCommand for this purpose, since \verbx is a new command not available in standard LaTeX.

3-4-29

As already mentioned, fancyvrb offers a way to make a certain character denote the start and stop of verbatim text without the need to put \verb in front. The command to declare such a delimiting character is \DefineShortVerb. Like other fancyvrb commands it accepts an optional argument that allows you to set key/value pairs. These influence the formatting and parsing, though this time you cannot overwrite your choices on the individual instance. Alternatively, \fvset can be used, since it works on all verbatim commands and environments within its scope. To remove the special meaning from a character declared with \DefineShortVerb, use \UndefineShortVerb.

3-4-30

Your favorite extensions or customizations can be grouped in a file with the name fancyvrb.cfg. After fancyvrb finishes loading, the package will automatically search for this file. The advantage of using such a file, when installed in a central place, is that you do not have to put your extensions into all your documents. The downside is that your documents will no longer be portable unless you distribute this file in tandem with them.

3.4.4. listings—Pretty-printing program code

A common application of verbatim typesetting is presenting program code. While one can successfully deploy a package like fancyvrb to handle this job, it is often preferable to enhance the display by typesetting certain program components (such as keywords, identifiers, and comments) in a special way.

Two major approaches are possible: one can provide commands to identify the logical aspects of algorithms or the programming language, or the application can (try to) analyze the program code behind the scenes. The advantage of the first approach is that you have potentially more control over the presentation; however, your program code is intermixed with TeX commands and thus may be difficult to maintain, unusable for direct processing, and often rather complicated to read in the source. Examples of packages classified into this category are alg and algorithmic. Here is an example:

3-4-31

The second approach is exemplified in the package listings1 written by Carsten Heinz. This package first analyzes the code, decomposes it into its components, and then formats those components according to customizable rules. The package parser is quite general and can be tuned to recognize the syntax of many different languages (see Table 3.7). New languages are regularly added, so if your target language is not listed it might be worth checking the latest release of the package on CTAN. You may even consider contributing the necessary declarations yourself, which involves some work but is not very difficult.

1 The package version described here is 1.0. Earlier releases used a somewhat different syntax in some cases, so please upgrade if you find that certain features do not work as advertised.

Table 3.7. Languages supported by listings (Winter 2003)

The user commands and environments in this package share many similarities with those in fancyvrb. Aspects of parsing and formatting are controlled via key/value pairs specified in an optional argument, and settings for the whole document or larger parts of it can be specified using \lstset (the corresponding fancyvrb command is \fvset). Whenever appropriate, both packages use the same keywords so that users of one package should find it easy to make the transition to the other.

After loading the package it is helpful to specify all program languages needed in the document (as a comma-separated list) using \lstloadlanguages. Such a declaration does not select a language, but merely loads the necessary support information and speeds up processing.

Program fragments are included inside a lstlisting environment. The language of the fragment is specified with the language keyword. In the following example we set this keyword via \lstset to C and then overwrite it later in the optional argument to the second lstlisting environment.

3-4-32

This example also uses the keyword commentstyle, which controls the layout of comments in the language. The package properly identifies the different syntax styles for comments. Several other such keywords are available as well—basicstyle to set the overall appearance of the listing, stringstyle to format strings in the language, and directivestyle to format compiler directives, among others.

To format the language keywords, keywordstyle and ndkeywordstyle (second order) are used. Other identifiers are formatted according to the setting of identifierstyle. The values for the “style” keywords (except basicstyle) accept a one-argument LaTeX command such as \textbf as their last token. This scheme works because the “identifier text” is internally surrounded by braces and can thus be picked up by a command with an argument.

Thus, highlighting of keywords, identifiers, and other elements is done automatically in a customizable way. Nevertheless, you might want to additionally emphasize the use of a certain variable, function, or interface. For this purpose you can use the keywords emph and emphstyle. The first gets a list of names you want to emphasize; the second specifies how you want them typeset.

3-4-33

If you want to typeset a code fragment within normal text you can use the command \lstinline. The code is delimited in the same way as with the \verb command, meaning that you can choose any character (other than the open bracket) that is not used within the code fragment and use it as delimiter. An open bracket cannot be used because the command also accepts an optional argument in which you can specify a list of key/value pairs.

3-4-34

Of course, it is also possible to format the contents of whole files; for this purpose you use the command \lstinputlisting. It takes an optional argument in which you can specify key/value pairs and a mandatory argument in which you specify the file name to process. In the following example, the package identifies keywords of case-insensitive languages, even if they are written in an unusual mixed-case (WrItE) manner.

3-4-35

Spaces in strings are shown as ⊔ by default. This behavior can be turned off by setting the keyword showstringspaces to false, as seen in the next example. It is also possible to request that all spaces be displayed in this way by setting the keyword showspaces to true. Similarly, tab characters can be made visible by using the Boolean keyword showtabs.

Line numbering is possible, too, using the same keywords as employed with fancyvrb: numbers accepts either left, right, or none (which turns numbering on or off), numberblanklines decides whether blank lines count with respect to numbering (default false), numberstyle defines the overall look and feel of the numbers, stepnumber defines which line numbers will appear (0 means no numbering), and numbersep defines the separation between numbers and the start of the line. By default, line numbering starts with 1 on each \lstinputlisting but this can be changed using the firstnumber keyword. If you specify last as a special value to firstnumber, numbering is continued.

3-4-36

An overall indentation can be set using the xleftmargin keyword, as shown in the previous example, and gobble can be used to remove a certain number of characters (hopefully only spaces) from the left of each line displayed. Normally, indentations of surrounding environments like itemize will be honored. This feature can be turned off using the Boolean keyword resetmargin. Of course, all such keywords can be used together. To format only a subrange of the code lines you can specify the first and/or last line via firstline and lastline; for example, lastline=10 would typeset a maximum of 10 code lines.

Another way to provide continued numbering is via the name keyword. If you define “named” environments using this keyword, numbering is automatically continued with respect to the previous environment with the same name. This allows independent numbering if the need arises.

3-4-37

If a listing contains very long lines they may not fit into the available measure. In that case listings will produce overfull lines sticking out to the right, just like a verbatim environment would do. However, you can direct it to break long lines at spaces or punctuation characters by specifying the keyword breaklines. Wrapped lines are indented by 20pt, a value that can be adjusted through the keyword breakindent.

If desired, you can add something before (keyword prebreak) and after (keyword postbreak) the break to indicate that the line was artificially broken in the listing. We used this ability below to experiment with small arrows and later on with the string “(cont.)” in tiny letters. Both keywords are internally implemented as a TeX \discretionary, which means that they accept only certain input (characters, boxes, and kerns). For more complicated material it would be best to wrap everything in an \mbox, as we did in the example. In case of color changes, even that is not enough: you need an extra level of braces to prevent the color \special from escaping from the box (see the discussion in Appendix A.2.5).

The example exhibits another feature of the breaking mechanism—namely, if spaces or tabs appear in front of the material being broken, then these spaces are by default repeated on continuation lines. If this behavior is not desired, set the keyword breakautoindent to false as we did in the second part of the example.

3-4-38

You can put frames or rules around listings using the frame keyword, which takes the same values as it does in fancyvrb (e.g., single, lines). In addition, it accepts a subset of the string trblTRBL as its value. The uppercase letters stand for double rules the lowercase ones for single rules. There are half a dozen more keywords: to influence rule widths, create separation from the text, make round corners, and so on—all of them are compatible with fancyvrb if the same functionality is provided.

3-4-39

You can specify a caption for individual listings using the keyword caption. The captions are, by default, numbered and prefixed with the string Listing stored in \lstlistingname. The counter used is lstlisting; thus, to change its appearance you could modify \thelstlisting. The caption is positioned either above (default) or below the listing, and this choice can be adjusted using the keyword captionpos.

To get a list of all captions, put the command \lstlistoflistings at an appropriate place in your document. It produces a heading containing the words stored in \lstlistlistingname (default is Listings). If you want the caption text in the document to differ from the caption text in the list of listings, use an optional argument as shown in the following example. Note that in this case you need braces around the value to hide the right bracket. To prevent the caption from appearing in the list of listings, use the keyword nolol with a value of true. By using the keyword label you can specify a label for referencing the listing number via \ref, provided you have not suppressed the number.

3-4-40

The keyword frameround used in the previous example allows you to specify round corners by giving t for true and f for false, starting with the upper-right corner and moving clockwise. This feature is not available with fancyvrb frames.

Instead of formatting your listings within the text, you can turn them into floats by using the keyword float, typically together with the caption keyword. Its value is a subset of htbp specifying where the float is allowed to go (using it without a value is equivalent to tbp). You should, however, avoid mixing floating and nonfloating listings as this could sometimes result in captions being numbered out of order, as in Example 6-3-5 on page 296.

By default, listings only deals with input characters in the ASCII range; unexpected 8-bit input can produce very strange results, like the misordered letters in the following example. By setting extendedchars to true you can enable the use of 8-bit characters, which makes the package work harder, but (usually) produces the right results. Of course, if you use an extended character set you would normally add the keyword to the \lstset declaration instead of specifying it every time on the environment. It is also possible to specify an input encoding for the code fragments (if different from the input encoding used for the remainder of the document) by using the keyword inputencoding. This keyword can be used only if the inputenc package is loaded.

3-4-41

The package offers many more keys to influence the presentation. For instance, you can escape to LaTeX for special formatting tricks, display tab or form-feed characters, index certain identifiers, or interface to hyperref so that clicking on some identifier will jump to the previous occurrence. Some of the features are still considered experimental and you have to request them using an optional argument during package loading. These are all documented in great detail in the manual (roughly 50 pages) accompanying the package.

As a final example of the kind of treasures you can find in that manual, look at the following example. It shows code typesetting as known from Donald Knuth’s literate programming conventions.