Chapter 2. The Structure of a LaTeX Document

One of the ideas behind LaTeX is the separation between layout and structure (as far as possible), which allows the user to concentrate on content rather than having to worry about layout issues [104]. This chapter explains how this general principle is implemented in LaTeX.

The first section of this chapter shows how document class files, packages, options, and preamble commands can affect the structure and layout of a document. The logical subdivisions of a document are discussed in general, before explaining in more detail how sectioning commands and their arguments define a hierarchical structure, how they generate numbers for titles, and how they produce running heads and feet. Different ways of typesetting section titles are presented with the help of examples. It is also shown how the information that is written to the table of contents can be controlled and how the look of this table, as well as that of the lists of tables and figures, can be customized. The final section introduces LaTeX commands for managing cross-references and their scoping rules.

2.1. The structure of a source file

You can use LaTeX for several purposes, such as writing an article or a letter, or producing overhead slides. Clearly, documents for different purposes may need different logical structures, i.e., different commands and environments. We say that a document belongs to a class of documents having the same general structure (but not necessarily the same typographical appearance). You specify the class to which your document belongs by starting your LaTeX file with a documentclass command, where the mandatory parameter specifies the name of the document class. The document class defines the available logical commands and environments (for example, chapter in the report class) as well as a default formatting for those elements. An optional argument allows you to modify the formatting of those elements by supplying a list of class options. For example, 11pt is an option recognized by most document classes that instructs LaTeX to choose eleven point as the basic document type size.

Many LaTeX commands described in this book are not specific to a single class but can be used with several classes. A collection of such commands is called a package and you inform LaTeX about your use of certain packages in the document by placing one or more usepackage commands after documentclass.

Just like the documentclass declaration, usepackage has a mandatory argument consisting of the name of the package and an optional argument that can contain a list of package options that modify the behavior of the package.

The document classes and the packages reside in external files with the extensions .cls and .sty, respectively. Code for options is sometimes stored in external files (in the case of class files with the extension .clo) but is normally directly specified in the class or package file (see Appendix A for information on declaring options in classes and packages). However, in case of options, the file name can differ from the option name. For example, the option 11pt is related to size11.clo when used in the article class and to bk11.clo inside the book class.

The document preamble

Commands placed between documentclass and egin{document} are in the so-called document preamble. All style parameters must be defined in this preamble, either in package or class files or directly in the document before the egin{document} command, which sets the values for some of the global parameters. A typical document preamble could look similar to the following:

Image

This document preamble defines that the class of the document is article and that the layout is influenced by the formatting request twocolumn (typeset in two columns) and the option a4paper (print on A4 paper). The first usepackage declaration informs LaTeX that this document contains commands and structures provided by the package multicol. In addition, the babel package with the options german (support for German language) and french (support for French language) is loaded. Finally, the default height of the text body was enlarged by three lines for this document.

Generally, nonstandard LaTeX package files contain modifications, extensions, or improvements1 with respect to standard LaTeX, while commands in the preamble define changes for the current document. Thus, to modify the layout of a document, you have several possibilities:

• Change the standard settings for parameters in a class file by options defined for that class.

• Add one or more packages to your document and make use of them.

• Change the standard settings for parameters in a package file by options defined for that package.

• Write your own local packages containing special parameter settings and load them with usepackage after the package or class they are supposed to modify (as explained in the next section).

• Make final adjustments inside the preamble.

1 Many of these packages have become de facto standards and are described in this book. This does not mean, however, that packages that are not described here are necessarily less important or useful, of inferior quality, or should not be used. We merely concentrated on a few of the more established ones; for others, we chose to explain what functionality is possible in a given area.

If you want to get deeper into LaTeX’s internals, you can, of course, define your own general-purpose packages that can be manipulated with options. You will find additional information on this topic in Appendix A.

2.1.1. Processing of options and packages

Today’s LaTeX makes a clear distinction between declared options (of a class or package) and general-purpose package files. The latter have to be specified using the usepackage command. Think of options as properties of the whole document (when used in documentclass) or as properties of individual packages (if specified in usepackage).

You can specify options in a usepackage command only if these options are declared by the package. Otherwise, you will receive an error message, informing you that your specified option is unknown to the package in question. Options to the documentclass are handled slightly differently. If a specified option is not declared by the class, it will be assumed to be a “global option”.

All options to documentclass (both declared and global ones) are automatically passed as class options to all usepackage declarations. Thus, if a package file loaded with a usepackage declaration recognizes (i.e., declares) some of the class options, it can take appropriate actions. If not, the class options will be ignored while processing that package. Because all options have to be defined inside the class or package file, their actions are under the control of the class or package (an action can be anything from setting internal switches to reading an external file). For this reason their order in the optional argument of documentclass or usepackage is (usually) irrelevant.

If you want to use several packages, all taking the same options (for example, none), it is possible to load them all with a single usepackage command by specifying the package names as a comma-separated list in the mandatory argument. For example,

Image

is equivalent to

Image

Specifying german as a global option to the class can further shorten the usepackage declaration as german will be passed to all loaded packages and thus will be processed by those packages that declare it.

Image

Of course, this assumes that neither multicol nor epic changes its behavior when german is passed as a class option.

Finally, when the egin{document} is reached, all global options are checked to see whether each has been used by at least one package; if not, a warning message is displayed. It is usually a spelling mistake if your option name is never used; another possibility is the removal of a usepackage command loading a package that used this option previously.

If you want to make some modifications to a document class or a package (for example, changing parameter values or redefining some commands), you should put the relevant code into a separate file with the extension .sty. Then load this file with a usepackage command after the package whose behavior you wish to modify (or the document class, if your modifications concern class issues).

Alternatively, you can insert the modifications directly into the preamble of your document. In that case, you may have to bracket them with makeatletter and makeatother if they contain internal LaTeX commands (i.e., those with an @ sign in their names). For more details see the discussion on page 843 concerning internal commands in the preamble.

2.1.2. Splitting the source file into parts

Partial processing

LaTeX source documents can be conveniently split into several parts by using include commands. Moreover, documents can be reformatted piecewise by specifying as arguments of an includeonly command only those files LaTeX has to re-process. For the other files that are specified in include statements, the counter information (page, chapter, table, figure, equation, ...) will be read from the corresponding .aux files as long as they have been generated during a previous run.

In the following example, the user wants to reprocess only files chap1.tex and appen1.tex:

Image

Be aware that LaTeX only issues a warning message like "No file xxx.tex" when it cannot find a file specified in an include statement, not an error message, and continues processing.

If the information in the .aux files is up-to-date, it is possible to process only part of a document and have all counters, cross-references, and pages be corrected in the reformatted part. However, if one of the counters (including the page number for cross-references) changes in the reprocessed part, then the complete document might have to be rerun to get the index, table of contents, and bibliographic references consistently correct.

Note that each document part loaded via include starts on a new page and finishes by calling clearpage; thus, floats contained therein will not move outside the pages produced by this part. So natural candidates for include are whole chapters of a book but not necessarily small fractions of text.

While it is certainly an advantage to split a larger document into smaller parts and to work on more manageable files with a text editor, partial reformatting should be used only with great care and when still in the developing stage for one or more chapters. When a final and completely correct copy is needed, the only safe procedure is to reprocess the complete document. If a document is too large to process in a single run, it can be subdivided into parts that can be run separately. However, in this case, the pieces must be processed in the correct sequence (if necessary several times), to ensure that the cross-references and page numbers are correct.

Interactive inclusion

If you intend to work with include commands, consider using the small package askinclude created by Pablo Straub. It interactively asks you which files to include. You can then specify the files as a comma-separated list (i.e., what you would put into the includeonly argument). If the Enter button is pressed in response, then the files from the previous run are included automatically (except on the first run, where this response means to include all files). If the answer is a *, then all files are included; a - means no files should be included. This way you do not have to modify your master source to process different parts of your document (a very useful feature during the production of this book).

Excluding instead of including

An extension to the include mechanism is provided by the package excludeonly created by Dan Luecking and Donald Arseneau. It offers the command excludeonly, which takes a comma-separated list of include file names and prevents their inclusion. If both includeonly and excludeonly are used, then only the files permitted by both declarations are used. For example,

Image

results in only chap1 and appen1 being included. This behavior actually contradicts the package name, which indicates that “only” the given list is excluded. You can achieve this effect by calling the package with the option only, in which case an includeonly declaration is ignored.

This package redefines the internal @include command, so it will not work with packages or classes that redefine this command as well. Known conflicts are with the document classes paper and thesis by Wenzel Matiaske.

2.1.3. Combining several files

When sending a LaTeX document to another person you may have to send local or uncommon package files (e.g., your private modifications to some packages) along with the source. In such cases it is often helpful if you can put all the information required to process the document into a single file.

For this purpose, LaTeX provides the environment filecontents. This environment takes one argument, the name of a file;1 its body consists of the contents of this file. It is only allowed to appear before a documentclass declaration. The egin and end tags should be placed on lines of their own in the source. In particular, there should be no material following them, or you will get LaTeX errors.

1 If no extension is specified, the actual external file name will be the one LaTeX would read if you used this name as an argument to input, i.e., typically adding the extension .tex.

If LaTeX encounters such an environment, it will try to find the mentioned file name. If it cannot, it will write the body of the environment verbatim into a file in the current directory and inform you about this action. Conversely, if a file with the given name was found by LaTeX, it will inform you that it has ignored this instance of the filecontents environment because the file is already present on the file system.

The generated file will get a few comment lines (using % as a comment character) added to the top to announce that this file was written by a filecontents environment:

Image

If this is not appropriate—for example, if the file is not a LaTeX file—use the filecontents* environment instead, which does not produce such extra lines.

To get a list of (nearly) all files used in your document (so that you know what you might have to pack together), specify the command listfiles in the preamble.

2.1.4. optional—Providing variants in the document source

Sometimes it is useful to keep several versions of a document together in a single source, especially if most of the text is shared between versions. This functionality is provided by the optional package created by Donald Arseneau.

The variant text parts are specially marked in the source using the command opt, and during formatting some of them are selected. The command takes two arguments: a label (or a comma-separated list of labels) that describes to which variant the optional text belongs, and the text to be conditionally printed. Because the text is given in an argument, it cannot contain verb commands and must have balanced braces. This approach works well enough for shorter texts. With longer parts to be optionally printed, however, it is usually best to store them in an external file and conditionally load this file using the opt command, as was done in the example below.

There are a number of ways to select which variants are to be printed. The following example shows the non-interactive way, where the variants to be printed are specified by selecting them as options on the usepackage declaration.

2-1-1
Image

Alternatively, you can prompt the user each time for a list of options by including the declaration AskOptions in the preamble, though that can become tedious if used too often. To help the person select the right options interactively you can define the command ExplainOptions—if defined, its replacement text will be displayed on the terminal prior to asking for a list of options.

If your LaTeX implementation supports passing LaTeX code instead of a file name to the program, there is a third way to select the variants. If you invoke LaTeX with the line

Image

then the variants with the labels doc and code will be used (in addition to those specified on the usepackage, if any). The example command line above would be suitable for a UN*X system; on other platforms, you might need different quotes.

The optional package selects the variants to process during the LaTeX formatting. Depending on the application, it might be better to use a different approach involving a preprocessor that extracts individual variants from the master source. For example, the docstrip program can be successfully used for this purpose; in contrast to other preprocessors, it has the advantage that it will be usable at every site that has an installed LaTeX system (see Section 14.2 for details).

