3.3. List structures

Lists are very important LaTeX constructs and are used to build many of LaTeX’s display-like environments. LaTeX’s three standard list environments are discussed in Section 3.3.1, where we also show how they can be customized. Section 3.3.2 starting on page 132 provides an in-depth discussion of the paralist package, which introduces a number of new list structures and offers comprehensive methods to customize them, as well as the standard lists. It is followed by a discussion of “headed lists”, such as theorems and exercises. Finally, Section 3.3.4 on page 144 discusses LaTeX’s general list environment.

3.3.1. Modifying the standard lists

It is relatively easy to customize the three standard LaTeX list environments itemize, enumerate, and description, and the next three sections will look at each of these environments in turn. Changes to the default definitions of these environments can either be made globally by redefining certain list-defining parameters in the document preamble or can be kept local.

Customizing the itemize list environment

For a simple unnumbered itemize list, the labels are defined by the commands shown in Table 3.5. To create a list with different-looking labels, you can redefine the label-generating command(s). You can make that change local for one list, as in the example below, or you can make it global by putting the redefinition in the document preamble. The following simple list is a standard itemize list with a marker from the PostScript Zapf Dingbats font (see Section 7.6.4 on page 378) for the first-level label:

Image

Table 3.5. Commands controlling an itemize list environment

3-3-1
Image
Customizing the enumerate list environment

LaTeX’s enumerated (numbered) list environment enumerate is characterized by the commands and representation forms shown in Table 3.6 on the next page. The first row shows the names of the counter used for numbering the four possible levels of the list. The second and third rows are the commands giving the representation of the counters and their default definition in the standard LaTeX class files. Rows four, five, and six contain the commands, the default definition, and an example of the actual enumeration string printed by the list.

Image

Table 3.6. Commands controlling an enumerate list environment

A reference to a numbered list element is constructed using the heenumi, heenumii, and similar commands, prefixed by the commands p@enumi, p@enumii, etc., respectively. The last three rows in Table 3.6 on the following page show these commands, their default definition, and an example of the representation of such references. It is important to consider the definitions of both the representation and reference-building commands to get the references correct.

We can now create several kinds of numbered description lists simply by applying what we have just learned.

Our first example redefines the first- and second-level counters to use capital Roman digits and Latin characters. The visual representation should be the value of the counter followed by a dot, so we can use the default value from Table 3.6 on the next page for labelenumi.

3-3-2
Image

After these redefinitions we get funny-looking references; to correct this we have to adjust the definition of the prefix command p@enumii. For example, to get a reference like “I–A” instead of “IA” as in the previous example, we need

Image

because the reference is typeset by executing p@enumii followed by heenumii. Note that we need makeatletter and makeatother because the command name to redefine contains an @ sign. Instead of this low-level method, consider using labelformat from the varioref package described in Section 2.4.2.

You can also decorate an enumerate field by adding something to the label field. In the example below, we have chosen for the first-level list elements the paragraph sign (§) as a prefix and a period as a suffix (omitted in references).

3-3-3
Image

You might even want to select different markers for consecutive labels. For instance, in the following example, characters from the PostScript font ZapfDingbats are used. In this case there is no straightforward way to automatically make the ef commands produce the correct references. Instead of heenumi simply producing the representation of the enumi counter, we define it to calculate from the counter value which symbol to select. The difficulty here is to create this definition in a way such that it survives the label-generating process. The trick is to add the protect commands so that setcounter and ding are not executed when the label is written to the .aux file, yet to ensure that the current value of the counter is stored therein. The latter goal is achieved by prefixing value by the (internal) TeX command he within setcounter (but not within ding!); without it the references would all show the same values.1

1 For the TeXnically interested: LaTeX’s value command, despite its name, does not produce the “value” of a LaTeX counter but only its internal TeX register name. In most circumstances this can be used as the value but unfortunately not inside edef or write, where the internal name rather than the “value” will survive. By prefixing the internal register name with the command he, we get the “value” even in such situations.

3-3-4
Image

The same effect is obtained with the dingautolist environment defined in the pifont package, which is part of the PSNFSS system (see Section 7.6.4 on page 378).

Customizing the description list environment

With the description environment you can change the descriptionlabel command that generates the label. In the following example the font for typesetting the labels is changed from boldface (default) to sans serif.

3-3-5
Image

The standard LaTeX class files set the starting point of the label box in a description environment at a distance of labelsep to the left of the left margin of the enclosing environment. Thus, the descriptionlabel command in the example above first adds a value of labelsep to start the label aligned with the left margin (see page 147 for detailed explanations).

3.3.2. paralist—Extended list environments

The paralist package created by Bernd Schandl provides a number of new list environments and offers extensions to LaTeX’s standard ones that make their customization much easier. Standard and new list environments can be nested within each other and the enumeration environments support the label/ ef mechanism.

Enumerations

All standard LaTeX lists are display lists; that is, they leave some space at their top and bottom as well as between each item. Sometimes, however, one wishes to enumerate something within a paragraph without such visual interruption. The inparaenum environment was developed for this purpose. It supports an optional argument that you can use to customize the generated labels, the exact syntax of which is discussed later in this section.

3-3-6
Image

But perhaps this is not precisely what you are looking for. A lot of people like to have display lists but prefer them without much white space surrounding them. In that case compactenum might be your choice, as it typesets the list like enumerate but with all vertical spaces set to 0pt.

3-3-7
Image

Actually, our previous statement was not true—you can customize the vertical spaces used by compactenum. Here are the parameters: pltopsep is the space above and below the environment, plpartopsep is the extra space added to the previous space when the environment starts a paragraph on its own, plitemsep is the space between items, and plparsep is the space between paragraphs within an item.

A final enumeration alternative is offered with the asparaenum environment, which formats the items as individual paragraphs. That is, their first line is indented by parindent and following lines are aligned with the left margin.

3-3-8
Image

As seen in the previous examples all enumeration environments support one optional argument that describes how to format the item labels. Within the argument the tokens A, a, I, i, and 1 have a special meaning: they are replaced by the enumeration counter displayed in style Alph, alph, Roman, oman, or arabic, respectively. All other characters retain their normal meanings. Thus, the argument [(a)] will result in labels like (a), (b), (c), and so on, while [S i:] will produce §i:, §ii:, §iii:, and so on.

You have to be a bit careful if your label contains text strings, such as labels like Example 1, Example 2, ... In this case you have to hide the “a” inside a brace group—that is, use an argument like [{Example} 1]. Otherwise, you will get strange results, as shown in the next example.

3-3-9
Image