2.2. Sectioning commands

The standard LaTeX document classes (i.e., article, report, and book) contain commands and environments to define the different hierarchical structural units of a document (e.g., chapters, sections, appendices). Each such command defines a nesting level inside a hierarchy and each structural unit belongs to some level.

A typical document (such as an article) consists of a title, some sections with probably a multilevel nested substructure, and a list of references. To describe such a structure the title-generating command maketitle, sectioning commands such as section and subsection, and the thebibliography environment are used. The commands should be correctly nested. For example, a subsection command should be issued only after a previous section.

Longer works (such as reports, manuals, and books) start with more complex title information, are subdivided into chapters (and parts), provide cross-reference information (table of contents, list of figures, list of tables, and indexes), and probably have appendices. In such a document you can easily distinguish the front matter, body, and back matter. In LaTeX’s book class these three parts can be explicitly marked up using the commands frontmatter, mainmatter, and ackmatter. In other classes you often find only the command appendix, which is used to separate the body matter from the back matter.

In the front matter the so-called starred form of the section or chapter sectioning command is normally used. This form suppresses the numbering of a heading. Sectional units with fixed names, such as “Introduction”, “Index”, and “Preface”, are usually not numbered. In the standard classes, the commands ableofcontents, listoftables, and listoffigures, and the theindex and thebibliography environments internally invoke the command (section or chapter) using their starred form.

Standard LaTeX provides the set of sectioning commands shown in Table 2.1. The chapter command defines level zero of the hierarchical structure of a document, section defines level one, and so on, whereas the optional part command defines the level minus one (or zero in classes that do not define chapter). Not all of these commands are defined in all document classes. The article class does not have chapter and the letter class does not support sectioning commands at all. It is also possible for a package to define other sectioning commands, allowing either additional levels or variants for already supported levels.

Image

Table 2.1. LaTeX’s standard sectioning commands

Generally, the sectioning commands automatically perform one or more of the following typesetting actions:

• Produce the heading number reflecting the hierarchical level.

• Store the heading as an entry for a table of contents (into the .toc file).

• Save the contents of the heading to be (perhaps) used in a running head and/or foot.

• Format the heading.

All sectioning commands have a common syntax as exemplified here by the section command:

Image

The starred form (e.g., section*{...}) suppresses the numbering for a title and does not produce an entry in the table of contents or the running head. In the second form the optional argument toc-entry is used when the text string for the table of contents and the running head and/or foot is different from the printed title. If this variant is used, numbering depends on the current value of the counter secnumdepth (discussed in the next section).

Problems with explicit formatting

If you try to advise TeX on how to split the heading over a few lines using the “~” symbol or the \ command, then side effects may result when formatting the table of contents or generating the running head. In this case the simplest solution is to repeat the heading text without the specific markup in the optional parameter of the sectioning command.

The remainder of this section discusses how the appearance of headings can be modified. It explains how to define a command like section that has the above syntax, produces a table of contents entry if desired, but has a thick rule above its heading text or uses a normal-sized italic font rather than a large bold one.

First, some examples show how to change the numbering of headings. Next, examples demonstrate how to enter information about headings into the table of contents. Finally, changes to the general layout of headings are discussed, showing what LaTeX offers to define them.

2.2.1. Numbering headings

To support numbering, LaTeX uses a counter for each sectional unit and composes the heading number from these counters.

Numbering no headings

Perhaps the change desired most often concerning the numbering of titles is to alter the nesting level up to which a number should be produced. This is controlled by a counter named secnumdepth, which holds the highest level with numbered headings. For example, some documents have none of their headings numbered. Instead of always using the starred form of the sectioning commands, it is more convenient to set the counter secnumdepth to -2 in the document preamble. The advantages of this method are that an entry in the table of contents can still be produced, and that arguments from the sectioning commands can produce information in running headings. As discussed above, these features are suppressed in the starred form.

Numbering all headings

To number all headings down to subparagraph or whatever the deepest sectioning level for the given class is called, setting the counter to a high enough value (e.g., a declaration such as setcounter{secnumdepth}{10} should normally be sufficient).

Finally, the addtocounter command provides an easy way of numbering more or fewer heading levels without worrying about the level numbers of the corresponding sectioning commands. For example, if you need one more level with numbers, you can place addtocounter{secnumdepth}{1} in the preamble of your document without having to look up the right value.

Every sectioning command has an associated counter, which by convention has the same name as the sectioning command (e.g., the command subsection has a corresponding counter subsection). This counter holds the current (formatted) number for the given sectioning command. Thus, in the report class, the commands chapter, section, subsection, and so on represent the hierarchical structure of the document and a counter like subsection keeps track of the number of subsections used inside the current section. Normally, when a counter at a given hierarchical level is stepped, then the next lower-level counter (i.e., that with the next higher-level number) is reset. For example, the report class file contains the following declarations:

Image

These commands declare the various counters. The level one (section) counter is reset when the level zero (chapter) counter is stepped. Similarly, the level two (subsection) counter is reset whenever the level one (section) counter is stepped. The same mechanism is used down to the subparagraph command. Note that in the standard classes the part counter is decoupled from the other counters and has no influence on the lower-level sectioning commands. As a consequence, chapters in the book or report class or sections in article will be numbered consecutively even if a part command intervenes. Changing this is simple—you just replace the corresponding declaration of the chapter counter with:

Image

The behavior of an already existing counter can be changed with the command @addtoreset (see Appendix A.1.4), for example,

Image

Recall that the latter instruction, because of the presence of the @ character, can be issued only inside a package file or in the document preamble between makeatletter and makeatother commands, as explained on page 843.

Every counter in LaTeX, including the sectioning counters, has an associated command constructed by prefixing the counter name with he, which generates a typeset representation of the counter in question. In case of the sectioning commands this representation form is used to produce the full number associated with the commands, as in the following definitions:

Image

In this example, hesubsection produces an Arabic number representation of the subsection counter prefixed by the command hesection and a dot. This kind of recursive definition facilitates modifications to the counter representations because changes do not need to be made in more than one place. If, for example, you want to number sections using capital letters, you can redefine the command hesection:

2-2-1
Image

Thus, by changing the counter representation commands, it is possible to change the number displayed by a sectioning command. However, the representation of the number cannot be changed arbitrarily by this method. Suppose you want to produce a subsection heading with the number surrounded by a box. Given the above examples one straightforward approach would be to redefine hesubsection, e.g.,

Image

But this is not correct, as one sees when trying to reference such a section.

2-2-2
Image

In other words, the counter representation commands are also used by LaTeX’s cross-referencing mechanism (the label, ef commands; see Section 2.4). Therefore, we can only make small changes to the counter representation commands so that their use in the ef command still makes sense. To produce the box around the heading number without spoiling the output of a ef, we have to redefine LaTeX’s internal command @seccntformat, which is responsible for typesetting the counter part of a section title. The default definition of @seccntformat typesets the he representation of the section counter (in the example above, it uses the hesection command), followed by a fixed horizontal space of 1 em. Thus, to correct the problem, the previous example should be rewritten as follows:

2-2-3
Image

The framed box around the number in the section heading is now defined only in the @seccntformat command, and hence the reference labels come out correctly.1 Also note that we reduced the space between the box and the text to 0.5 em (instead of the default 1 em). The definition of @seccntformat applies to all headings defined with the @startsection command (which is described in the next section). Therefore, if you wish to use different definitions of @seccntformat for different headings, you must put the appropriate code into every heading definition.

1 The command @seccntformat takes as an argument the section level identifier, which is appended to the he prefix to generate the presentation form needed via the csname, endcsname command constructor. In our example, the @seccntformat command is called with the section argument and thus the replacement text fbox{csname thesectionendcsname}hspace{0.5em} is generated. See the TeXbook [82] for more details about the csname command.

2.2.2. Formatting headings

LaTeX provides a generic command called @startsection that can be used to define a wide variety of heading layouts. To define or change a sectioning command one should find out whether @startsection can do the job. If the desired layout is not achievable that way, then secdef can be used to produce sectioning formats with arbitrary layout.

Headings can be loosely subdivided into two major groups: display and run-in headings. A display heading is separated by a vertical space from the preceding and the following text—most headings in this book are of this type.

A run-in heading is characterized by a vertical separation from the preceding text, but the text following the title continues on the same line as the heading itself, only separated from the latter by a horizontal space.

2-2-4
Image

The generic command @startsection allows both types of headings to be defined. Its syntax and argument description are as follows:

Image

name The name used to refer to the heading counter1 for numbered headings and to define the command that generates a running header or footer (see page 218). For example, name would be the counter name, hename would be the command to display the current heading number, and namemark would be the command for running headers. In most circumstances the name will be identical to the name of the sectioning command being defined, without the preceding backslash—but this is no requirement.

1 This counter must exist; it is not defined automatically.

level A number denoting the depth level of the sectioning command. This level is used to decide whether the sectioning command gets a number (if the level is less than or equal to secnumdepth; see Section 2.2.1 on page 24) or shows up in the table of contents (if the value is less or equal to tocdepth, see Section 2.3.2 on page 49). It should therefore reflect the position in the command hierarchy of sectioning commands, where the outermost sectioning command has level zero.1

1 In the book and report classes, the part command actually has level -1 (see Table 2.1).

indent The indentation of the heading with respect to the left margin. By making the value negative, the heading will start in the outer margin. Making it positive will indent all lines of the heading by this amount.

beforeskip The absolute value of this parameter defines the space to be left in front of the heading. If the parameter is negative, then the indentation of the paragraph following the heading is suppressed. This dimension is a rubber length, that is, it can take a stretch and shrink component. Note that LaTeX starts a new paragraph before the heading, so that additionally the value of parskip is added to the space in front.

afterskip The space to be left following a heading. It is the vertical space after a display heading or the horizontal space after a run-in heading. The sign of afterskip controls whether a display heading (afterskip > 0) or a run-in heading (afterskip ≤ 0) is produced. In the first case a new paragraph is started so that the value of parskip is added to the space after the heading. An unpleasant side effect of this parameter coupling is that it is impossible to define a display heading with an effective “after space” of less than parskip using the @startsection command. When you try to compensate for a positive parskip value by using a negative afterskip, you change the display heading into a run-in heading.

style The style of the heading text. This argument can take any instruction that influences the typesetting of text, such as aggedright, Large, or fseries (see the examples below).

Figures 2.1 and 2.2 show these parameters graphically for the case of display and run-in headings, respectively.

2-2-5
Image

Figure 2.1. The layout for a display heading (produced by layouts)

2-2-6
Image

Figure 2.2. The layout for a run-in heading (produced by layouts)

Next we show how these arguments are used in practice to define new sectioning commands. Suppose that you want to change the subsection command of a class like article to look roughly like this:

2-2-7
Image

In this case the following redefinition for subsection is needed:

Image

The first argument is the string subsection to denote that we use the corresponding counter for heading numbers. In the sectional hierarchy we are at level two. The third argument is 0 mm because the heading should start at the left margin. The absolute value of the fourth argument (beforeskip) specifies that a distance equal to one baseline must be left in front of the heading and, because the parameter is negative, that the indentation of the paragraph following the heading should be suppressed. The absolute value of the fifth parameter (after-skip) specifies that a distance equal to one-half baseline must be left following the heading and, because the parameter is positive, that a display heading has to be produced. Finally, according to the sixth parameter, the heading should be typeset in an italic font using a size equal to the normal document type size.

In fact, the redefinition is a bit too simplistic because, as mentioned earlier, on top of the absolute value of beforeskip and afterskip, LaTeX always adds the current value of parskip. Thus, in layouts where this parameter is nonzero, we need to subtract it to achieve the desired separation.

Another layout, which is sometimes found in fiction books, is given by the following definition:

Image

This defines a run-in heading using small capitals. The space definition for the horizontal afterskip deserves an explanation: it is the value of the stretchable space between words taken from the current font, negated to make a run-in heading. Details about fontdimens can be found in Section 7.10.3 on page 428. The result is shown in the next example.

2-2-8
Image

Of course, for such a layout one should turn off numbering of the headings by setting the counter secnumdepth to -2.

Simple heading style changes

Which commands can be used for setting the styles of the heading texts in the style argument of the @startsection command? Apart from the font-changing directives (see Chapter 7), few instructions can be used here. A centering command produces a centered display heading and a aggedright declaration makes the text left justified. The use of aggedleft is possible, but may give somewhat strange results. You can also use hrule, medskip, ewpage, or similar commands that introduce local changes. The next example shows some possible variations.

2-2-9
Image

Hyphenation and line breaks in headings

In the standard LaTeX document classes, words in long headings are justified and, if necessary, hyphenated as can be seen in the previous example. If this is not wanted, then justification can be turned off by using aggedright in the style part of the @startsection command. If line breaks are manually adjusted using \, then one has to repeat the heading title, without the extra formatting instruction, in the optional argument. Otherwise, the line breaks will also show up in the table of contents.

2-2-10
Image

Indentation after a heading

Finally, a few words about the suppression of the indentation for the first paragraph after a display heading. Standard LaTeX document classes, following (American) English typographic tradition, suppress the indentation in this case. All first paragraphs after a display heading can be indented by specifying the package indentfirst (David Carlisle).

Complex heading layout definitions

In the standard LaTeX classes the highest-level sectioning commands part and chapter produce their titles without using @startsection since their layout cannot be produced with that command. Similarly, you may also want to construct sectioning commands without limitations. In this case you must follow a few conventions to allow LaTeX to take all the necessary typesetting actions when executing them.

The command secdef can help you when defining such commands by providing an easy interface to the three possible forms of section headings, as shown in the case of the part command. With the definition

Image

the following actions take place:

Image

The commands you have to provide are a (re)definition1 of part and a definition of the commands labeled cmda or cmdb, respectively. Note that cmda has an optional argument containing the text to be entered in the table of contents .toc file, while the second (mandatory) argument, as well as the single argument to cmdb, specifies the heading text to be typeset. Thus, the definitions must have the following structure:

Image

1 Redefinition in case you change an existing heading command such as part in the preamble of your document.

An explicit example is a simplified variant of appendix. It redefines the section command to produce headings for appendices (by invoking either the command Appendix or sAppendix), changing the presentation of the section counter and resetting it to zero. The modified section command also starts a new page, which is typeset with a special page style (see Chapter 4) and with top floats suppressed. The indentation of the first paragraph in a section is also suppressed by using the low-level kernel command @afterheading and setting the Boolean switch @afterindent to false. For details on the use of these commands see the chapter implementation in the standard classes (file classes.dtx).

Image

In the definition below you can see how Appendix advances the section counter using the efstepcounter command (the latter also resets all subsidiary counters and defines the “current reference string”; see Section 2.4). It writes a line into the .toc file with the addcontentsline command, performs the formatting of the heading title, and saves the title for running heads and/or feet by calling sectionmark. The @afterheading command handles the indentation of the paragraph following the heading.

Image

The sAppendix command (starred form) performs only the formatting.

Image

Applying these definitions will produce the following output:

2-2-11
Image

Do not forget that the example shown above represents only a simplified version of a redefined section command. Among other things, we did not take into account the secnumdepth counter, which contains the numbering threshold. You might also have to foresee code dealing with various types of document formats, such as one- and two-column output, or one- and two-sided printing.

2.2.3. Changing fixed heading texts

Some of the standard heading commands produce predefined texts. For example, chapter produces the string “Chapter” in front of the user-supplied text. Similarly, some environments generate headings with predefined texts. For example, by default the abstract environment displays the word “Abstract” above the text of the abstract supplied by the user. LaTeX defines these strings as command sequences (see Table 2.2) so that you can easily customize them to obtain your favorite names. This is shown in the example below, where the default name “Abstract”, as defined in the article class, is replaced by the word “Summary”.

Image

Table 2.2. Language-dependent strings for headings

2-2-12
Image

The standard LaTeX class files define a few more strings. See Section 9.1.3, and especially Table 9.2 on page 547, for a full list and a discussion of the babel system, which provides translations of these strings in more than twenty languages.

2.2.4. fncychap—Predefined chapter heading layouts

For those who wish to have fancy chapter headings without much work there exists the package fncychap (Ulf Lindgren). It provides six distinctive layout styles for the chapter command that can be activated by loading the package with one of the following options: Sonny, Lenny, Glenn, Conny, Rejne, or Bjarne. Because the package is intended for modifying the chapter command, it works only with document classes that provide this command (e.g., report and book, but not article and its derivatives). As an example we show the results of using the option Lenny.

2-2-13
Image

The package also offers several commands to modify the layouts in various ways. It comes with a short manual that explains how to provide your own layouts.

2.2.5. quotchap—Mottos on chapters

Another way to enhance chapter headings is provided by the quotchap package created by Karsten Tinnefeld. It allows the user to specify quotation(s) that will appear on the top left of the chapter title area.

The quotation(s) for the next chapter are specified in a savequote environment; the width of the quotation area can be given as an optional argument defaulting to 10cm. Each quotation should finish with a qauthor command to denote its source, though it would be possible to provide your own formatting manually.

The default layout produced by the package can be described as follows: the quotations are placed flush left, followed by vertical material stored in the command chapterheadstartvskip. It is followed by a very large chapter number, typeset flush right in 60% gray, followed by the chapter title text, also typeset flush right. After a further vertical separation, taken from the command chapterheadendvskip, the first paragraph of the chapter is started without indentation.

The number can be printed in black by specifying the option nogrey to the package. To print the chapter number in one of the freely available PostScript fonts, you can choose among a number of options, such as charter for Bitstream’s Charter BT or times for Adobe’s Times. By default, Adobe’s Bookman is chosen. Alternatively, you could redefine the chapnumfont command, which is responsible for selecting the font for the chapter number. Finally, the font for the chapter title can be influenced by redefining the sectfont command as shown in the example.

This, together with the possibilities offered by redefining the commands chapterheadstartvskip and chapterheadendvskip, allows you to produce a number of interesting layouts. The example below uses a negative vertical skip to move the quotation on the same level as the number (in Avantgarde) and set the title and quotation in Helvetica.

2-2-14
Image

If you want quotations on your chapters but prefer one of the layouts provided by fncychap, you can try to combine both packages. Load the latter package after quotchap. Of course, the customization possibilities described above are then no longer available but savequote will still work, although the quotations will appear always in a fixed position above the heading.

2.2.6. titlesec—A different approach to headings

The information presented so far in this chapter has focused on the tools and mechanisms provided by the LaTeX kernel for defining and manipulating headings, as well as a few packages that provide some extra features, such as predefined layouts, built on top of the standard tools.

The titlesec package created by Javier Bezos approaches the topic differently by providing a complete reimplementation for the heading commands. Javier’s approach overcomes some of the limitations inherent in the original tools and provides a cleaner and more generic interface. The disadvantage is that this package might introduce some incompatibilities with extensions based on the original interfaces. Whether this possibility turns out to be a real issue clearly depends on the task at hand and is likely to vanish more or less completely the moment this interface comes into more widespread use.

The package supports two interfaces: a simple one for smaller adjustments, which is realized mainly by options to the package, and an extended interface to make more elaborate modifications.

The basic interface

The basic interface lets you modify the font characteristics of all headings by specifying one or more options setting a font family (rm, sf, tt), a font series (md, bf), or a font shape (up, it, sl, sc). The title size can be influenced by selecting one of the following options: big (same sizes as for standard LaTeX classes), tiny (all headings except for chapters in text size), or medium or small, which are layouts between the two extremes. The alignment is controlled by raggedleft, center, or raggedright, while the vertical spacing can be reduced by specifying the option compact.

To modify the format of the number accompanying a heading, the command itlelabel is available. Within it hetitle refers to the current sectioning number, such as hesection or hesubsection. The declaration applies to all headings, as can be seen in the next example.

2-2-15
Image
Image

The basic interface offers one more command, itleformat*, that takes two arguments. The first argument (cmd) is a sectioning command we intend to modify. The second argument (format) contains the formatting instruction that should be applied to this particular heading. This declaration works on individual sectioning commands, and its use overwrites all font or alignment specifications given as options to the package (i.e., the options rm, it, and raggedleft in the following example). The last command used in the second argument can be a command with one argument—it will receive the title text if present. In the next example we use this feature to set the subsubsection title in small capitals (though this looks rather ugly with full-sized numbers).

2-2-16
Image

The part heading is not influenced by settings for the basic interface. If you want to modify it, you must use the extended interface described below.

The extended interface

The extended interface consists of two major commands, itleformat and itlespacing. They allow you to declare the “inner” format (i.e., fonts, label, alignment, ...) and the “outer” format (i.e., spacing, indentation, etc.), respectively. This scheme was adopted because people often wish to alter only one or the other aspect of the layout.

Image

The first argument (cmd) is the heading command name (e.g., section) whose format is to be modified. In contrast to @startsection this argument requires the command name—that is, with the backslash in front. The remaining arguments have the following meaning:

shape The basic shape for the heading. A number of predefined shapes are available: hang, the default, produces a hanging label (like section in standard classes); display puts label and heading text on separate lines (like standard chapter); while runin produces a run-in title (like standard paragraph). In addition, the following shapes, which have no equivalents in standard LaTeX, are provided: frame is similar to display but frames the title; leftmargin puts the title into the left margin; while rightmargin places it into the right margin. The last two shapes might conflict with marginpar commands, that is, they may overlap.

A general-purpose shape is block, which typesets the heading as a single block. It should be preferred to hang for centered layouts. Both drop and wrap wrap the first paragraph around the title, with drop using a fixed width for the title and wrap using the width of the widest title line (automatically breaking the title within the limit forced by the left-sep argument of itlespacing). As the interface is extensible (for programmers), additional shapes may be available with your installation.

format The declarations that are applied to the whole title—label and text. They may include only vertical material, which is typeset following the space above the heading. If you need horizontal material, it should be entered in the label or before-code argument.

label The formatting of the label, that is, the heading number. To refer to the number itself, use hesection or whatever is appropriate. For defining chapter headings the package offers chaptertitlename, which produces chaptername or appendixname, depending on the position of the heading in the document.

sep Length whose value determines the distance between the label and title text. Depending on the shape argument, it might be a vertical or horizontal separation. For example, with the frame shape, it specifies the distance between the frame and heading text.

before-code Code executed immediately preceding the heading text. Its last command can take one argument, which will pick up the heading text and thus permits more complicated manipulations (see Example 2-2-19).

after-code Optional code to be executed after formatting the heading text (still within the scope of the declarations given in format). For hang, block, and display, it is executed in vertical mode; with runin, it is executed in horizontal mode. For other shapes, it has no effect.

If the starred form of a heading is used, the label and sep arguments are ignored because no number is produced.