Fortunately, the package usually detects such incorrect input and will issue a warning message. A consequence of hiding special characters by surrounding them with braces is that an argument like [ extbf{a)}] will not work either, because the “a” will not be considered as special any more. A workaround for this case is to use something that does not require braces, such as fseries.

As can be seen above, referencing a label will produce only the counter value in the chosen representation but not any frills added in the optional argument. This is the case for all enumeration environments.

It is not possible with this syntax to specify that a label should show the outer as well as the inner enumeration counter, because the special characters always refer to the current enumeration counter. There is one exception: if you load the package with the option pointedenum or with the option pointlessenum, you will get labels like those shown in the next example.

3-3-10
Image

The difference between the two options is the presence or absence of the trailing period. As an alternative to the options you can use the commands pointedenum and pointlessenum. They enable you to define your own environments that format labels in this way while other list environments show labels in different formats. If you need more complicated labels, such as those involving several enumeration counters from different levels, then you have to construct them manually using the methods described in Section 3.3.1 on page 129.

The optional argument syntax for specifying the typesetting of enumeration labels was first implemented in the enumerate package by David Carlisle, who extended the standard enumerate environment to support such an optional argument. With paralist the optional argument is supported for all enumeration environments, including the standard enumerate environment (for which it is an upward-compatible extension).

If an optional argument is used on any of the enumeration environments, then by default the left margin will be made only as wide as necessary to hold the labels. More exactly, the indentation is adjusted to the width of the label as it would be if the counter value is currently seven. This produces a fairly wide number (vii) if the numbering style is “Roman” and does not matter otherwise. This behavior is shown in the next example. For some documents this might be the right behavior, but if you prefer a more uniform indentation use the option neverdecrease, which will ensure that the left margin is always at least as wide as the default setting.

3-3-11
Image

On the other hand, you can always force that kind of adjustment, even for environments without an optional argument, by specifying the option alwaysadjust.

3-3-12
Image

Finally, with the option neveradjust the standard indentation is used in all cases. Thus, labels that are too wide will extend into the left margin.

3-3-13
Image
Itemizations

For itemized lists the paralist package offers the environments compactitem, which is a compact version of the standard itemize environment; asparaitem which formats the items as paragraphs; and inparaitem, which produces an inline itemization. The last environment was added mainly for symmetry reasons. All three environments accept an optional argument, that specifies the label to be used for each item.

3-3-14
Image

The three label justification options neverdecrease, alwaysadjust, and neveradjust are also valid for the itemized lists, as can be seen in the previous example. When the paralist package is loaded, LaTeX’s itemize environment is extended to also support that type of optional argument.

Descriptions

For descriptions the paralist package introduces three additional environments: compactdesc, which is like the standard LaTeX description environment but with all vertical spaces reduced to zero (or whatever you specify as a customization); asparadesc, which formats each item as a paragraph; and inparadesc, which allows description lists within running text.

Because description-type environments specify each label at the item command, these environments have no need for an optional argument.

3-3-15
Image
Adjusting defaults

Besides providing these useful new environments the paralist package lets you customize the default settings of enumerated and itemized lists.

You can specify the default labels for different levels of itemized lists with the help of the setdefaultitem declaration. It takes four arguments (as four levels of nesting are possible). In each argument you specify the desired label (just as you do with the optional argument on the environment itself) or, if you are satisfied with the default for the given level, you specify an empty argument.

3-3-16
Image

The changed defaults apply to all subsequent itemized environments. Normally, such a declaration is placed into the preamble, but you can also use it to change the defaults mid-document. In particular, you can define environments that contain a setdefaultitem declaration which would then apply only to that particular environment—and to lists nested within its body.

You will probably not be surprised to learn that a similar declaration exists for enumerations. By using setdefaultenum you can control the default look and feel of such environments. Again, there are four arguments corresponding to the four levels. In each you either specify your label definition (using the syntax explained earlier) or you leave it empty to indicate that the default for this level should be used.

3-3-17
Image

There is also the possibility of adjusting the indentation for the various list levels using the declaration setdefaultleftmargin. However, this command has six arguments (there are a total of six list levels in the standard LaTeX classes), each of which takes either a dimension denoting the increase of the indention at that level or an empty argument indicating to use the current value as specified by the class or elsewhere. Another difference from the previous declarations is that in this case we are talking about the absolute list levels and not about relative levels related to either enumerations or itemizations (which can be mixed). Compare the next example with the previous one to see the difference.

3-3-18
Image

By default, enumeration and itemized lists set their labels flush right. This behavior can be changed with the help of the option flushleft.

As described earlier, the label of the standard description list can be adjusted by modifying descriptionlabel, which is also responsible for formatting the label in a compactdesc environment. With inparadesc and asparadesc, however, a different command, paradescriptionlabel, is used for this purpose. As these environments handle their labels in slightly different ways, they do not need adjustments involving labelsep (see page 147). Thus, its default definition is simply:

Image

Finally, the paralist package supports the use of a configuration file named paralist.cfg, which by default is loaded if it exists. You can prevent this by specifying the option nocfg.

3.3.3. amsthm—Providing headed lists

The term “headed lists” describes typographic structures that, like other lists such as quotations, form a discrete part of a section or chapter and whose start and finish, at least, must be clearly distinguished. This is typically done by adjusting the vertical space at the start or adding a rule, and in this case also by including some kind of heading, similar to a sectioning head. The end may also be distinguished by a rule or other symbol, maybe within the last paragraph, and by extra vertical space.

Another property that distinguishes such lists is that they are often numbered, using either an independent system or in conjunction with the sectional numbering.

Perhaps one of the more fruitful sources of such “headed lists” is found in the so-called “theorem-like” environments. These had their origins in mathematical papers and books but are equally applicable to a wide range of expository material, as examples and exercises may take this form whether or not they contain mathematical material.

Because their historical origins lie in the mathematical world, we choose to describe the amsthm package [7] by Michael Downes from the American Mathematical Society (AMS) as a representative of this kind of extension.1 This package provides an enhanced version of standard LaTeX’s ewtheorem declaration for specifying theorem-like environments (headed lists).

1 When the amsthm package is used with a non-AMS document class and with the amsmath package, amsthm must be loaded after amsmath. The AMS document classes incorporate both packages.

As in standard LaTeX, environments declared in this way take an optional argument in which extra text, known as “notes”, can be added to the head of the environment. See the example below for an illustration.

Image

The ewtheorem declaration has two mandatory arguments. The first is the environment name that the author would like to use for this element. The second is the heading text.