The next example shows a more old-fashioned run-in heading, for which we define only the format, not the spacing around the heading. The latter is manipulated with the itlespacing command.

2-2-17
Image

By default, LaTeX’s section headings are not indented (they are usually of shape hang). If you prefer a normal paragraph indentation with such a heading, you could add indent before the S sign or specify the indentation with the itlespacing declaration, described next.

Image

The starred form of the command suppresses the paragraph indentation for the paragraph following the title, except with shapes where the heading and paragraph are combined, such as runin and drop. The cmd argument holds the heading command name to be manipulated. The remaining arguments are as follows:

left-sep Length specifying the increase of the left margin for headings with the block, display, hang, or frame shape. With ...margin or drop shapes it specifies the width of the heading title, with wrap it specifies the maximum width for the title, and with runin it specifies the indentation before the title (negative values would make the title hang into the left margin).

before-sep Length specifying the vertical space added above the heading.

after-sep Length specifying the separation between the heading and the following paragraph. It can be a vertical or horizontal space depending on the shape deployed.

right-sep Optional length specifying an increase of the right margin, which is supported for the shapes block, display, hang, and frame.

The before-sep and after-sep arguments usually receive rubber length values to allow some flexibility in the design. To simplify the declaration you can alternatively specify *f (where f is a decimal factor). This is equivalent to f ex with some stretchability as well as a small shrinkability inside before-sep, and an even smaller stretchability and no shrinkability inside after-sep.

2-2-18
Image

Spacing tools for headings

The previous example introduced filcenter, but there also exist filleft, filright, and fillast—the latter produces an adjusted paragraph but centers the last line. These commands should be preferred to aggedleft or aggedright inside itleformat, as the latter would cancel left-sep or right-sep set up by the itlespacing command. Alternatively, you can use filinner or filouter, which resolve to filleft or filright, depending on the current page. However, due to TeX’s asynchronous page makeup algorithm, they are only supported for headings that start a new page—for example, chapter in most designs. See Example 2-2-21 on page 43 for a solution to this problem for other headings. Another useful spacing command is wordsep, which refers to the interword space (including stretch and shrink) of the current font.

Indentation after heading

The paragraph indentation for the first paragraph following the headings can alternatively be globally specified using the package options indentafter or noindentafter, bypassing the presence or absence of a star in itlespacing.

Spacing between consecutive headings

By default, the spacing between two consecutive headings is defined to be the after-sep of the first one. If this result is not desired you can change it by specifying the option largestsep, which will put the spacing to the maximum of after-sep from the first heading and before-sep of the second.

Headings at page bottom

After a heading LaTeX tries to ensure that at least two lines from the following paragraph appear on the same page as the heading title. If this proves impossible the heading is moved to the next page. If you think that two lines are not enough, try the option nobottomtitles or nobottomtitles*, which will move headings to a new page whenever the remaining space on the page is less than the current value of ottomtitlespace. (Its default is .2 extheight; to change its value, use enewcommand rather than setlength.) The starred version is preferred, as it computes the remaining space with more accuracy, unless you use headings with drop, margin, or wrap shapes, which may get badly placed when deploying the starred option.

Handling unusual layouts

In most heading layouts the number appears either on top or to the left of the heading text. If this placement is not appropriate, the label argument of itleformat cannot be used. Instead, one has to exploit the fact that the before-code can pick up the heading text. In the next example, the command secformat has one argument that defines the formatting for the heading text and number; we then call this command in the before-code argument of itleformat. Note that the font change for the number is kept local by surrounding it with braces. Without them the changed font size might influence the title spacing in some circumstances.

2-2-19
Image

The same technique can be applied to change the heading text in other ways. For example, if we want a period after the heading text we could define

Image

and then call secformat in the before-code of the itleformat declaration as shown in the previous example.

Measuring the width of the title

The wrap shape has the capability to measure the lines in the title text and return the width of the widest line in itlewidth. This capability can be extended to three other shapes (block, display, and hang) by loading the package with the option calcwidth and then using itlewidth within the arguments of itleformat, as needed.

Rules and leaders

For rules and leaders the package offers the itlerule command. Used without any arguments it produces a rule of height .4pt spanning the full width of the column (but taking into account changes to the margins as specified with the itlespacing declaration). An optional argument lets you specify a height for the produced rule. The starred form of itlerule is used to produce leaders (i.e., repeated objects) instead of rules. It takes an optional width argument and a mandatory text argument. The text is repeatedly typeset in boxes with its natural width, unless a different width is specified in the optional argument. In that case, only the first and the last boxes retain their natural widths to allow for proper alignment on either side.

The command itleline lets you add horizontal material to arguments of itleformat that expect vertical material. It takes an optional argument specifying the alignment and a mandatory argument containing the material to typeset. It produces a box of fixed width taking into account the marginal changes due to the itlespacing declaration. Thus, either the material needs to contain some rubber space, or you must specify an alignment through the optional argument (allowed values are l, r, and c).

The itleline* variant first typesets the material from its mandatory argument in a box of width itlewidth (so you may have to add rubber space to this argument) and then uses this box as input to itleline (i.e., aligns it according to the optional argument). Remember that you may have to use the option calcwidth to ensure that itlewidth contains a sensible value.

In the next somewhat artificial example, which is worth studying though better not used in real life, all of these tools are applied together:

2-2-20
Image

Breaking before a heading

Standard LaTeX considers the space before a heading to be a good place to break the page unless the heading immediately follows another heading. The penalty to break at this point is stored in the internal counter @secpenalty and in many classes it holds the value -300 (negative values are bonus places for breaking). As only one penalty value is available for all heading levels, there is seldom any point in modifying its setting. With titlesec, however, you can exert finer control: whenever a command namebreak is defined (where name is the name of a sectioning command, such as sectionbreak), the latter will be used instead of adding the default penalty. For example,

Image

would result in sections always appearing on top of a page with all pending floats being typeset first.

Always keeping the space above a heading

In some layouts the space above a heading must be preserved, even if the heading appears on top of a page (by default, such spaces vanish at page breaks). This can be accomplished using a definition like the following:

Image

The addpenalty command indicates a (good) break point, which is followed by a zero space that cannot vanish. Thus, the “before” space from the heading will appear as well at the top of the page if a break is taken at the penalty.

Conditional heading layouts

So far we have seen how to define fixed layouts for a heading command using itleformat and itlespacing. The titlesec package also allows you to conditionally change the layout on verso and recto pages, and to use special layouts for numberless headings (i.e., those produced by the starred form of the heading command).

This is implemented through a keyword/value syntax in the first argument of itleformat and itlespacing. The available keys are name, page (values odd or even), and numberless (values true or false). In fact, the syntax we have seen so far, itleformat{section}{..}..., is simply an abbreviation for the general form itleformat{name=section}{..}....

In contrast to the spacing commands filinner and filouter, which can only be used with headings that start a new page, the page keyword enables you to define layouts that depend on the current page without any restriction. To specify the layout for a verso (left-hand) page, use the value even; for a recto (right-hand) page, use the value odd. Such settings only affect a document typeset in twoside mode. Otherwise, all pages are considered to be recto in LaTeX. In the following example we use a block shape and shift the heading to one side, depending on the current page. In a similar fashion you could implement headings that are placed in the margin by using the shapes leftmargin and rightmargin.

2-2-21
Image

Similarly, the numberless key is used to specify that a certain itleformat or itlespacing declaration applies only to headings with (or without) numbers. By default, a heading declaration applies to both cases, so in the example the second declaration actually overwrites part of the first declaration. To illustrate what is possible the example uses quite different designs for the two cases—do not mistake this for an attempt to show good taste. It is important to realize that neither the label nor the sep argument is ignored when numberless is set to true as seen in the example—in normal circumstances you would probably use {}{0pt} as values.

2-2-22
Image
Changing the heading hierarchy

The commands described so far are intended to adjust the formatting and spacing of existing heading commands. With the itleclass declaration it is possible to define new headings.

Image

There are three classes of headings: the page class contains headings that fill a full page (like part in LaTeX’s report and book document classes); the top class contains headings that start a new page and thus appear at the top of a page; and all other headings are considered to be part of the straight class.

Used without any optional argument the itleclass declaration simply changes the heading class of an existing heading cmd. For example,

Image

would result in sections always starting a new page.

If this declaration is used with the optional super-level-cmd argument, you introduce a new heading level below super-level-cmd. Any existing heading command at this level is moved one level down in the hierarchy. For example,

Image

introduces the heading subchapter between chapter and section. The declaration does not define any layout for this heading (which needs to be defined by an additional itleformat and itlespacing command), nor does it initialize the necessary counter. Most likely you also want to update the counter representation for section:

Image

The third variant of itleclass is needed only when you want to build a heading structure from scratch—for example, when you are designing a completely new document class that is not based on one of the standard classes. In that case load the package with the option loadonly so that the package will make no attempt to interpret existing heading commands so as to extract their current layout. You can then start building heading commands, as in the following example:

Image

The start-level is usually 0 or -1; see the introduction in Section 2.2 for its meaning. There should be precisely one itleclass declaration that uses this particular optional argument.

If you intend to build your own document classes in this way, take a look at the documentation accompanying the titlesec package. It contains additional examples and offers further tips and tricks.

2.3. Table of contents structures

A table of contents (TOC) is a special list in which the titles of the section units are listed, together with the page numbers indicating the start of the sections. This list can be rather complicated if units from several nesting levels are included, and it should be formatted carefully because it plays an important rôle as a navigation aid for the reader.

Similar lists exist containing reference information about the floating elements in a document—namely, the list of tables and the list of figures. The structure of these lists is simpler, as their contents, the captions of the floating elements, are normally all on the same level (but see Section 6.5.2).

Standard LaTeX can automatically create these three contents lists. By default, LaTeX enters text generated by one of the arguments of the sectioning commands into the .toc file. Similarly, LaTeX maintains two more files, one for the list of figures (.lof) and one for the list of tables (.lot), which contain the text specified as the argument of the caption command for figures and tables.

The information written into these files during a previous LaTeX run is read and typeset (normally at the beginning of a document) during a subsequent LaTeX run by invoking these commands: ableofcontents, listoffigures, and listoftables.

A TOC needs two, sometimes even three, LaTeX runs

To generate these cross-reference tables, it is always necessary to run LaTeX at least twice—once to collect the relevant information, and a second time to read back the information and typeset it in the correct place in the document. Because of the additional material to be typeset in the second run, the cross-referencing information may change, making a third LaTeX run necessary. This is one of the reasons for the tradition of using different page-numbering systems for the front matter and the main text: in the days of hand typesetting any additional iteration made the final product much more expensive.

The following sections will discuss how to typeset and generate these contents lists. It will also be shown how to enter information directly into one of these auxiliary files and how to open and write into a supplementary file completely under user control.

2.3.1. Entering information into the contents files

Normally the contents files are generated automatically by LaTeX. With some care this interface, which consists of the addcontentsline and addtocontents commands, can also be used to enter information directly.

Image

The addcontentsline command writes the text together with some additional information, such as the page number of the current page, into a file with the extension ext (usually .toc, .lof, or .lot). Fragile commands within text need to be protected with protect. The type argument is a string that specifies the kind of contents entry that is being made. For the table of contents (.toc), it is usually the name of the heading command without a backslash; for .lof or .lot files, figure or table is normally specified.

The addcontentsline instruction is normally invoked automatically by the document sectioning commands or by the caption commands within the float environments. Unfortunately, the interface has only one argument for the variable text, which makes it awkward to properly identify an object’s number if present. Since such numbers (e.g., the heading number) typically need special formatting in the contents lists, this identification is absolutely necessary. The trick used by the current LaTeX kernel to achieve this goal is to surround such a number with the command umberline within the text argument as follows:

Image

For example, a caption command inside a figure environment saves the caption text for the figure using the following line:

Image

Because of the protect command, umberline will be written unchanged into the external file, while hefigure will be executed along the way so that the actual figure number will end up in the file.

Later on, during the formatting of the contents lists, umberline can be used to format the number in a special way, such as by providing extra space or a different font. The downside of this approach is that it is less general than a version that takes a separate argument for this number (e.g., you cannot easily do arbitrary transformation on this number) and it requires a suitable definition for umberline—something that is unfortunately not always available (see the discussion in Section 2.3.2 on page 49).

Sometimes addcontentsline is used in the source to complement the actions of standard LaTeX. For instance, in the case of the starred form of the section commands, no information is written to the .toc file. If you do not want a heading number (starred form) but you do want an entry in the .toc file, you can use addcontentsline with or without umberline as shown in the following example.

2-3-1
Image

Using umberline as in the “Foreword” produces an indented “section” entry in the table of contents, leaving the space where the section number would go free. Omitting the umberline command (as was done for the bibliography entry) would typeset the heading flush left instead. Adding a similar line after the start of the theindex means that the “Index” will be listed in the table of contents. Unfortunately, this approach cannot be used to get the list of figures or tables into the table of contents because listoffigures or listoftables might generate a listing of several pages and consequently the page number picked up by addcontentsline might be wrong. And putting it before the command does not help either, because often these list commands start a new page. One potential solution is to copy the command definition from the class file and put addcontentsline directly into it.

Bibliography or index in table of contents

In case of standard classes or close derivatives you can use the tocbibind package created by Peter Wilson to get the “List of...”, “Index”, or “Bibliography” section listed in the table of contents without further additions to the source. The package offers a number of options such as notbib, notindex, nottoc, notlof, and notlot (do not add the corresponding entry to the table of contents) as well as numbib and numindex (number the corresponding section). By default the “Contents” section is listed within the table of contents, which is seldom desirable; if necessary, use the nottoc option to disable this behavior.

Image

The addtocontents command does not contain a type parameter and is intended to enter special formatting information not directly related to any contents line. For example, the chapter command of the standard classes places additional white space in the .lof and .lot files to separate entries from different chapters as follows:

Image

By using addvspace at most 10 points will separate the entries from different chapters without producing strange gaps if some chapters do not contain any figures or tables.

Potential problems with addvspace

This example, however, shows a certain danger of the interface: while the commands addcontentsline, addtocontents, and addvspace appear to be user-level commands (they do not contain any @ signs in their names), they can easily produce strange errors.1 In particular, addvspace can be used only in vertical mode, which means that a line like the above works correctly only if an earlier addcontentsline ends in vertical mode. Thus, you need to understand how such lines are actually processed to be able to enter arbitrary formatting instructions between them. This is the topic of the next section.

1 For an in-depth discussion of addvspace, see Appendix A.1.5, page 858.

Potential problems with include

If either addcontentsline or addtocontents is used within the source of a document, one important restriction applies: neither command can be used at the same level as an include statement. That means, for example, that the sequence

Image

with sect1.tex containing a section command would surprisingly result in a .toc file containing

Image

showing that the lines appear out of order. The solution is to move the addtocontents or addcontentsline statement into the file loaded via include or to avoid include altogether.

2.3.2. Typesetting a contents list

As discussed above, contents lists are generated by implicitly or explicitly using the commands addcontentsline and addtocontents. The exact effect of

Image

is to place the line

Image

into the auxiliary file with extension ext, where page is the current page number in the document. The command addtocontents{ext}{text} is simpler: it just puts text into the auxiliary file. Thus, a typical contents list file consists of a number of contentsline commands, possibly interspersed with further formatting instructions added as a result of addtocontents calls. It is also possible for the user to create a table of contents by hand with the help of the command contentsline.

Image Inconsistency with part

A typical example is shown below. Note that most (though not all) heading numbers are entered as a parameter of the umberline command to allow formatting with the proper indentation. LaTeX is unfortunately not consistent here; the standard classes do not use umberline for part headings but instead specify the separation between number and text explicitly. Since the 2001/06/01 release you can also use umberline in this place, but with older releases the formatting will be unpredictable.

2-3-2
Image

The contentsline command is implemented to take its first argument type, and then use it to call the corresponding l@type command, which does the actual typesetting. One separate command for each of the types must be defined in the class file. For example, in the report class you find the following definitions:

Image

By defining l@type to call @dottedtocline (a command with five arguments) and specifying three arguments (level, indent, and numwidth), the remaining arguments, text and page, of contentsline will be picked up by @dottedtocline as arguments 4 and 5.

Note that some section levels build their table of contents entries in a somewhat more complicated way, so that the standard document classes have definitions for l@part and l@chapter (or l@section with article) that do not use @dottedtocline. Generally they use a set of specific formatting commands, perhaps omitting the ellipses and typesetting the title in a larger font.

So to define the layout for the contents lists, we have to declare the appropriate l@type commands. One easy way to do this, as shown above, is to use @dottedtocline, an internal command that we now look at in some detail.

Image

The last two parameters of @dottedtocline coincide with the last parameters of contentsline, which itself usually invokes a @dottedtocline command. The other parameters are the following:

level The nesting level of the entry. With the help of the counter tocdepth the user can control how many nesting levels will be displayed. Levels greater than the value of this counter will not appear in the table of contents.

indent The total indentation from the left margin.

indent The total indentation from the left margin.

numwidth The width of the box that contains the number if text has a umberline command. It is also the amount of extra indentation added to the second and later lines of a multiple-line entry.

Additionally, the command @dottedtocline uses the following global formatting parameters, which specify the visual appearance of all entries:

@pnumwidth The width of the box in which the page number is set.

@tocrmarg The indentation of the right margin for all but the last line of multiple-line entries. Dimension, but changed with enewcommand! It can be set to a rubber length, which results in the TOC being set unjustified.

@dotsep The separation between dots, in mu (math units).1 It is a pure number (like 1.7 or 2). By making this number large enough you can get rid of the dots altogether. To be changed with enewcommand!

1 There are 18 mu units to an em, where the latter is taken from the fontdimen2 of the math symbol font symbols. See Section 7.10.3 for more information about fontdimens.

A pictorial representation of the effects described is shown in Figure 2.3. The field identified by numwidth contains a left-justified section number, if present. You can achieve the proper indentation for nested entries by varying the settings of indent and numwidth.

Image

Figure 2.3. Parameters defining the layout of a contents file

Problem with many headings on one level

One case in which this is necessary, while using a standard class (article, report, or book), arises when you have ten or more sections and within the later ones more than nine subsections. In that case numbers and text will come too close together or even overlap if the numwidth argument on the corresponding calls to @dottedtocline is not extended, as seen in the following example.

2-3-3
Image

Redefining l@subsection to leave more space for the number (third argument to @dottedtocline) gives a better result in this case. You will probably have to adjust the other commands, such as l@subsubsection, as well to produce a balanced look for the whole table.

2-3-4
Image

Another example that requires changes is the use of unusual page numbering. For example, if the pages are numbered by part and formatted as “A–78”, “B–328”, and so on, then the space provided for the page number is probably too small, resulting at least in a large number of annoying “Overfull hbox” warnings, but more likely in some bad spacing around them. In that case the remedy is to set @pnumwidth to a value that fits the widest entry—for example, via

Image

When adjusting @pnumwidth this way it is likely that the value of @tocrmarg needs to be changed as well to keep the layout of the table of contents consistent.

The level down to which the heading information is displayed in the table of contents is controlled by the counter tocdepth. It can be changed, for example, with the following declaration:

Image

In this case section heading information down to the second level (e.g., in the report class part, chapter, and section) will be shown.

2.3.3. Combining contents lists

By default, LaTeX produces separate lists for the table of contents, the list of figures, and the list of tables, available via ableofcontents, listoffigures, and listoftables, respectively. None of the standard classes support combining those lists, such as having all tables and figures in a single list, or even combining all three in a single table of contents as is sometimes requested.

How could such a request be fulfilled? The first requirement is that we make LaTeX write to the appropriate auxiliary file when it internally uses addcontentsline. For example, all caption commands need to write to a single file if we want to combine figures and tables in a single list. Looking at the LaTeX sources reveals that this goal is easy to achieve: figure captions write to a file with the extension specified by ext@figure, while table captions use ext@table for this purpose.

So using an appropriate redefinition of, say, ext@table we can force LaTeX to assemble all references to figures and tables in the .lof file. But is this enough? The example clearly shows that it is probably not enough to force the entries together. When looking at the generated list we cannot tell which entry refers to a figure or a table. The only indication that something is amiss is given by the identical numbers on the left.

2-3-5
Image

The situation would be slightly better if the figures and tables share the same counter, so that we do not end up with identical numbers in the left column of the list. Unfortunately, this result is fairly difficult to achieve, because one must directly manipulate the low-level float definitions.

Another possible remedy is to define l@figure and l@table in such a way that this information is present. The example on the following page shows a possible solution that appends the string “(figure)” or “(table)” to each entry. In theory it would also be possible to annotate the number to indicate the type of float, but that would require redefining a lot of LaTeX’s internals such as umberline.

What happens if we force all entries into a single list—that is, into the table of contents? In that case we get a list ordered according to the final appearance of the objects in the document, which may not be what we would expect to see. In the next example, the figure, which actually came last in the source, shows up before the section in which it is referenced, because the float algorithm places it on the top of the page. This outcome might be acceptable within books or reports where the major heading starts a new page and prevents top floats on the heading page, but is probably not desirable in other cases.

2-3-6
Image

In summary, while it is possible to combine various types of contents lists, the results may not be what one would expect. In any case such an approach requires a careful redesign of all l@type commands so that the final list will be useful to the reader.

2.3.4. Providing additional contents files

If you want to make a list comprising all of the examples in a book, you need to create a new contents file and then make use of the facilities described above. First, two new commands must be defined. The first command, ecaption, associates a caption with the current position in the document by writing its argument and the current page number to the contents file. The second command, listofexamples, reads the information written to the contents file on the previous run and typesets it at the point in the document where the command is called.

The listofexamples command invokes @starttoc{ext}, which reads the external file (with the extension ext) and then reopens it for writing. This command is also used by the commands ableofcontents, listoffigures, and listoftables. The supplementary file could be given an extension such as xmp. A command like chapter*{List of examples} can be put in front or inside of listofexamples to produce a title and, if desired, a command addcontentsline can signal the presence of this list to the reader by entering it into the .toc file.

The actual typesetting of the individual entries in the .xmp file is controlled by l@example, which needs to be defined. In the example below, the captions are typeset as paragraphs followed by an italicized page number.

2-3-7
Image

The float package described in Section 6.3.1 on page 291 implements the above mechanism with the command listof, which generates a list of floats of the type specified as its argument.

2.3.5. shorttoc—Summary table of contents

With larger documents it is sometimes helpful to provide a summary table of contents (with only the major sections listed) as well as a more detailed one. This can be accomplished with the shorttoc package created by Jean-Pierre Drucbert.

Image