If ewtheorem* is used instead of ewtheorem, no automatic numbers will be generated for the environments. This form of the command can be useful if you have only one lemma or exercise and do not want it to be numbered; it is also used to produce a special named variant of one of the common theorem types.

3-3-19
Image

In addition to the two mandatory arguments, ewtheorem has two mutually exclusive optional arguments. They affect the sequencing and hierarchy of the numbering.

Image

By default, each kind of theorem-like environment is numbered independently. Thus, if you have lemmas, theorems, and some examples interspersed, they will be numbered something like this: Example 1, Lemma 1, Lemma 2, Theorem 1, Example 2, Lemma 3, Theorem 2. If, for example, you want the lemmas and theorems to share the same numbering sequence—Example 1, Lemma 1, Lemma 2, Theorem 3, Example 2, Lemma 4, Theorem 5—then you should indicate the desired relationship as follows:

Image

The optional use-counter argument (value thm) in the second statement means that the lem environment should share the thm numbering sequence instead of having its own independent sequence.

To have a theorem environment numbered subordinately within a sectional unit—for example, to get exercises numbered Exercise 2.1, Exercise 2.2, and so on, in Section 2—put the name of the parent counter in square brackets in the final position:

Image

With the optional argument [section], the exa counter will be reset to 0 whenever the parent counter section is incremented.

Defining the style of headed lists

The specification part of the amsthm package supports the notion of a current theorem style, which determines the formatting that will be set up by a collection of ewtheorem commands.1

1 This was first introduced in the now-superseded theorem package by Frank Mittelbach.

Image

The three theorem styles provided by the package are plain, definition, and remark; they specify different typographical treatments that give the environments a visual emphasis corresponding to their relative importance. The details of this typographical treatment may vary depending on the document class, but typically the plain style produces italic body text and the other two styles produce Roman body text.

To create new theorem-like environments in these styles, divide your ewtheorem declarations into groups and preface each group with the appropriate heoremstyle. If no heoremstyle command is given, the style used will be plain. Some examples follow:

3-3-20
Image

Note that the fairly obvious choice of “def” for the name of a “Definition” environment does not work, because it conflicts with the existing low-level TeX command def.

Number swapping

A fairly common style variation for theorem heads is to have the theorem number on the left, at the beginning of the heading, instead of on the right. As this variation is usually applied across the board regardless of individual heoremstyle changes, swapping numbers is done by placing a swapnumbers declaration at the beginning of the list of ewtheorem statements that should be affected.

Advanced customization

More extensive customization capabilities are provided by the package through the ewtheoremstyle declaration and through a mechanism for using package options to load custom theorem style definitions.

Image

To set up a new style of “theorem-like” headed list, use this declaration with the nine mandatory arguments described below. For many of these arguments, if they are left empty, a default is used as listed here.

name The name used to refer to the new style.

space-above The vertical space above the headed list, a rubber length (default opsep).

space-below The vertical space below the headed list, a rubber length (default opsep).

body-style A declaration of the font and other aspects of the style to use for the text in the body of the list (default ormalfont).

indent The extra indentation of the first line of the list, a non-rubber length (default is no extra indent).

head-style A declaration of the font and other aspects of the style to use for the text in the head of the list (default ormalfont).

head-after-punct The text (typically punctuation) to be inserted after the head text, including any note text.

head-after-space The horizontal space to be inserted after the head text and “punctuation”, a rubber length. It cannot be completely empty. As two very special cases it can contain either a single space character to indicate that just a normal interword space is required or, more surprisingly, just the command ewline to indicate that a new line should be started for the body of the list.

head-full-spec A non-empty value for this argument enables a complete specification of the setting of the head itself to be supplied; an empty value means that the layout of the “plain” theorem style is used. See below for further details.

Any extra set-up code for the whole environment is best put into the body-style argument, although care needs to be taken over how it will interact with what is set up automatically. Anything that applies only to the head can be put in head-style.

In the example below we define a break theorem style, which starts a new line after the heading. The heading text is set in bold sans serif, followed by a colon and outdented into the margin by 12pt. Since the book examples are typeset in a very small measure, we added aggedright1 to the body-style argument.

1 The example does not work if ragged2e is loaded (as of 2005), so RaggedRight cannot be used.

3-3-21
Image

Specifying the heading format

The head-full-spec argument, if non-empty, becomes the definition part of an internal command that is used to typeset the (up to) three bits of information contained in the head of a theorem-like environment: its number (if any), its name, and any extra notes supplied by the author when using the environment. Thus, it should contain references to three arguments that will then be replaced as follows:

#1 The fixed text that is to be used in the head (for example, “Exercises”), It comes from the ewtheorem used to declare an environment.

#2 A representation of the number of the element, if it should be numbered. It is conventionally left empty if the environment should not be numbered.

#3 The text for the optional note, from the environment’s optional argument.

Assuming all three parts are present, the contents of the head-full-spec argument could look as follows:

Image

Although you are free to make such a declaration, it is normally best not to use these arguments directly as this might lead to unwanted extra spaces if, for example, the environment is unnumbered.

To account for this extra complexity, the package offers three additional commands, each of which takes one argument: hmname, hmnumber, and hmnote. These three commands are redefined at each use of the environment so as to process their arguments in the correct way. The default for each of them is simply to “typeset the argument”. Nevertheless, if, for example, the particular occurrence is unnumbered, then hmnumber gets redefined to do no typesetting. Thus, a better definition for the head-full-spec argument would be

Image

which corresponds to the set-up used by the default plain style. Note the spaces within the last two arguments: they provide the interword spaces needed to separate the parts of the typeset head but, because they are inside the arguments, they are present only if that part of the head is typeset.

In the following example we provide a “Theorem” variation in which the whole theorem heading has to be supplied as an optional note, such as for citing theorems from other sources.

3-3-22
Image
Proofs and the QED symbol

Of more specifically mathematical interest, the package defines a proof environment that automatically adds a “QED symbol” at the end. This environment produces the heading “Proof” with appropriate spacing and punctuation.1

1 The proof environment is primarily intended for short proofs, no more than a page or two in length. Longer proofs are usually better done as a separate section or subsection in your document.

An optional argument of the proof environment allows you to substitute a different name for the standard “Proof”. If you want the proof heading to be, for example, “Proof of the Main Theorem”, then put this in your document:

Image

A “QED symbol” (default ) is automatically appended at the end of a proof environment. To substitute a different end-of-proof symbol, use enewcommand to redefine the command qedsymbol. For a long proof done as a subsection or section, you can obtain the symbol and the usual amount of preceding space by using the command qed where you want the symbol to appear.