This shorttableofcontents command (or shorttoc as a synonym) must be specified before the ableofcontents command; otherwise, the summary table of contents will be empty. The table’s heading is given by the title argument and the depth down to which contents entries are shown is defined by the second argument. Thus, to show only chapters and sections in the summary and everything down to subsubsections in the detailed table of contents, you would specify:

Image

The package supports two options, loose (default) and tight, that deal with the vertical spacing of the summary table.

2.3.6. minitoc—Multiple tables of contents

The minitoc package, originally written by Nigel Ward and Dan Jurafsky and completely redesigned by Jean-Pierre Drucbert, enables the creation of mini-tables of contents (a “minitoc”) for chapters, sections, or parts. It also supports the creation of mini-tables for the list of figures and list of tables contained in a chapter, section, or part. A similar functionality, albeit using a completely different approach, is provided by the titletoc package described in Section 2.3.7.

Here we describe in some detail the use of the package to generate such tables on a per-chapter basis. The generation of per-section or per-part tables is completely analogous (using differently named commands); an overview appears at the end of the section.

The package supports almost all language options of the babel system (see Section 9.1.3), which predefine the heading texts used. In addition, the formatting of the generated tables can be influenced by the options loose (default) or tight and dotted (default) or undotted. Further control over the appearance is provided by a number of parameters that can be set in the preamble (see Table 2.3 on the next page).

Image

Table 2.3. A summary of the minitoc parameters

To initialize the minitoc system, you place a dominitoc command before the ableofcontents command. If you do not want a full table of contents but only mini-tables, replace the latter command with faketableofcontents. Mini-lists of figures or tables are initialized similarly, by using dominilof or dominilot, if necessary together with fakelistoffigures or fakelistoftables.

The domini... commands accept one optional argument to denote the position of the table titles: l for left (default), c for center, r for right, or n for no title (a supported synonym is e for empty). The declaration is global for all tables in the document.

The actual mini-tables of contents are then generated by putting the command minitoc in suitable places (typically directly after a chapter command) inside the document. The actual placement is at your discretion. For instance, you may put some text before it or place a box around it. If one of the tables is empty, the package suppresses the heading and issues a warning to alert you about possible formatting problems due to the material added by you around the command.

If you want to generate mini-lists of figures or tables, you use minilof or minilot after initializing the system as explained above.

For each mini-table of contents, an auxiliary file with the extension .mtc n, where n is the chapter number, will be created.1 For mini-lists of figures and tables, files with the extensions .mlf n and .mlt n are created, respectively.

1 A different scheme is automatically used for operating systems in which file extensions are limited to three characters, like MS-DOS. It can be explicitly requested using the option shortext on the usepackage command.

By default, the mini-tables contain only references to sections and subsections. The minitocdepth counter, similar to tocdepth, allows the user to modify this behavior. The fonts used for individual entries can also be modified by changing the definitions of mtcfont and its companions shown in Table 2.3. You can influence the use of rules around the mini-tables by specifying mtcrule (default) or omtcrule in the preamble or before individual mini-tables. Similarly, you can request the use of page numbers in the mini-table by using the mtcpagenumbers declaration (default) or their suppression by using omtcpagenumbers.

As the mini-tables and mini-lists take up room within the document, their use will alter the page numbering. Therefore, three runs normally are needed to ensure correct information in the mini-table of contents.

Mini-tables on part or section level

For mini-tables and mini-lists on the part level, commands similar to those in Table 2.3 are provided. The only difference is that their names contain the string part instead of mini or ptc instead of mtc. Thus, you would use doparttoc to initialize the system, parttoc to print a mini-table, optcrules to suppress rules, and so on. The only addition is the declaration ptcCfont, which defines the font to use for chapter entries and which naturally has no equivalent.

For mini-tables and mini-lists on the section command level, the situation is again similar: replace mini by sect or mtc by stc—for example, use dosecttoc, secttoc, and stcfont. If sectlof or sectlot commands are used, you may want to try the option placeins, which confines floats to their sections by using the placeins package with its options below and section (see Section 6.2.1 on page 288).

2-3-8
Image

To turn off the minitoc commands, merely replace the package minitoc with mtcoff on your usepackage command. This step ensures that all minitoc-related commands in the source will be ignored.

2.3.7. titletoc—A different approach to contents lists

The titletoc package written by Javier Bezos was originally developed as a companion package to titlesec but can be used on its own. It implements its own interface to lay out contents structures, thereby avoiding some of the limitations of the original LaTeX code.

Relation to standard LaTeX

The actual generation of external contents files and their syntax is left unchanged so that it works nicely with other packages generating such files. There is one exception, however: contents files should end with the command contentsfinish. For the standard file extensions .toc, .lof, and .lot, this is handled automatically. But if you provide your own type of contents lists (see Section 2.3.4), you have to announce it to titletoc, as in the following example:

Image

As explained in Section 2.3.2 a contents file consists of contentsline commands that are sometimes separated by some arbitrary code due to the use of addtocontents. To format such contents lines with standard LaTeX we had to define commands of the form l@type; with titletoc, this step is no longer needed. Instead, we declare the desired formatting using the itlecontents declaration (for vertically oriented entries) or its starred form (for run-in entries).

Image

The first argument of itlecontents contains the type of contents line for which we set up the layout—it corresponds to the first argument of contentsline. In other words, for each type of sectioning command that can appear in the document, we need one itlecontents declaration.1 The remaining arguments have the following meaning:

left-indent Argument that specifies the indentation from the left margin for all lines of the entry. It is possible to place material (e.g., the heading number) in this space. Even though this argument has to be given in square brackets, it is not optional in the current package release!

above-code Code to be executed before the entry is typeset. It can be used to provide vertical space, such as by using addvspace, and to set up formatting directives, such as font changes, for the whole entry. You can also use filleft, filright, filcenter, or fillast, already known from the titlesec package, at this point.

numbered-entry-format Code to format the entry including its number. It is executed in horizontal mode (after setting up the indentation). The last token can be a command with one argument, in which case it will receive the entry text as its argument. The unformatted heading number is available in the command hecontentslabel, but see below for other possibilities to access and place it.

numberless-entry-format Code to format the entry if the current entry does not contain a number. Again the last token may be a command with one argument.

page-format Code that is executed after formatting the entry but while still being in horizontal mode. It is normally used to add some filling material, such as a dotted line, and to attach the page number stored in hecontentspage. You can use the itlerule command, discussed on page 41, to produce leaders.

below-code An (optional) argument used to specify code to be executed in vertical mode after the entry is typeset—for example, to add some extra vertical space after the entry.

To help with placing and formatting the heading and page numbers, the titletoc package offers two useful tools: contentslabel and contentspage.

1 The package honors existing l@type declarations made, for example, by the document class. Thus, it can be used to change the layout of only some types.

Image

The purpose of the contentslabel command is to typeset the text (which by default contains hecontentslabel) left aligned in a box of width size and to place that box to the left of the current position. Thus, if you use this command in the numbered-entry-format argument of itlecontents, then the number will be placed in front of the entry text into the margin or indentation set up by left-indent. For a more refined layout you can use the optional argument to specify your own formatting usually involving hecontentslabel.

Package options

The package offers three options to influence the default outcome of the contentslabel command when used without the text argument. With rightlabels the heading number is right aligned in the space. The default, leftlabels, makes it left aligned. With dotinlabels a period is added after the number.

Image

In similar fashion contentspage typesets text (which by default contains hecontentspage) right aligned in a box and arranges for the box to be placed to the right of the current position but without taking up space. Thus, if placed at the right end of a line, the box will extend into the margin. In this case, however, no mandatory argument specifies the box size: it is the same for all entries. Its value is the same as the space found to the right of all entries and can be set by the command contentsmargin described below.

Image A note on the examples in this section

For the examples in this section we copied some parts of the original .toc file generated by LaTeX for this book (Chapter 2 and parts of Chapter 3) into the file partial.toc. Inside the examples we then loaded this file with input and manually added contentsfinish. Of course, in a real document you would use the command ableofcontents instead, so that the .toc file for your document is loaded and processed.

In our first example we provide a new formatting for chapter entries, while keeping the formatting for the section entries as defined by the standard LaTeX document class. The chapter entries are now set ragged right (filright) in bold typeface, get one pica space above, followed by a thick rule. The actual entry is indented by six picas. In that space we typeset the word “Chapter” in small caps followed by a space and the chapter number ( hecontentslabel) using the contentslabel directive with its optional argument. There is no special handling for entries without numbers, so they would be formatted with an indentation of six picas. We fill the remaining space using hfill and typeset the page number in the margin via contentspage. Finally, after the entry we add another two points of space so that the entry is slightly separated from any section entry following.

2-3-9
Image

Instead of indenting the whole entry and then moving some material into the left margin using contentslabel, you can make use of contentspush to achieve a similar effect.

Image

This command typesets text and then increases the left-indent by the width of text for all additional lines of the entry (if any). As a consequence, the indentation will vary if the width of the text changes. In many cases such variation is not desirable, but in some cases other solutions give even worse results. Consider the case of a document with many chapters, each containing dozens of sections. A rigid left-indent needs to be able to hold the widest number, which may have five or six digits. In that case a label like “1.1” will come out unduly separated from its entry text. Given below is a solution that grows with the size of the entry number.

2-3-10
Image
Image

The right margin for all entries can be set to right-sep using the contentsmargin declaration. The default value for this margin is @pnumwidth, which is set by the standard classes to be wide enough to contain up to three digits. The optional correction argument will be added to all lines of an entry except the last. This argument can, for example, be used to fine-tune the contents layout, so that dots from a row of leaders align with the text of previous lines in a multiple-line entry.

Contents entries combined in a paragraph

Standard LaTeX only supports contents entries formatted on individual lines. In some cases, however, it is more economical to format lower-level entries together in a single paragraph. With the titletoc package this becomes possible.

Image

The itlecontents* declaration is used for entries that should be formatted together with other entries of the same or lower level in a single paragraph. The first six arguments are identical to those of itlecontents described on page 59. But instead of a vertically oriented below-code argument, itlecontents* provides one to three optional arguments that handle different situations that can happen when entries are about to be joined horizontally. All three optional arguments are by default empty. The joining works recursively as follows:

• If the current entry is the first entry to participate in joining, then its start-code is executed before typesetting the entry.

• Otherwise, there has been a previous entry already participating.

– If both entries are on the same level, then the mid-code is inserted.

– Otherwise, if the current entry is of a lower level, then the start-code for it is inserted and we recur.

– Otherwise, the current entry is of a higher level. First, we execute for each level that has ended the final-code (in reverse order). Then, if the current entry is not participating in joining, we are done. Otherwise, the mid-code for the entry is executed, as a previous entry of the same level should already be present (assuming a hierarchically structured document).

If several levels are to be joined, then you have to specify any paragraph layout information in the before-code of the highest level participating. Otherwise, the scope of your settings will not include the paragraph end and thus will not be applied. In the following example, footnotesize applies only to the section entries—the aselineskip for the whole paragraph is still set in ormalsize. This artificial example shows how one can join two different levels using the three optional arguments. Note in particular the spaces added at the beginning of some arguments to get the right result when joining.

2-3-11
Image

Let us now see how this works in practice. In the next example we join the section level, separating entries by a bullet surrounded by some stretchable space (xquad) and finishing the list with a period. The chapter entries are interesting as well, because we move the page number to the left. Both types omit the heading numbers completely in this design. As there are no page numbers at the right, we also set the right margin to zero.

2-3-12
Image

As a second example we look at a set-up implementing a layout close to the one used in Methods of Book Design [170]. This design uses non-lining digits, something we achieve by using the eco package. The chapter titles are set in small capitals. To arrange that we use scshape and turn all letters in the title to lowercase using MakeLowercase (remember that the last token of the numbered-entry-format and the numberless-entry-format arguments can be a command with one argument to receive the heading text). The sections are all run together in a paragraph with the section number getting a § sign prepended. Separation between entries is a period followed by a space, and the final section is finished with a period as well.

2-3-13
Image
Generating partial table of contents lists

It is possible to generate partial contents lists using the titletoc package; it provides four commands for this purpose.

Image

A partial table of contents is started with startcontents. It is possible to collect data for several partial TOCs in parallel, such as one for the current part as well as one for the current chapter. In that case the optional name argument allows us to distinguish between the two (its default value is the string default). Concurrently running partial TOCs are allowed to overlap each other, although normally they will be nested. All information about these partial TOCs is stored in a single file with the extension .ptc; this file is generated once a single startcontents command is executed.

Image

This command prints the current partial TOC started earlier by startcontents; if the optional name argument is used, then a partial contents list with that name must have been started.1

1 The package is currently (as of 2003) quite unforgiving if you try to print a contents list without first starting it—you will receive an unspecific low-level TeX error.

It is quite likely that you want to format the partial TOC differently from the main table of contents. To allow for this the prefix argument is prepended to any entry type when looking for a layout definition provided via itlecontents or its starred form. In the example below we used p- as the prefix and then defined a formatting for p-subsection to format subsection entries in the partial TOC.

The start-level argument defines the first level that is shown in the partial TOC; in the example we used the value 2 to indicate that we want to see all subsections and lower levels.

The depth to which we want to include entries in the partial TOC can be set in toc-code by setting the tocdepth to a suitable value. Other initializations for typesetting the partial TOC can be made there as well. In the example we cancel any right margin, because the partial TOC is formatted as a single paragraph.

Integrating partial TOCs in the heading definitions so that there is no need to change the actual document is very easy when titletoc is used together with the titlesec package. Below we extend Example 2-2-18 from page 40 so that the section command now automatically prints a partial TOC of all its subsections. This is done by using the optional after-code argument of the itleformat declaration. We first add some vertical space, thereby ensuring that no page break can happen at this point. We next (re)start the default partial TOC with startcontents. We then immediately typeset it using printcontents; its arguments have been explained above. Finally, we set up a formatting for subsections in a partial TOC using itlecontents* to run them together in a justified paragraph whose last line is centered (fillast). Stringing this all together gives the desired output without any modification to the document source. Of course, a real design would also change the look and feel of the subsection headings in the document to better fit those of the sections.

2-3-14
Image

If necessary, one can temporarily (or permanently) stop collecting entries for a partial TOC. We made use of this feature in the previous example by suppressing the third subsection.

Image

The stopcontents command stops the entry collection for the default partial TOC or, if used with the name argument, for the TOC with that name. At a later point the collection can be restarted using esumecontents. Note that this is quite different from calling startcontents, which starts a new partial TOC, thereby making the old entries inaccessible.

2.4. Managing references

LaTeX has commands that make it easy to manage references in a document. In particular, it supports cross-references (internal references between elements within a document), bibliographic citations (references to external documents), and indexing of selected words or expressions. Indexing facilities will be discussed in Chapter 11, and bibliographic citations in Chapters 12 and 13.

To allow cross-referencing of elements inside a document, you should assign a “key” (consisting of a string of ASCII letters, digits, and punctuation) to the given structural element and then use that key to refer to that element elsewhere.

Image

The label command assigns the key to the currently “active” element of the document (see below for determining which element is active at a given point). The ef command typesets a string, identifying the given element—such as the section, equation, or figure number—depending on the type of structural element that was active when the label command was issued. The pageref command typesets the number of the page where the label command was given. The key strings should, of course, be unique. As a simple aid it can be useful to prefix them with a string identifying the structural element in question: sec might represent sectional units, fig would identify figures, and so on.

2-4-1
Image

Image Restrictions on the characters used in keys

There is a potential danger when using punctuation characters such as a colon. In certain language styles within the babel system (see Chapter 9), some of these characters have special meanings and behave essentially like commands. The babel package tries hard to allow such characters as part of label keys but this can fail in some situations. Similarly, characters outside the ASCII range, made available through packages such as inputenc, are not officially supported in such keys and are likely to produce errors if used.

For building cross-reference labels, the “currently active” structural element of a document is determined in the following way. The sectioning commands (chapter, section, ...), the environments equation, figure, table, and the theorem family, as well as the various levels of the enumerate environment, and footnote set the current reference string, which contains the number generated by LaTeX for the given element. This reference string is usually set at the beginning of an element and reset when the scope of the element is exited.

Image Problems with wrong references on floats

Notable exceptions to this rule are the table and figure environments, where the reference string is defined by the caption commands. This allows several caption and label pairs inside one environment.1 As it is the caption directive that generates the number, the corresponding label command must follow the caption command in question. Otherwise, an incorrect number will be generated. If placed earlier in the float body, the label command will pick up the current reference string from some earlier entity, typically the current sectional unit.

1 There are, however, good reasons for not placing more than one caption command within a float environment. Typically proper spacing is difficult to achieve and, more importantly, future versions of LaTeX might make this syntax invalid.

The problem is shown clearly in the following example, where only the labels “fig:in2” and “fig:in3” are placed correctly to generate the needed reference numbers for the figures. In the case of “fig:in4” it is seen that environments (in this case, center) limit the scope of references, since we obtain the number of the current section, rather than the number of the figure.

2-4-2
Image

For each key declared with label{key}, LaTeX records the current reference string and the page number. Thus, multiple label commands (with different key identifiers key) inside the same sectional unit will generate an identical reference string but, possibly, different page numbers.

2.4.1. showkeys—Displaying the reference keys

When writing a larger document many people print intermediate drafts. With such drafts it would be helpful if the positions of label commands as well as their keys could be made visible. This becomes possible with the showkeys package written by David Carlisle.

When this package is loaded, the commands label, ef, pageref, cite, and ibitem are modified in a way that the used key is printed. The label and ibitem commands normally cause the key to appear in a box in the margin, while the commands referencing a key print it in small type above the formatted reference (possibly overprinting some text). The package tries hard to position the keys in such a way that the rest of the document’s formatting is kept unchanged. There is, however, no guarantee for this, and it is best to remove or disable the showkeys package before attempting final formatting of the document.

2-4-3
Image

The package supports the fleqn option of the standard classes and works together with the packages of the AMS-LaTeX collection, varioref, natbib, and many other packages. Nevertheless, it is nearly impossible to ensure its safe working with all packages that hook into the reference mechanisms.

If you want to see only the keys on the label command in the margin, you can suppress the others by using the package option notref (which disables the redefinition of ef, pageref, and related commands) or the option notcite (which does the same for cite and its cousins from the natbib and harvard packages). Alternatively, you might want to use the option color to make the labels less obstructive.

Finally, the package supports the options draft (default) and final. While the latter is useless when used on the package level, because you can achieve the same result by not specifying the showkeys package, it comes in handy if final is specified as a global option on the class.

2.4.2. varioref—More flexible cross-references

In many cases it is helpful, when referring to a figure or table, to put both a ef and a pageref command into the document, especially when one or more pages separate the reference and the object. Some people use a command like

Image

to reduce the number of keystrokes necessary to make a complete reference. But because one never knows with certainty where the referenced object finally falls, this method can result in a citation to the current page, which is disturbing and should therefore be avoided. The package varioref, written by Frank Mittelbach, tries to solve that problem. It provides the commands vref and vpageref to deal with single references, as well as vrefrange and vpagerefrange to handle multiple references. In addition, its labelformat declaration offers the ability to format references differently depending on the counter used in the reference.

Image

The command vref is like ef when the reference and label are on the same page. If the label and reference differ by one page, vref creates one of these strings: “on the facing page”, “on the preceding page”, or “on the following page”. The word “facing” is used when both label and reference fall on a double spread. When the difference is larger than one page, vref produces both ef and pageref. Note that when a special page numbering scheme is used instead of the usual Arabic numbering (for example, pagenumbering{roman}), there will be no distinction between being one or many pages off.

There is one other difference between ef and vref: the latter removes any preceding space and inserts its own. In some cases, such as after an opening parenthesis, this is not desirable. In such cases, use vref*, which acts like vref but does not add any space before the generated text.

Image

Sometimes you may only want to refer to a page number. In that case, a reference should be suppressed if you are citing the current page. For this purpose the vpageref command is defined. It produces the same strings as vref except that it does not start with ef, and it produces the string saved in eftextcurrent if both label and reference fall on the same page.

Defining eftextcurrent to produce something like “on this page” ensures that text like

Image

does not come out as “... see the diagram which shows ...”, which could be misleading.

You can put a space in front of vpageref; it will be ignored if the command does not create any text at all. If some text is added, an appropriate space is automatically placed in front of the text. The variant form vpageref* removes preceding white space before the generated text but does not reinsert its own. Use it if the space otherwise generated poses a problem.

In fact, vpageref and vpageref* allow even more control when used with their two optional arguments. The first argument specifies the text to be used if the label and reference fall on the same page. This is helpful when both are close together, so that they may or may not be separated by a page break. In such a case, you will usually know whether the reference comes before or after the label so that you can code something like the following:

Image

The resultant text will be “... see the diagram above which shows ...” when both are on the same page, or “... see the diagram on the page before which shows ...” (or something similar, depending on the settings of the eftext..before and eftext..after commands) if they are separated by a page break. Note, however, that if you use vpageref with the optional argument to refer to a figure or table, depending on the float placement parameters, the float may show up at the top of the current page and therefore before the reference, even if it follows the reference in the source file.1

1 To ensure that a floating object always follows its place in the source use the flafter package, which is described in Section 6.2.

Maybe you even prefer to say “... see the above diagram” when both diagram and reference fall on the same page—that is, reverse the word order compared to our previous example. In fact, in some languages the word order automatically changes in that case. To allow for this variation the second optional argument otherpage can be used. It specifies the text preceding the generated reference if both object and reference do not fall on the same page. Thus, one would write

Image

to achieve the desired effect.

The amsmath package provides a eqref command to reference equations. It automatically places parentheses around the equation number. To utilize this, one could define

Image

to automatically add a page reference to it.

Image

This command is similar to vref but takes two mandatory arguments denoting a range of objects to refer to (e.g., a sequence of figures or a sequence of equations). It decides what to say depending on where the two labels are placed in relation to each other; it is essentially implemented using vpagerefrange (described below). The optional argument that the command may take is the text to use in case both labels appear on the current page. Its default is the string stored in eftextcurrent.

2-4-4
Image
Image

This command is similar to vpageref but takes two mandatory arguments—two labels denoting a range. If both labels fall on the same page, the command acts exactly like vpageref (with a single label); otherwise, it produces something like “on pages 15–18” (see the customization possibilities described below). Like vrefrange it has an optional argument that defaults to the string stored in eftextcurrent and is used if both labels appear on the current page.

Fancy labels

Again there exists a starred form, vpagerefrange*, which removes preceding white space before the generated text without reinserting its own space.

A reference via ef produces, by default, the data associated with the corresponding label command (typically a number); any additional formatting must be provided by the user. If, for example, references to equations are always to be typeset as “equation (number)”, one has to code “equation ( ef{key})”.