Automatic placement of the QED symbol can be problematic if the last part of a proof environment is, for example, tabular or a displayed equation or list. In that case put a qedhere command at the somewhat earlier place where the QED symbol should appear; it will then be suppressed from appearing at the logical end of the proof environment. If qedhere produces an error message in an equation, try using mbox{qedhere} instead.

3-3-23
Image

3.3.4. Making your own lists

Most lists in LaTeX, including those we have seen previously, are internally built using the generic list environment. It has the following syntax:

Image

The argument default-label is the text to be used as a label when an item command is found without an optional argument. The second argument, decls, can be used to modify the different geometrical parameters of the list environment, which are shown schematically in Figure 3.3 on the next page.

3-3-24
Image

Figure 3.3. Parameters used by the list environment

The default values of these parameters typically depend on the type size and the level of the list. Those being vertically oriented are rubber lengths, meaning that they can stretch or shrink. They are set by the list environment as follows: upon entering the environment the internal command @list level is executed, where level is the list nesting level represented as a Roman numeral (e.g., @listi for the first level, @listii for the second, @listiii for the third, and so on). Each of these commands, defined by the document class, holds appropriate settings for the given level. Typically, the class contains separate definitions for each major document size available via options. For example, if you select the option 11pt, one of its actions is to change the list defaults. In the standard classes this is done by loading the file size11.clo, which contains the definitions for the 11pt document size.

In addition, most classes contain redefinitions of @listi (i.e., first-level list defaults) within the size-changing commands ormalsize, small, and footnotesize, the assumption being that one might have lists within “small” or “footnote-sized” text. However, since this is a somewhat incomplete set-up, strange effects are possible if you

• Use nested lists in such small sizes (the nested lists get the standard defaults intended for ormalsize),

• Jump from small or footnotesize directly to a large size, such as huge (a first-level list now inherits the defaults from the small size, since in this set-up huge does not reset the list defaults).

With a more complex set-up these defects could be mended. However, since the simpler set-up works well in most practical circumstances, most classes provide only this restricted support.

Global changes are difficult

Because of this size- and nesting-dependent set-up for the list parameters, it is not possible to change any of them globally in the preamble of your document. For global changes you have to provide redefinitions for the various @list.. commands discussed above or select a different document class.

Page breaking around lists

Page breaking around and within a list structure is controlled by three TeX counters: @beginparpenalty (for breaking before the list), @itempenalty (for breaking before an item within the list), and @endparpenalty (for breaking the page after a list). By default, all three are set to a slightly negative value, meaning that it is permissible (and even preferable) to break a page in these places compared to other break points. However, this outcome may not be appropriate. You may prefer to discourage or even prevent page breaks directly before a list. To achieve this, assign a high value to @beginparpenalty (10000 or more prohibits the break in all circumstances), for example:

Image

TeX counters need this unusual assignment form and since all three contain an @ sign in their name, you have to surround them with makeatletter and makeatother if the assignment is done in the preamble.

Many environments are implemented as lists

It is important to realize that such a setting is global to all environments based on the generic list environment (unless it is made in the decls argument) and that several LaTeX environments are defined with the help of this environment (for example, quote, quotation, center, flushleft, and flushright). These environments are “lists” with a single item, and the item[] command is specified in the environment definition. The main reason for them to be internally defined as lists is that they then share the vertical spacing with other display objects and thus help achieve a uniform layout.

As an example, we can consider the quote environment, whose definition gives the same left and right margins. The simple variant Quote, shown below, is identical to quote apart from the double quote symbols added around the text. Note the special precautions, which must be taken to eliminate undesirable white space in front of (ignorespaces) and following (unskip) the text. We also placed the quote characters into boxes of zero width to make the quotes hang into the margin. (This trick is worth remembering: if you have a zero-width box and align the contents with the right edge, they will stick out to the left.)

3-3-25
Image

In the remainder of this section we will construct a number of different “description” lists, thereby explaining the various possibilities offered by the generic list environment. We start by looking at the default definition of the description environment as it can be found in LaTeX’s standard classes such as article or report.1

1 If you look into article.cls or report.cls you will find a slightly optimized coding that uses, for example, low-level assignments instead of setlength. However, conceptually, the definitions are identical.

Image

To understand the reasoning behind this definition recall Figure 3.3 on page 145, which explains the relationship between the various list parameters. The parameter settings start by setting labelwidth to zero, which means that we do not reserve any space for the label. Thus, if the label is being typeset, it will move the text of the first line to the right to get the space it needs. Then the itemindent parameter is set to the negation of leftmargin. As a result, the starting point for the first text line is moved to the enclosing margin but all turnover lines are still indented by leftmargin. The last declaration makes makelabel identical to the command descriptionlabel. The command makelabel is called by the list environment whenever it has to format an item label. It takes one argument (the label) and is supposed to produce a typeset version of that argument. So the final task to finish the definition of the description environment is to provide a suitable definition for descriptionlabel. This indirection is useful because it allows us to change the label formatting without modifying the rest of the environment definition.

How should descriptionlabel be defined? It has to provide the formatting for the label. With the standard description environment this label is supposed to be typeset in boldface. But recall that the label is separated from the following text by a space of width labelsep. Due to the parameter settings given above this text starts at the outer margin. Thus, without correction our label would end up starting in the margin (by the width of labelsep). To prevent this outcome the standard definition for the descriptionlabel command has the following curious definition, in that it first moves to the right and then typesets the label:

Image

To remove this dependency, one would need to change the setting of itemindent to already take the labelsep into account, which in itself would not be difficult. You may call this behavior an historical artifact, but many documents rely on this somewhat obscure feature. Thus, it is difficult to change the setting in the LaTeX kernel without breaking those documents.

With the parameter settings of the standard description environment, in case of short labels the text of the first line starts earlier than the text of remaining lines. If we always want a minimal indentation we can try a definition similar to the one in the following example, where we set labelwidth to 40pt and leftmargin to labelwidth plus labelsep. This means that makelabel has to concern itself only with formatting the label. However, given that we now have a positive nominal label width, we need to define what should happen if the label is small. By using hfil we specify where extra white space should be inserted.

3-3-26
Image

This example shows a typical problem with description-like lists when the text in the label (term) is wider than the width of the label. Our definition lets the text of the term continue into the text of the description part. This is often not desired, and to improve the visual appearance of the list we have started one of the description parts on the next line. A new line was forced by putting an empty box on the same line, followed by the ‘\’ command.