Image

With labelformat the varioref package offers a possibility to generate such frills automatically.1 The command takes two arguments: the name of a counter and its representation when referenced. Thus, for a successful usage, one has to know the counter name being used for generating the label, though in practice this should not pose a problem. The current counter number (or, more exactly, its representation) is picked up as an argument, so the second argument should contain #1.

1 This command is also available separately with the fncylab package written by Robin Fairbairns.

A side effect of using labelformat is that, depending on the defined formatting, it becomes impossible to use ef at the beginning of a sentence (if its replacement text starts with a lowercase letter). To overcome this problem varioref introduces the commands Ref and Vref (including starred forms) that behave like ef and vref except that they uppercase the first token of the generated string. In the following example (which you should compare to Example 2-4-3 on page 68), you can observe this behavior when “section” is turned into “Section”.

2-4-5
Image

To make Ref or Vref work properly the first token in the second argument of labelformat has to be a simple ASCII letter; otherwise, the capitalization will fail or, even worse, you will end up with some error messages. If you actually need something more complicated in this place (e.g., an accented letter), you have to explicitly surround it with braces, thereby identifying the part that needs to be capitalized. For example, for figure references in the Hungarian language you might want to write labelformat{figure}{{'a}bra~ hefigure}.

As a second example of the use of labelformat consider the following situation: in the report or book document class, footnotes are numbered per chapter. Referencing them would normally be ambiguous, given that it is not clear whether we refer to a footnote in the current chapter or to a footnote from a different chapter. This ambiguity can be resolved by always adding the chapter information in the reference, or by comparing the number of the chapter in which the label occurred with the current chapter number and adding extra information if they differ. This is achieved by the following code:

Image

The trick is to use protect to prevent iscurrentchapter from being evaluated when the label is formed. Then when the ef command is executed, iscurrentchapter will compare its argument (i.e., the chapter number current when the label was formed) to the now current chapter number and, when they differ, typeset the appropriate information.

Providing your own reference commands

The package also provides the vrefpagenum command, which allows you to write your own small commands that implement functions similar to those provided by the two previous commands. It takes two arguments: the second is a label (i.e., as used in label or ef) and the first is an arbitrary command name (make sure you use your own) that receives the page number related to this label. Thus, if you have two (or more) labels, you could retrieve their page numbers, compare them, and then decide what to print.

The next example shows a not very serious application that compares two equation labels and prints out text depending on their relative positions. Compare the results of the tests on the first page with those on the second.

2-4-6
Image

Package options

The package supports the options defined by the babel system (see Section 9.1.3); thus a declaration like usepackage[german]{varioref} will produce texts suitable for the German language. In addition, the package supports the options final (default) and draft; the latter changes certain error messages (described on page 75) into warnings. This ability can be useful during the development of a document.

Individual customization

To allow further customization, the generated text strings (which will be predefined by the language options) are all defined via macros. Backward references use eftextbefore if the label is on the preceding page but invisible, and eftextfacebefore if it is on the facing page (that is, if the current page number is odd).

Similarly, eftextafter is used when the label comes on the next page but one has to turn the page, and eftextfaceafter when it is on the next, but facing, page. These four strings can be redefined with enewcommand.

The command eftextfaraway is used when the label and reference differ by more than one page, or when they are non-numeric. This macro is a bit different from the preceding ones because it takes one argument, the symbolic reference string, so that you can make use of pageref in its replacement text. For instance, if you wanted to use your macros in German language documents, you would define something like:

Image

The eftextpagerange command takes two arguments and produces the text that describes a page range (the arguments are keys to be used with pageref). See below for the English language default.

Similarly, eftextlabelrange takes two arguments and describes the range of figures, tables, or whatever the labels refer to. The default for English is “ ef{#1} to~ ef{#2}”.

To allow some random variation in the generated strings, you can use the command eftextvario inside the string macros. This command takes two arguments and selects one or the other for printing depending on the number of vref or vpageref commands already encountered in the document.

The default definitions of the various macros described in this section are shown below:

Image

If you want to customize the package according to your own preferences, just write appropriate redefinitions of the above commands in a file with the extension .sty (e.g., vrflocal.sty). If you also put RequirePackage{varioref} (see Section A.4 on page 877) at the beginning of this file, then your local package will automatically load the varioref package. If you use the babel system, redefinitions for individual languages should be added using addto, as explained in Section 9.5.

Some people do not like textual references to pages but want to automatically suppress a page reference when both label and reference fall on the same page. This can be achieved with the help of the hevpagerefnum command as follows:

Image

Within one of the eftext... commands, hevpagerefnum evaluates to the current page number if known, or to two question marks otherwise.

A few warnings

Defining commands, like the ones described above, poses some interesting problems. Suppose, for example, that a generated text like “on the next page” gets broken across pages. If this happens, it is very difficult to find an acceptable algorithmic solution and, in fact, this situation can even result in a document that will always change from one state to another (i.e., inserting one string; finding that this is wrong; inserting another string on the next run which makes the first string correct again; inserting ...). The current implementation of the package varioref considers the end of the generated string as being relevant. For example,

Table 5 on the current page break page

would be true if Table 5 were on the page containing the word “page”, not the one containing the word “current”. However, this behavior is not completely satisfactory, and in some cases may actually result in a possible loop (where LaTeX is requesting an additional run over and over again). Therefore, all such situations will produce a LaTeX error message, so that you can inspect the problem and perhaps decide to use a ef command in that place.

Also, be aware of the potential problems that can result from using eftextvario: if you reference the same object several times in nearby places, the change in wording every second time will look strange.

A final warning: every use of vref or vpageref internally generates two macro names. As a result, you may run out of name space or main memory if you make heavy use of this command on a small TeX installation. For this reason the command fullref is also provided. It can be used whenever you are sure that both label and reference cannot fall on nearby pages.

2.4.3. prettyref—Adding frills to references

One problem with LaTeX’s cross-referencing mechanism is that it only produces the element number (or the page number) but leaves the surrounding formatting as the responsibility of the author. This means that uniform references are difficult to achieve. For example, if the publisher’s house style requires that figures be referenced as “Fig.xx” one has to manually go through the source document and change all references to that format.

The prettyref package written by Kevin Ruland provides automatic support for such additional formatting strings, provided the keys used on the label commands obey a certain structure. They have to be of the form “prefix : name” with neither prefix nor name containing a colon (e.g., fig:main), a form used by many people anyway. The extra formatting strings are produced when using the command prettyref; standard ef and pageref are not affected by the package. Note that this is different from the labelformat declaration, as provided by varioref, which changes the display of the reference labels in all circumstances.

Image

This command defines the formatting for references having the prefix as the prefix in their key. The code argument uses #1 to refer to the key used so that it can be passed to ef, vref, and so on. This format can be accessed when using the key with the command prettyref.

2-4-7
Image

The example shows that the prettyref package has formatting for the prefixeq” already built in. In fact, it knows about several other predefined formats, but since most of them allow breaking between the generated text and the number you should probably define your own.

Because this package does not make any distinction between references used at the beginning of a sentence and references used in mid-sentence, it may not be usable in all circumstances. It is also impossible to replace the colon that separates prefix and name, which means that it cannot be combined with some language packages that use the colon in special ways. In that case you might consider using the fancyref package written by Axel Reichert, which provides a similar functionality but internally uses a much more complex set-up.

2.4.4. titleref—Non-numerical references

In some documents it is required to reference sections by displaying their title texts instead of their numbers, either because there is no number to refer to or because the house style asks for it. This functionality is available through the titleref package written by Donald Arseneau, which provides the command itleref to cross-reference the titles of sections and float captions.

Image Unnumbered sections get moving arguments

For numbered sections and floats with captions, the titles are those that would be displayed in the contents lists (regardless of whether such a list is actually printed). That is, if a short title is provided via the optional argument of a sectioning command or caption, then this title is printed by itleref. Unnumbered sections take their title reference from the printed title. As a consequence, the arguments of unnumbered sectioning commands are turned into moving arguments, which will cause weird errors if they contain unprotected fragile commands.

A itleref to a label unrelated to a title (e.g., a label in a footnote, or an enumeration item) will simply pick up any earlier title, typically the one from the surrounding section.

As shown in the next example, the title of the current section is available through currenttitle, independently of whether it was associated with a label key. The example also shows that itleref and ef can coexist.

2-4-8
Image

The format of the title reference can be controlled by redefining the command heTitleReference. It takes two arguments: a number as it would be displayed by ef, and a title. If a document contains references to unnumbered titles, the number argument should not be used in the replacement text as it will contain an arbitrary number. For instance, the itleref command in the next example displays “1”, even though the reference is to an unnumbered section.

2-4-9
Image

Conflicts with other packages

By default, the package works by inserting additional code into commands that are typically used to build headings, captions, and other elements. If combined with other packages that provide their own methods for typesetting titles, it might create conflicts. In that case you can tell the package to use a completely different approach by specifying the option usetoc. As the name implies, it directs the package to record the titles from the data written to the contents lists by redefining addcontentsline. A consequence of this approach is that the label command is not allowed within the title argument but has to follow it. In addition, no unrelated addcontentsline command is allowed to intervene between heading and label. As starred sectioning commands do not generate contents entries, they are still redefined. This can be prevented by additionally specifying the option nostar, although then one can no longer refer to their titles.

2.4.5. hyperref—Active references

Sebastian Rahtz (with contributions by Heiko Oberdiek and David Carlisle) has developed the package hyperref, which makes it possible to turn all cross-references (citations, table of contents, and so on) into hypertext links. It works by extending the existing commands with functionality to produce special commands that suitably equipped drivers can use to turn the references into hypertext links. The package is described in detail in [56, pp.35–67] and comes with its own manual, which itself contains hypertext links produced using the package.

The usage of hyperref can be quite easy. Just including it in your list of loaded packages (as the last package) suffices to turn all cross-references in your document into hypertext links. The package has a number of options to change the way the hypertext links look or work. The most important options are colorlinks, which makes the text of the link come out in color instead of with a box around it, and backref, which inserts links in the bibliography pointing to the place where an entry was cited.

The package offers a number of ways to influence the behavior of the PDF file produced from your document as well as ways to influence the behavior of the PDF viewer, such as the Adobe Reader.

2.4.6. xr—References to external documents

David Carlisle, building on earlier work of Jean-Pierre Drucbert, developed a package called xr, which implements a system for external references.

If, for instance, a document needs to refer to sections of another document—say, other.tex—then you can specify the xr package in the main file and give the command externaldocument{other} in the preamble. Then you can use ef and pageref to refer to anything that has been defined with a label command in either other.tex or your main document. You may declare any number of such external documents.

If any of the external documents or the main document uses the same label key, then a conflict will occur because the key will have been multiply defined. To overcome this problem, externaldocument takes an optional argument. If you declare externaldocument[A-]{other}, then all references from the file other.tex are prefixed by A-. So, for instance, if a section in the file other.tex had a label{intro}, then it could be referenced with ef{A-intro}. The prefix need not be A-; it can be any string chosen to ensure that all the labels imported from external files are unique.

Note, however, that if one of the packages you are using declares certain active characters (e.g., : in French or " in German), then these characters should not be used inside label commands. Similarly, you should not use them in the optional argument to externaldocument.

The package does not work together with the hyperref package because both modify the internal reference mechanism. Instead, you can use the xr-hyper package, which is a reimplementation tailored to work with hyperref.

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

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