In the remaining part of this section various possibilities for controlling the width and mutual positioning of the term and description parts will be investigated. The first method changes the width of the label. The environment is declared with an argument specifying the desired width of the label field (normally chosen to be the widest term entry). Note the redefinition of the makelabel command where you specify how the label will be typeset. As this redefinition is placed inside the definition1 of the altDescription environment, the argument placeholder character # must be escaped to ## to signal LaTeX that you are referring to the argument of the makelabel command, and not to the argument of the outer environment. In such a case, labelwidth is set to the width of the environment’s argument after it is processed by makelabel. This way formatting directives for the label that might change its width are taken into account.

1 This is done for illustration purposes. Usually the solution involving an external name is preferable, as with Descriptionlabel in Example 3-3-26 on the preceding page.

3-3-27
Image

A similar environment (but using an optional argument) is shown in Example A-1-9 on page 850. However, having several lists with varying widths for the label field on the same page might look typographically unacceptable. Evaluating the width of the term is another possibility that avoids this problem. If the width is wider than labelwidth, an additional empty box is appended with the effect that the description part starts on a new line. This matches the conventional method for displaying options in UN*X manuals.

To illustrate this method we reuse the Description environment defined in Example 3-3-26 but provide a different definition for the Descriptionlabel command as follows:

3-3-28
Image

The definition of Descriptionlabel sets the length variable Mylen equal to the width of the label. It then compares that length with labelwidth. If the label is not wider than labelwidth, then it is typeset on the same line as the description term. Otherwise, it is typeset in a zero-width box with the material sticking out to the right as far as needed. It is placed into a bottom-aligned parbox followed by a forced line break so that the description term starts one line lower. This somewhat complicated maneuver is necessary because makelabel, and thus Descriptionlabel, are executed in a strictly horizontal context in which vertical spaces or \ commands have no effect.

Yet another possibility is to allow multiple-line labels.

3-3-29
Image

In the previous example, we once again used the Description environment as a basis, with yet another redefinition of the Descriptionlabel command. The idea here is that large labels may be split over several lines. Certain precautions have to be taken to allow hyphenation of the first word in a paragraph, and therefore the hspace{0pt} command is introduced in the definition. The material gets typeset inside a paragraph box of the correct width labelwidth, which is then top and left aligned into a box that is itself placed inside a box with a height of 1 ex and no depth. In this way, LaTeX does not realize that the material extends below the first line.

The final example deals with the definition of enumeration lists. An environment with an automatically incremented counter can be created by including a usecounter command in the declaration of the list environment. This function is demonstrated with the Notes environment, which produces a sequence of notes. In this case, the first parameter of the list environment is used to provide the automatically generated text for the term part.

After declaring the notes counter, the default label of the Notes environment is defined to consist of the word NOTE in small caps, followed by the value of the notes counter, using as its representation an Arabic numeral followed by a dot. Next labelsep is set to a relatively large value and itemindent, leftmargin, and labelwidth are adjusted in a way such that the label nevertheless starts out at the left margin. Finally, the already-mentioned usecounter declaration ensures that the notes counter is incremented for each item command.

3-3-30
Image

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
Image

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
Image

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

3-4-3
Image

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 egin{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
Image

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
Image

This behavior can be changed by loading the package upquote (written by Michael Covington), which uses the glyphs extasciigrave and extquotesingle 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
Image

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
Image

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

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 elsize{-2}.

3-4-9
Image

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
Image

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
Image

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;1 lines 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).

1 There is no value to indicate a line at the right side.

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
Image

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
Image

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
Image

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
Image

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
Image

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
Image

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

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
Image

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
Image

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 ewcommand* and redefined with enewcommand*. Using ewcommand will not work! To cancel such a declaration is even more complicated: you have to let the command to elax, for example,

Image

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

3-4-21
Image

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 egin{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 egin 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
Image

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
Image

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
Image

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.

Image

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

Image

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
Image

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 ableofcontents 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 extnormal, which is needed to cancel the fseries 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
Image

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
Image

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
Image

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
Image

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
Image

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.

Image

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
Image

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 extbf 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
Image

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
Image

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
Image

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
Image

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
Image

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
Image

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
Image

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 helstlisting. 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 ef, provided you have not suppressed the number.

3-4-40
Image

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
Image

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.

3-4-42
Image

3.5. Lines and columns

In the last part of this chapter we present a few packages that help in manipulating the text stream in its entirety. The first package deals with attaching line numbers to paragraphs, supporting automatic references to them. This can be useful in critical editions and other scholarly works.

The second package deals with the problem of presenting two text streams side by side—for example, some original and its translation. We will show how both packages can be combined in standard cases.

The third package deals with layouts having multiple columns. It allows switching between different numbers of columns on the same page and supports balancing textual data. Standard LaTeX already offers the possibility of typesetting text in one- or two-column mode, but one- and two-column output cannot be mixed on the same page.

We conclude by introducing a package that allows you to mark the modifications in your source with vertical bars in the margin.

3.5.1. lineno—Numbering lines of text

In certain applications it is useful or even necessary to number the lines of paragraphs to be able to refer to them. As TeX optimizes the line breaking over the whole paragraph, it is ill equipped to provide such a facility, since technically line breaking happens at a very late stage during the processing, just before the final pages are constructed. At that point macro processing, which could add the right line number or handle automatic references, has already taken place. Hence, the only way to achieve line numbering is by deconstructing the completed page line by line in the “output routine” (i.e., the part of LaTeX, that normally breaks the paragraph galley into pages and adds running headers and footers) and attaching the appropriate line numbers at that stage.

This approach was taken by Stephan Böttcher in his lineno package. Although one would expect such an undertaking to work only in a restricted environment, his package is surprisingly robust and works seamlessly with many other packages—even those that modify the LaTeX output routine, such as ftnright, multicol, and wrapfig. It also supports layouts produced with the twocolumn option of the standard LaTeX classes.

Image

Loading the lineno package has no direct effect: to activate line numbering, a linenumbers command must be specified in the preamble or at some point in the document. The command olinenumbers deactivates line numbering again. Line numbering works on a per-paragraph basis. Thus, when LaTeX sees the end of a paragraph, it checks whether line numbering is currently requested and, if so, attaches numbers to all lines of that paragraph. It is therefore best to put these commands between paragraphs rather than within them.

The linenumbers command can take an optional argument that denotes the number to use for the first line. If used without such an argument, it continues from where it stopped numbering previously. You can also use a star form, which is a shorthand for linenumbers[1].

3-5-1
Image

Numbering boxed paragraphs

Rather than starting or stopping line numbering with the above commands, you can use the environment linenumbers to define the region that should get line numbers. This environment will automatically issue a par command at the end to terminate the current paragraph. If line numbers are needed only for short passages, the environment form (or one of the special environments numquote and numquotation described later) is preferable.

As the production of line numbers involves the output routine, numbering will take place only for paragraphs being built and put on the “main vertical list” but not for those built inside boxes (e.g., not inside a marginpar or within the body of a float). However, the package offers some limited support for numbering lines in such places via the internallinenumbers command. Restrictions are that the baselines within such paragraphs need to be a fixed distance apart (otherwise, the numbers will not get positioned correctly) and that you may have to end such paragraphs with explicit par commands. The internallinenumbers command accepts a star and an optional argument just as linenumbers does. However, the starred form not only ensures that line numbering is (re)started with 1, but also that the line numbers do not affect line numbering in the main vertical list; compare the results in the two marginpars below.

3-5-2
Image

Handling display math

The line numbers in the second marginpar continue the numbering on the main vertical list (the last line of the preceding paragraph was 5) and the third paragraph then continues with line number 9. Such marginpar commands are processed before the paragraph containing them is broken into lines, which explains the ordering of the numbers.

As lineno needs par to attach line numbers when the output routine is invoked, a TeXnical problem arises when certain display math constructs are used: the partial paragraph above such a display is broken into lines by TeX without issuing a par. As a consequence, without further help such a partial paragraph will not get any line numbers attached. The package’s solution, as illustrated in the next example, is to offer the environment linenomath, which, if it surrounds such a display, will take care of the line numbering problem. It also has a starred form that also numbers the display lines.

3-5-3
Image

Cross-references to line numbers

If there are many such displays the need for surrounding each of them with a linenomath environment is cumbersome. For this reason the package offers the option displaymath, which redefines the basic LaTeX math display environments so that they internally use linenomath environments. The option mathlines will make linenomath behave like its starred form so that the displayed mathematical formulas get line numbers as well.

3-5-4
Image

To reference line numbers put a linelabel into the line and then refer to it via ef or pageref, just as with other references defined using label. The exception is that linelabel can only be used on the main vertical list and should only be used within paragraphs that actually carry numbers. If it is used elsewhere, you get either a bogus reference (if the current line does not have a line number) or an error message (in places where linelabel is not allowed).

3-5-5
Image

Labeling only some lines

It is also possible to refer to a line that carries no linelabel, by using the lineref command with an optional argument specifying the offset. This ability can be useful if you need to refer to a line that cannot be easily labeled, such as a math display, or if you wish to refer to a sequence of lines, as in the previous example.

There are several ways to customize the visual appearance of line numbers. Specifying the option modulo means that line numbers will only appear on some lines (default is every fifth). This effect can also be achieved by using the command modulolinenumbers. Calling this command with an optional argument attaches numbers to lines that are multiples of the specified number (in particular, a value of 1 corresponds to normal numbering). Neither command nor option initiates line numbering mode, for that a linenumbers command is still necessary.

3-5-6
Image

The font for line numbers is controlled by the hook linenumberfont. Its default definition is to use tiny sans serif digits. The numbers are put flush right in a box of width linenumberwidth. This box is separated from the line by the value stored in linenumbersep. To set the number flush left you have to dig deeper, but even for this case you will find hooks like makeLineNumberRight in the package. Although changing the settings in the middle of a document is usually not a good idea, it was done in the next example for demonstration purposes.

3-5-7
Image

For special applications the package offers two environments that provide line numbers automatically: numquote and numquotation. They are like their LaTeX cousins quote and quotation, except that their lines are numbered. They accept an optional argument denoting the line number with which to start (if the argument is omitted, they restart with 1) and they have starred forms that will suppress reseting the line numbers.

The main difference from their LaTeX counterparts (when used together with the linenumbers command) is the positioning of the numbers, which are indented inward. Thus, their intended use is for cases when only the quoted text should receive line numbers that can be referenced separately.

3-5-8
Image

Providing your own extensions

Using the machinery provided by the package material, it is fairly easy to develop your own environments that attach special items to each line. The main macro to customize is makeLineNumber, which gets executed inside a box of zero width at the left edge of each line (when line numbering mode is turned on). The net effect of your code should take up no space, so it is best to operate with llap or lap. Apart from that you can use basically anything. You should only remember that the material is processed and attached after the paragraph has been broken into lines and normal macro-processing has finished, so, you should not expect it to interact with data in mid-paragraph. You can produce the current line number with the LineNumber command, which will supply the number or nothing, depending on whether line numbering mode is on.

The following example shows the definition and use of two new environments that (albeit somewhat crudely, as they do not care about setting fonts and the like) demonstrate some of the possibilities. Note that even though the second environment does not print any line numbers, the lines are internally counted, so that line numbering resumes afterwards with the correct value.

3-5-9
Image

The appearance and behavior of the line numbers can be further controlled by a set of options or, alternatively, by a set of commands equivalent to the options (see the package documentation for details on the command forms). With the options left (default) and right, you specify in which margin the line numbers should appear. Using the option switch or switch*, you get them in the outer and inner margins, respectively.

At least two LaTeX runs of the document are required before the line numbers will appear in the appropriate place. Unfortunately, there is no warning about the need to rerun the document, so you have to watch out for this issue yourself.

verb is allowed

You can also request that numbers restart on each page by specifying the option pagewise. This option needs to come last.

3.5.2. parallel—Two text streams aligned

Sometimes it is necessary to typeset something in parallel columns, such as when presenting some text and its translation. Parallel in this context means that at certain synchronization points the two text streams are vertically (re)aligned. This type of layout is normally not supported by LaTeX (which by default only works with a single text stream), but it can be achieved by using Matthias Eckermann’s parallel package.

This package provides the Parallel environment, which surrounds the material to be typeset in parallel. It takes two mandatory arguments: the widths of the left and right columns. Their sum should be less than extwidth; otherwise, the text in the two columns will touch or even overlap. To ease usage, one or both arguments can be left empty, in which case the appropriate width for the column(s) will be calculated automatically, using the current value of ParallelUserMidSkip as the column separation. To mark up the left and the right text streams, you use ParallelLText and ParallelRText, respectively. Although both commands expect the text as an argument, it is nevertheless possible to use verb or a verbatim environment inside, as the following example shows.

3-5-10
Image

To align certain lines of text you split the two text streams at appropriate points by using pairs of ParallelLText and ParallelRText commands and separating each pair with ParallelPar. If you forget one of the ParallelPar commands, some of your text will get lost without warning. Moreover, as its name suggests, the ParallelPar command introduces a paragraph break, so that alignment is possible only at paragraph boundaries. Additional paragraph breaks inside the argument of a Parallel..Text command are also possible but in that case no alignment is attempted.

In the next example, displaying a few “direct” translations of computer jargon into German (taken from [54] with kind permission by Eichborn Verlag), we define a shorthand command LR to make it easier to input the text. If such a shorthand is used, verb can no longer be used in the argument. Thus, if you need verb, use the package commands directly. We also use the lineno package since line numbers can be useful when talking about a text and its translation.

3-5-11
Image

As you can see, it is possible to adjust paragraph parameters within the scope of the Parallel environment. The negative parindent cancels the positive leftskip so that each paragraph starts flush left but following lines are indented by leftskip (and both must be changed after calling aggedright, as the latter also sets these registers).

The Parallel environment works by aligning line by line, which has a surprising consequence when one block contains unusually large objects, such as a display. Thus, the method is suitable only for normal text lines.

3-5-12
Image

Footnotes in parallel text

Footnotes within the parallel text are not placed at the bottom of the current page, but rather are typeset directly after the end of the current Parallel environment and separated from it by the result of executing ParallelAtEnd, which is a command defined to do nothing. You can, however, redefine it to place something between footnotes and preceding text. If the redefinition should apply only to a single Parallel environment, place it within the scope of the environment.

The presentation of the footnotes is controlled by four package options: OldStyleNums sets footnote numbers using old-style numerals, RaiseNums generates raised footnote numbers, and ItalicNums produces italic numbers. If none of these options is given, then Arabic numerals at the baseline position are used. The options affect only the numbers in front of the footnote text; the markers within the parallel text are always raised Arabic numerals. The fourth option, SeparatedFootnotes, can be combined with one of the three other options and indicates that footnotes in each column should be independently numbered. The numbers from the right column are then postfixed with ParallelDot, which by default produces a centered dot. In the next example its definition is slightly modified so that the dot itself does not take up any space.

3-5-13
Image

The Parallel environment can sport an optional argument before the mandatory ones, whose value can be c (make two columns—the default), v (separate columns with a vertical rule as shown in the previous example), or p (put left text on left-hand pages and right text on right-hand pages). If the “page” variant is chosen it is possible that you get empty pages. For example, if you are on a verso page the environment has to skip to the next recto page in order to display the texts on facing pages.

3.5.3. multicol—A flexible way to handle multiple columns

With standard LaTeX it is possible to produce documents with one or two columns (using the class option twocolumn). However, it is impossible to produce only parts of a page in two-column format as the commands wocolumn and onecolumn always start a fresh page. Additionally, the columns are never balanced, which sometimes results in a slightly weird distribution of the material.

The multicol package1 by Frank Mittelbach solves these problems by defining an environment, multicols, with the following properties:

1 Although the multicol package is distributed under LPPL (LaTeX Project Public License) [111], for historical reasons its copyright contains an additional “moral obligation” clause that asks commercial users to consider paying a license fee to the author or the LaTeX3 fund for their use of the package. For details see the head of the package file itself.

• Support is provided for 2–10 columns, which can run for several pages.

• When the environment ends, the columns on the last page are balanced so that they are all of nearly equal length.

• The environment can be used inside other environments, such as figure or minipage, where it will produce a box containing the text distributed into the requested number of columns. Thus, you no longer need to hand-format your layout in such cases.

• Between individual columns, vertical rules of user-defined widths can be inserted.

• The formatting can be customized globally or for individual environments.

Image

Normally, you can start the environment simply by specifying the number of desired columns. By default paragraphs will be justified, but with narrow measures—as in the examples—they would be better set unjustified as we show later on.

3-5-14
Image

You may be interested in prefixing the multicolumn text with a bit of single-column material. This can be achieved by using the optional preface argument. LaTeX will then try to keep the text from this argument and the start of the multi-column text on the same page.

3-5-15
Image

The multicols environment starts a new page if there is not enough free space left on the current page. The amount of free space is controlled by a global parameter. However, when using the optional argument the default setting for this parameter may be too small. In this case you can either change the global default (see below) or adjust the value for the current environment by using a second optional skip argument as follows:

Image

This would start a new page if less than 7cm free vertical space was available.

Preventing balancing

The multicols environment balances the columns on the last page (it was originally developed for exactly this purpose). If this effect is not desired you can use the multicols* variant instead. Of course, this environment works only in the main vertical galley, since inside a box one has to balance the columns to determine a column height.

The multicols environment recognizes several formatting parameters. Their meanings are described in the following sections. The default values can be found in Table 3.8 (dimensions) and Table 3.9 (counters). If not stated otherwise, all changes to the parameters have to be placed before the start of the environment to which they should apply.

Image

Table 3.8. Length parameters used by multicols

Image

Table 3.9. Counters used by multicols

The required free space

The multicols environment first checks whether the amount of free space left on the page is at least equal to premulticols or to the value of the second optional argument, when specified. If the requested space is not available, a ewpage is issued. A new page is also started at the end of the environment if the remaining space is less than postmulticols. Before and after the environment, a vertical space of length multicolsep is placed.

Column width and separation

Adding vertical lines

The column width inside the multicols environment will automatically be calculated based on the number of requested columns and the current value of linewidth. It will then be stored in columnwidth. Between columns a space of columnsep is left.

Between any two columns, a rule of width columnseprule is placed. If this parameter is set to 0pt (the default), the rule is suppressed. If you choose a rule width larger than the column separation, the rule will overprint the column text.

3-5-16
Image
Column formatting

By default (the flushcolumns setting), the multicols environment tries to typeset all columns with the same length by stretching the available vertical space inside the columns. If you specify aggedcolumns the surplus space will instead be placed at the bottom of each column.

Paragraphs are formatted using the default parameter settings (as described in Sections 3.1.11 and 3.1.12) with the exception of pretolerance and olerance, for which the current values of multicolpretolerance and multicoltolerance are used, respectively. The defaults are -1 and 9999, so that the paragraph-breaking trial without hyphenation is skipped and relatively bad paragraphs are allowed (accounting for the fact that the columns are typically very narrow). If the columns are wide enough, you might wish to change these defaults to something more restrictive, such as

Image

Note the somewhat uncommon assignment form: multicoltolerance is an internal TeX counter and is controlled in exactly the same way as olerance.

Balancing control1
Image

1 Very bad for reading but too good to fix: this problem of a break-stack with “the” four times in a row will not be detected by TeX’s paragraph algorithm—only a complete paragraph rewrite would resolve it.

At the end of the multicols environment, remaining text will be balanced to
produce columns of roughly equal length. If you wish to place more text in the
left columns you can advance the counter unbalance. This counter determines
the number of additional lines in the columns in comparison to the number that
the balancing routine has calculated. It will automatically be restored to zero after
the environment has finished. To demonstrate the effect, the next example uses
the text from Example 3-5-16 on the facing page but requests one extra line.

3-5-17
Image

Column balancing is further controlled by the two counters columnbadness and finalcolumnbadness. Whenever LaTeX is constructing boxes (such as a column) it will compute a badness value expressing the quality of the box—that is, the amount of excess white space. A zero value is optimal, and a value of 10000 is infinitely bad in LaTeX’s eyes.2 While balancing, the algorithm compares the badness of possible solutions and, if any column except the last one has a badness higher than columnbadness, the solution is ignored. When the algorithm finally finds a solution, it looks at the badness in the last column. If it is larger than finalcolumnbadness, it will typeset this column with the excess space placed at the bottom, allowing it to come out short.

2 For an overfull box the badness value is set to 100000 by TeX, to mark this special case.

Collecting material

To be able to properly balance columns the multicols environment needs to collect enough material to fill the remaining part of the page. Only then does it cut the collected material into individual columns. It tries to do so by assuming that not more than the equivalent of one line of text per column vanishes into the margin due to breaking at vertical spaces. In some situations this assumption is incorrect and it becomes necessary to collect more or less material. In such a case you can adjust the default setting for the counter collectmore. Changing this counter by one means collecting material for one more (or less) aselineskip.

There are, in fact, reasons why you may want to reduce that collection. If your document contains many footnotes and a lot of surplus material is collected, there is a higher chance that the unused part will contain footnotes, which could come out on the wrong page. The smallest sensible value for the counter is the negative number of columns used. With this value multicols will collect exactly the right amount of material to fill all columns as long as no space gets lost at a column break. However, if spaces are discarded in this set up, they will show up as empty space in the last column.

Tracing the algorithm

You can trace the behavior of the multicol package by loading it with one of the following options. The default, errorshow, displays only real errors. With infoshow, multicol becomes more talkative and you will get basic processing information such as

Image

which is the calculated column width.

With balancingshow, you get additional information on the various trials made by multicols when determining the optimal column height for balancing, including the resulting badness of the columns, reasons why a trial was rejected, and so on.

Using markshow will additionally show which marks for the running header or footer are generated on each page. Instead of using the options you can (temporarily) set the counter tracingmulticols to a positive value (higher values give more tracing information).

Manually breaking columns

Sometimes it is necessary to overrule the column-breaking algorithm. We have already seen how the unbalance counter is used to influence the balancing phase. But on some occasions one wishes to explicitly end a column after a certain line. In standard LaTeX this can be achieved with a pagebreak command, but this approach does not work within a multicols environment because it will end the collection phase of multicols and thus end all columns on the page. As an alternative the command columnbreak is provided. If used within a paragraph it marks the end of the current line as the desired breakpoint. If used between paragraphs it forces the next paragraph into the next column (or page) as shown in the following example. If flushcolumns is in force, the material in the column is vertically stretched (if possible) to fill the full column height. If this effect is not desired one can prepend a vfill command to fill the bottom of the column with white space.

3-5-18
Image
Floats and footnotes in multicol

Floats (e.g., figures and tables) are only partially supported within multicols. You can use starred forms of the float environments, thereby requesting floats that span all columns. Column floats and marginpars, however, are not supported.

Supported printer drivers

Footnotes are typeset (full width) on the bottom of the page, and not under individual columns (a concession to the fact that varying column widths are supported on a single page).

Under certain circumstances a footnote reference and its text may fall on subsequent pages. If this is a possibility, multicols produces a warning. In that case, you should check the page in question. If the footnote reference and footnote text really are on different pages, you will have to resolve the problem locally by issuing a pagebreak command in a strategic place. The reason for this behavior is that multicols has to look ahead to assemble material and may not be able to use all material gathered later on. The amount of looking ahead is controlled by the collectmore counter.

3.5.4. changebar—Adding revision bars to documents

When a document is being developed it is sometimes necessary to (visually) indicate the changes in the text. A customary way of doing that is by adding bars in the margin, known as “changebars”. Support for this functionality is offered by the changebar package, originally developed by Michael Fine and Neil Winton, and now supported by Johannes Braams. This package works with most PostScript drivers, but in particular dvips, which is the default driver when the package is loaded. Other drivers can be selected by using the package option mechanism. Supported options are dvitoln03, dvitops, dvips, emtex, textures, and vtex.

Image

When you add text to your document and want to signal this fact, you should surround it with the changebar environment. Doing so ensures that LaTeX will warn you when you forget to mark the end of a change. This environment can be (properly) nested within other environments. However, if your changes start within one LaTeX environment and end inside another, the environment form cannot be used as this would result in improperly nested environments. Therefore, the package also provides the commands cbstart and cbend. These should be used with care, because there is no check that they are properly balanced. Spaces after them might get ignored.

Changing the width

If you want to give a single bar a different width you may use the optional argument and specify the width as a normal LaTeX length.

Image

Text that has been removed can be indicated by inserting the cbdelete command. Again, the width of the bar can be changed.

3-5-19
Image
Image

When your document has reached the final stage you can remove the effect of using the changebar package by inserting the command ochangebars in the preamble of the document.

Customizations

If you want to change the width of all changebars you can do so by changing the value of changebarwidth via the command setlength. The same can be done for the deletion bars by changing the value of deletebarwidth.

Positioning changebars

By default, the changebars will show up in the “inner margin”, but this can be changed by using one of the following options: outerbars, innerbars, leftbars, or rightbars.

The distance between the text and the bars is controlled by changebarsep. It can can be changed only in the preamble of the document.

Coloring changebars

The color of the changebars can be changed by the user as well. By default, the option grey is selected so the changebars are grey (grey level 65%). The drivers dvitoln03 and emtex are exceptions that will produce black changebars.

The “blackness” of the bars can be controlled with the help of the LaTeX counter changebargrey. A command like setcounter{changebargrey}{85} changes that value. The value of the counter is a percentage, where 0 yields black bars, and 100 yields white bars.

Tracing the algorithm

The option color makes it possible to use colored changebars. It internally loads dvipsnames, so you can use a name when selecting a color.

Image

The color to use when printing changebars is selected with the command cbcolor, which accepts the same arguments as the color command from the color package [57, pp.317–326].

3-5-20
Image

You can trace the behavior of the changebar package by loading it with one of the following options. The default, traceoff, displays the normal information LaTeX always shows. The option traceon informs you about the beginning and end points of changebars being defined. The additional option tracestacks adds information about the usage of the internal stacks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.192.212