Chapter 4. The Layout of the Page

In this chapter we will see how to specify different page layouts. Often a single document requires several different page layouts. For instance, the layout of the first page of a chapter, which carries the chapter title, is generally different from that of the other pages in that chapter.

We first introduce LaTeX’s dimensional parameters that influence the page layout and describe ways to change them and visualize their values. This is followed by an in-depth discussion of the packages typearea and geometry, both of which provide sophisticated ways to implement page layout specifications. The third section deals with the LaTeX concepts used to provide data for running headers and footers. This is followed by a section that explains how to format such elements, including many examples deploying the fancyhdr package and others. The fifth section then introduces commands that help in situations when the text does not fit into the layout and manual intervention is required. The chapter concludes with a brief look at two generic classes that go a long way toward providing almost full control over the page layout specification process.

4.1. Geometrical dimensions of the layout

The text of a document usually occupies a rectangular area on the paper—the so-called type area or body. Above the text there might be a running header and below it a running footer. They can consist of one or more lines containing the page number; information about the current chapter, section, time, and date; and possibly other markers. If they are visually heavy and closely tied to the text, then these elements are considered to belong to the type area; this is often the case for running headers, especially when underlined. Otherwise, they are considered to belong to the top or bottom margins. This distinction is important when interpreting size specifications.

4-1-1
Image

The fields to the left and the right of the body are also called margins. Usually they are left blank, but small pieces of text, such as remarks or annotations—so-called marginal notes—can appear there.

In general one talks about the inner and the outer margins. For two-sided printing, inner refers to the middle margins—that is, the left margin on recto (odd-numbered) pages and the right margin on verso (even-numbered) ones. For one-sided printing, inner always indicates the left margin. In a book spread, odd-numbered pages are those on the right-hand side.

The size, shape, and position of these fields and margins on the output medium (paper or screen) and the contents of the running headers and footers are collectively called a page layout.

The standard LaTeX document classes allow document formatting for recto–verso (two-sided) printing. Two-sided layouts can be either asymmetrical or symmetrical (the LaTeX default). In the latter case the type areas of recto and verso pages are positioned in such a way that they overlap if one holds a sheet to the light. Also, marginal notes are usually swapped between left/right pages.

The dimensional parameters controlling the page layout are described and shown schematically in Figure 4.1 on the facing page.1 The default values of these parameters depend on the paper size. To ease the adjustments necessary to print on different paper sizes, the LaTeX class files support a number of options that set those parameters to the physical size of the requested paper as well as adjust the other parameters (e.g., extheight) that depend on them.

1 The graphical presentation was produced with the layouts package, described in Section 4.2.1.

Image

Figure 4.1. Page layout parameters and visualization

Table 4.1 shows the paper size options known to standard LaTeX classes together with the corresponding page dimensions. Table 4.2 on the following page presents the page layout parameter values for the letterpaper paper size option, the default when no explicit option is selected. They are identical for the three standard LaTeX document classes (article, book, and report). If a different paper size option is selected the values may change. Thus, to print on A4 paper, you can simply specify documentclass[a4paper]{article}.

Image

Table 4.1. Standard paper size options in LaTeX

Image

Table 4.2. Default values for the page layout parameters (letterpaper)

Additional or different options may be available for other classes. Nevertheless, there seems to be little point in providing, say, an a0paper option for the book class that would produce incredibly wide text lines.

Most of the layout parameters in LaTeX class files are specified in terms of the physical page size. Thus, they automatically change when paperwidth or paperheight is modified via one of the paper size options. Changing these two parameters in the preamble of your document does not have this effect, since by then the values for the other parameters are already calculated.

One-inch default margins

Standard-conforming dvi drivers place the reference point for TeX one inch down and to the right of the upper-left corner of the paper. These one-inch off-sets are called driver margins. The reference point can be shifted by redefining the lengths hoffset and voffset. By default, their values are zero. In general, the values of these parameters should never be changed. They provide, however, a convenient way to shift the complete page image (body, header, footer, and marginal notes) on the output plane without disturbing the layout. The driver margins are inherited from TeX, and are not needed in LaTeX’s parameterization of the page layout. A change to opmargin shifts the complete text vertically, while changes to oddsidemargin and evensidemargin shift it horizontally.

Note that some dvi drivers introduce their own shifts in the placement of the text on paper. To make sure that the reference point is properly positioned, you can run the test file testpage.tex (by Leslie Lamport, with modifications by Stephen Gildea) through LaTeX and the dvi driver in question. The resulting output page will show the position of the reference point with respect to the edges of the paper. For LaTeX2ε this file was rewritten by Rainer Schöpf to allow the specification of a paper size option.

4.2. Changing the layout

Image Change parameters only in the preamble

When you want to redefine the value of one or more page layout parameters, the setlength and addtolength commands should be used. It is important to keep in mind that changes to the geometrical page layout parameters should be made only in class or package files and/or in the preamble (i.e., before the egin{document} command). Although changing them in mid-document is not absolutely impossible, it will most likely produce havoc, due to the inner workings of TeX, which involve a number of subtle dependencies and timing problems. For example, if you change the extwidth you might find that the running header of the previous page is changed.

Initially, it is advisable to use TeX’s aselineskip parameter for setting vertical distances. This parameter is the distance between the baselines of two consecutive lines of text set in the “normal” document type size inside a paragraph. The aselineskip parameter may be considered to be the height of one line of text. Therefore, the following setting always means “two lines of text”:

Image

To guarantee that aselineskip is set properly, first set up the fonts used in the document (if necessary), and then invoke ormalsize to select the type size corresponding to the document base size.

Sometimes it is convenient to calculate the page layout parameters according to given typographic rules. For example, the requirement “the text should contain 50 lines” can be expressed using the command given below. It is assumed that the height of all (except one) lines is aselineskip and the height of the top line of the text body is opskip (this is TeX’s aselineskip length parameter for the first line with a default value of 10pt). Note that the examples in this chapter use the LaTeX package calc (which simplifies the calculational notation) and the extended control structures of LaTeX2ε (see Appendix A, Sections A.3.1 and A.3.2).

Image

A requirement like “the height of the body should be 198 mm” can be met in a similar way, and the calculation is shown below. First calculate the number of lines that the body of the desired size can contain. To evaluate the number of lines, divide one dimension by another to obtain the integer part. As TeX is unable to perform this kind of operation directly, the dimensions are first assigned to counters. The latter assignment takes place with a high precision because sp units are used internally.

Image

The value of the vertical distance, opmargin, can also be customized. As an example, suppose you want to set this margin so that the space above the text body is two times smaller than the space below the text body. The following calculation shows how to determine the needed value in the case of A4 paper (the paper height is 297 mm).

Image

In general, when changing the page layout you should take into account some elementary rules of legibility (see, for example, [150]). Studies of printed material in the English language have shown that a line should not contain more than 10–12 words, which corresponds to not more than 60–70 characters per line.

The number of lines on a page depends on the type size being used. The code below shows one way of calculating a extheight that depends on the document base size. Use the fact that in most document classes the internal LaTeX command @ptsize holds the number 0, 1, or 2 for the base font size 10pt, 11pt, or 12pt, respectively. This command is set when you select an option such as 11pt.

Image

Another important parameter is the amount of white space surrounding the text. As printed documents are likely to be bound or stapled, enough white space should be left in the inner margin of the text to allow for this possibility. If oddsidemargin is fixed, then the calculation of evensidemargin for two-sided printing is based on the following relationship:

Image

In most classes two-sided printing is turned on by specifying the twoside class option, which sets the Boolean register @twoside to true. Using commands from the ifthen package we can set parameters depending on the value of this Boolean register, also taking into account the selected document base size:

Image

Similarly, when a document contains a lot of marginal notes, it is worthwhile changing the layout to increase the margins. As an example, the (obsolete) a4 package defines a command WideMargins. This macro modifies the geometrical parameters in such a way that the width reserved for marginal notes is set to 1.5 inches by decreasing the width of the text body.

4.2.1. layouts—Displaying your layout

To visualize your layout parameter settings and help you experiment with different values there are two packages available. The package layout (originally written by Kent McPherson and converted to LaTeX2ε by Johannes Braams) provides the command layout, which produces a graphical representation of the current page parameters with all sizes reduced by a factor of two. If the class option twoside is used then two pages are produced.

A more flexible solution is provided by the package layouts written by Peter Wilson. This package can be used for two purposes: to produce an abstract graphical representation of the layout parameters (not reflecting the current settings) via pagediagram (as shown in the next example) or to produce trial layouts that show the effect of setting parameters to trial values and then applying the command pagedesign. In either mode setlayoutscale sets the scale factor to the specified value.

4-2-1
Image

To produce a trial layout you first have to specify suitable values for all page layout parameters. For each parameter param, there exists a declaration ryparam that accepts the trial values for this parameter as an argument. For example, ryheadsep{18pt} would produce a layout with headsep set to 18pt.

In addition, there are four Boolean-like declarations: oddpagelayoutfalse produces an “even page” (default is to produce odd pages), the declaration wocolumnlayouttrue produces a two-column layout (default is a single-column layout). The command eversemarginpartrue mimics the result of LaTeX’s eversemarginpar, and marginparswitchfalse prevents marginal notes from changing sides between verso and recto pages (a suitable setting for asymmetrical layouts, which are easily produced using the geometry package; see page 208).

To facilitate the specification of trial values you can start your trial by specifying currentpage. It sets all trial values and Boolean switches to the values currently used in your document.

By default, the footer has a height of one line, as LaTeX has no explicit parameter to change the box size of the footer. However, depending on the page style used this choice might not be appropriate, as the footer box defined by the page style might have an exceptionally large depth. To produce a diagram that is (approximately) correct in this case, one can set the footer box height and depth explicitly using setfootbox as we do in the example below.

This example also shows that you can combine this package with the calc package to allow arithmetic expressions in your trial declarations.

4-2-2
Image

Controlling the presentation

A number of display control statements influence the visual representation of the printed page designs, some of which were used in the previous example. The most important are discussed here, whilst others are described in the documentation accompanying the package.

With the setlabelfont declaration the font size used for the textual labels can be changed. Similarly, setparametertextfont influences the font sizes for parameters if they are shown (e.g., Example 4-2-1 on the preceding page).

The heading text displayed on top of the example can be suppressed with printheadingsfalse. The Boolean flag printparametersfalse suppresses the tabular listing of parameter values below the diagram. A similar table can be generated separately using the command pagevalues.

With drawdimensionstrue arrows are drawn to indicate where parameters apply (by default, this feature is turned on in pagediagram and off when pagedesign is used).

Visualizing other layout objects

The layouts package is not restricted to page layouts. It also supports the visualization of other objects. Eight “diagram” commands can be used to show the general behavior of other LaTeX layout parameters. The listdiagram command visualizes the list-related parameters (it is used in Figure 3.3 on page 145). The ocdiagram command shows which parameters influence table of content lists and how they relate to each other. Float-related parameters are visualized using floatdiagram and floatpagediagram. Parameters for sectioning commands are displayed with headingdiagram, and parameters related to footnotes and general paragraphs can be shown with footnotediagram and paragraphdiagram. Finally, the stockdiagram command produces a page layout diagram similar to pagediagram but displays parameters available only in the memoir document class and its derivatives (see Section 4.6.2 on page 237).

There also exist corresponding “design” commands, such as listdesign, ocdesign, floatdesign, floatpagedesign, headingdesign, and so on, that allow you to experiment with different parameter settings. For each parameter a declaration ry param allows you to set its value for visualization. The full list of parameters supported this way is given in the package documentation. But if you know the applicable LaTeX parameters (or look them up on the “diagram” command results) you can start experimenting straight away.

4.2.2. A collection of page layout packages

Because the original LaTeX class files were based on American page sizes, European users developed several packages that adapt the page layout parameters for metric sizes. All such packages are superseded by the typearea or geometry package (described in the next two sections) and for new documents we recommend that you use these packages. As you will find the original attempts still in the archives, we mention them here in passing.

Examples of such packages are a4, which generates rather small pages; a4dutch (by Johannes Braams and Nico Poppelier), which is well documented; and a4wide (by Jean-François Lamy), which produces somewhat longer lines. Moreover, often there exist locally developed files under such names. For A5 pages one has the package files a5 and a5comb (by Mario Wolczko). The problem with all of these early packages was that they allowed little to no customization with respect to the size and placement of the text area and, for some of them, incompatible implementations exist.

A more general approach was taken by the vmargin package written by Volker Kuhlmann. His package supports a variety of paper sizes and allows you to specify a number of layout parameters with a single declaration, calculating others from the input (a number of variant declarations exist). In the example below the margins are specified and the text area is calculated.

4-2-3
Image

The package internally cancels the default offset of one inch (added normally by TeX output devices) by using a negative hoffset and voffset, a fact that can cause some surprise. This behavior can be seen in the example, where the dashed lines normally indicating this offset have vanished behind the page border and only the circle at (1 inch, 1 inch) remains.

4.2.3. typearea—A traditional approach

In books on typography one usually finds a section that deals with page layout, often describing construction methods for placing the text body and providing one or the other criterion for selecting text width, number of text lines, relationship between margins, and other considerations.

The package typearea by Markus Kohm and Frank Neukam, which is distributed as part of the KOMA-Script bundle, offers a simple way to deploy one of the more traditional page layout construction methods that has been used for many books since the early days of printing.

In a nutshell, the page layout generated by typearea provides a text body with the same spatial relationship as given by the paper size on which the document is being printed. In addition, the outer margin will be twice as wide as the inner margin and the bottom margin will be twice as wide as the top margin.

The construction method works by dividing the paper horizontally and vertically into n equal slices and then using one slice at the top and inner edges and two slices at the bottom and outer edges for the margins. By default, the variable n is calculated automatically by the package. It can also be requested explicitly (for example, to overwrite a configuration setting in the file typearea.cfg) by using the option DIVcalc. This option works by examining the document font and selecting a value that results in approximately 60–70 characters per text line, assuming a portrait page. Alternatively, one can explicitly set the value of n by specifying the option DIVn, resulting in n slices. As a third possibility, one can specify the option DIVclassic, which results in a page layout close to that found in certain types of medieval books.

The page height resulting from the chosen or calculated DIV value is automatically adjusted to produce an integral number of text lines. For this approach to work, the effective aselineskip used throughout the document has to be established first. Thus, when using a package like setspace or applying the command linespread this step should be taken prior to loading typearea.

For defining the paper typearea offers all of the paper size options of LaTeX’s standard classes (see Table 4.1 on page 195) as well as all sizes of the ISO-A, ISO-B, and ISO-C series (e.g., a0paper or c5paper). To change the text orientation use landscape, as in the example below.

4-2-4
Image

The calculated DIV value is recorded in the .log file of the LaTeX run together with the values chosen for other page parameters. In the above example this value was 7, so instead of DIVcalc we could have used DIV7.

Determining the body area

So far, we have explained how the package chooses the text body dimensions and how it places that body on the page, but we have not discussed whether the running header and footer participate in that calculation. This issue must be decided depending on their content. If, for example, the running header contains a lot of material, perhaps even with a rule underlining it, and thus contributes considerably to the grey value of the page, it is best regarded as part of the page body. In other cases it might be more appropriate to consider it as being part of the margin (e.g., if it is unobstructive text in small type). For the same reason a footer holding only the page number should normally be considered as lying outside the text body and not contributing to the placement calculations.

The choices for a particular document can be explicitly specified with the options headinclude, footinclude, headexclude, and footexclude. The latter two options are used by default. With large DIV values (i.e., small margins), excluding the header or footer might make it fall off the page boundary so you may have to adjust one or the other setting.

In a similar fashion (using mpinclude or mpexclude), one can include or exclude the marginpar area into the calculation for left and right margins. This, too, is turned off by default but it might be appropriate to include it for layouts with many objects of this type.

The header size is by default 1.25 text lines high. This value can be adjusted by using an option of the type num headlines, where num is a decimal number, such as 2.3, denoting the number of text lines the header should span.

The next example has header and marginals included and the header size is enlarged to 2.5 lines. Compare this example to the layout in Example 4-2-4 on the preceding page, where header, footer, and marginals are excluded.

4-2-5
Image

Depending on the type of binding for the final product, more or less of the inner margin will become invisible. To account for this loss of white space the package supports the option BCOR val, where val is the amount of space (in any LaTeX unit) taken up by the binding. For example, BCOR1.2cm would subtract 1.2 centimeters from the page width prior to doing the page layout calculations.

As an alternative to customizing the layout through options to the package, one can perform the parameter calculations with the command ypearea; for details, see the KOMA-Script documentation. This ability is useful, for example, if a document class, such as one of the classes in the KOMA-Script bundle, already loads the typearea package and you want to use an unusual body font by loading it in the preamble of the document. In that case the layout calculations need to be redone to account for the properties of the chosen font.

4-2-6
Image

4.2.4. geometry—Layout specification with auto-completion

The geometry package written by Hideo Umeki provides a comprehensive and easy-to-use interface to all geometrical aspects of the page layout. It deploys the keyval package so that all parameters (and their values) can be specified as options to the usepackage declaration.

In contrast to the typearea package, geometry does not implement a certain typographical concept but rather carries out specifications as requested. It knows, however, about certain relationships between various page parameters and in case of incomplete specifications can calculate the remaining parameter values automatically. The following example shows a layout very similar to the one produced by typearea in Example 4-2-5 on the preceding page. Here a number of values have been explicitly set (e.g., those for the top and left margins), but the size of the page body has been automatically calculated from the paper size (a5paper), the values for top margin (tmargin) and left margin (lmargin), and a specified margin ratio of 1:2 (marginratio).

4-2-7
Image

The example also shows that with Boolean options it is permissible to leave out the value part (which then defaults to =true); with all other options the value part is mandatory.

The remainder of this section discusses the various page layout aspects that are supported by geometry. In most cases there is more than one way to achieve the same result because some of the parameters have to satisfy certain relations. If your specification violates such a relation, geometry will warn you and then ignore one or the other option setting.

Paper sizes

The paper size can be specified with the paper option, which accepts the values a0paper to a6paper, and b0paper to b6paper. Alternatively, the values letterpaper, legalpaper, and executivepaper can be used. For convenience you are allowed to denote the paper size by specifying the named paper as an option; for example, a5paper is equivalent to the specification paper=a5paper.

When formatting for a computer display you might want to try the option screen. To specify other nonstandard sizes you can use paperwidth and paperheight to define the appropriate dimensions explicitly.

General page characteristics

With respect to general page characteristics, geometry supports the Boolean options twoside, landscape (switching paper height and width), and portrait. Obviously, portrait=false is just a different way of specifying landscape.

If a certain part of the page becomes invisible due to the binding method, you can specify this loss of white space with the option bindingoffset. It will add the specified value to the inner margin.

When the Boolean option twocolumn is specified, the text area will be set up to contain two columns. In this case the separation between columns can be specified through the option columnsep.

What constitutes the body area

In Section 4.2.3 describing the typearea package, we stated that, depending on the nature of the document, it may be appropriate to consider the running header and/or footer (and in some cases even the part of the margin taken up by marginal notes) as being part of the text body. By default, geometry excludes the header, footer, and marginals. As these settings modify the relationship between body and margin sizes used for calculating missing values, they should be set appropriately. To change the defaults, a number of Boolean options1 are available: includemp, to include the marginals, which is seldom necessary; includehead, to be used with heavy running headers; includefoot, which is rarely ever necessary, as the footer normally contains only a page number; and includeheadfoot and includeall, which are shorthand for combinations of the other options.

1 The typearea package offers the same functionality, with similar (though in fact different) option names, such as headinclude instead of includehead.

Footnotes are always considered to be part of the text area. With the option footnotesep you specify only the separation between the last text line and the footnotes; the calculation of the margins remains unaffected.

Text area

For specifying the text body size several methods are available; the choice of which to use is largely a matter of taste. You can explicitly specify the text area size by giving values for textwidth and textheight. In that case you should normally ensure that textheight holds an integral number of text lines to avoid underfull box messages for pages consisting only of text. A convenient way to achieve this goal is to use the lines option, which calculates the appropriate extheight using the current values for aselineskip and opskip.

Alternatively, you can set the Boolean option heightrounded, in which case geometry will adjust the extheight appropriately. This Boolean option is especially useful if the body size is calculated automatically by the package—for example, if you specify the values for only some of the margins and let the package work out the rest.

As an alternative to specifying the text area and having the package calculate the body size by adding the sizes of the header, footer, and/or marginals as specified through the above options, you can give values for the whole body area and have the package calculate the text area by subtracting. This is done with the options width and height (this approach, of course, differs from the previous approach only if you have included header and/or footer). If this method is used consider specifying heightrounded to let the package adjust the calculated extheight as needed.

If you do not like specifying fixed values but prefer to set the body size relative to the page size, you can do so via the options hscale and vscale. They denote the fraction of the horizontal or vertical size of the page that should be occupied by the body area.

Margins

The size of the margins can be explicitly specified through the options lmargin, rmargin, tmargin, and bmargin (for the left, right, top, and bottom margins, respectively). If the Boolean option twoside is true, then lmargin and rmargin actually refer to the inner and outer margins, so the option names are slightly misleading. To account for this case, the package supports inner and outer as alternative names—but remember that they are merely aliases. Thus, if used with the asymmetric option (described below), they would be confusing as well. To give you even more freedom there exists another set of option names: left, right, top, and bottom. If you choose to specify only verso pages (the recto pages being automatically produced by selecting twoside or asymmetric), then the first or the last set of names is probably the best choice.

If none, or only some, of the margin sizes are specified, the missing ones are calculated. Given the equations

Image
Image

then knowing two values from the righthand side allows the calculation of the third value (instead of width or height the body area might be specified through some of the other methods discussed above). If only one value from the righthand side is specified, the package employs two further equations to reduce the free variables:

Image
Image

The default value for the hmarginratio option is 2:3 when twoside is true, and otherwise 1:1. The default for vmarginratio is 2:3 without exception.

The allowed values for these “ratio” options are restricted: both numbers have to be positive integers less than 100 separated with a colon. For example, you would use 4:5 instead of 1:1.25.

If you wish to center the body area, use the option centering. It is a convenient shorthand for setting hmarginratio and vmarginratio both to 1:1.

Asymmetrical and symmetrical layouts

In standard LaTeX classes the option twoside actually fulfills a dual purpose: beside setting up the running header and footer to contain different content on verso and recto pages, it automatically implements a symmetrical layout with left and right margins (including marginal notes) swapped on verso pages. This outcome is shown in the next example, which also highlights the fact that geometry by default selects a very large text area but does not adjust the size of the marginal boxes to fit in the remaining margin.

4-2-8
Image

With the geometry package, however, asymmetrical page layouts are possible, simply by using the option asymmetric. The use of bindingoffset in the next example proves that an asymmetrical two-sided layout is indeed produced, as the offset is applied to the inner margins and not always to the left margin, even though the marginal notes always appear on the left. As we want the larger margin on the left, we have to change hmarginratio appropriately. At first glance the right margin on the verso page might appear incorrectly large given a marginal ratio of 2:1; this is due to the bindingoffset being added to it.

4-2-9
Image

Running header and footer

The dimensions for the running header and its separation from the text area can be specified through the options headheight and headsep. The distance between the text area and the footer is available through footskip. There also exist the Boolean options nohead, nofoot, and noheadfoot, which set these dimensions to zero. In most circumstances, however, it is better to use ignorehead, etc. as this will allow you to attach the header or footer on one or the other page without affecting the margin calculations.

Marginal notes

As most documents do not contain many marginal notes, the space occupied by them by default does not count toward the margin calculations. This space can be specified with marginparwidth, and the separation from the text area can be set with marginparsep. Unless includemp is specified it is the user’s responsibility to ensure that this area falls within the calculated or specified margin size.

By default, the marginal notes appear in the outer margin. By specifying the Boolean option reversemp this set-up can be reversed.

Miscellaneous features

Instead of using an external package, such as layouts, to visualize the results produced by geometry, one can use its built-in option showframe. By default, all settings, including any calculated values, are recorded in the transcript file of the current LaTeX run. Setting the Boolean option verbose ensures that these settings are also displayed on the terminal.

Some TeX extensions or device drivers such as pdfTeX or VTeX like to know about the dimensions of the paper that is being targeted. The geometry package accounts for this by providing the options pdftex, vtex, dvipdfm, and dvips. Naturally, at most one of them should be specified. If a document is processed with the pdfTeX program then the pdftex option is automatically selected (and the others are disabled).

Like most packages these days, geometry supports the extended syntax of the calc package if the latter is loaded before geometry.

To account for unusual behavior of the printing device, LaTeX maintains two dimension registers, hoffset and voffset, which will shift all output (on every page) horizontally to the right and vertically downward by the specified amount. The package supports the setting of these registers via the options hoffset and voffset. They have no effect on the calculation of other page dimensions.

Magnification

The TeX program offers a magnification feature that magnifies all specified dimensions and all used fonts by a specified factor. Standard LaTeX has disabled this feature, but with geometry it is again at the disposal of the user via the option mag. Its value should be an integer, where 1000 denotes no magnification. For example, mag=1414 together with a5paper would result in printing on a4paper, as it enlarges all dimensions by Image, the factor distinguishing two consecutive paper sizes of the ISO-A series. This ability can be useful, for example, if you later wish to photomechanically reduce the printed output to achieve a higher print resolution. As this option also scales fonts rather than using fonts designed for a particular size, it is usually not adequate if the resulting (magnified) size is your target size.

When magnification is used, you can direct TeX to leave certain dimensions unmagnified by prepending the string true to the unit. For example, left=1truein would leave a left margin of exactly one inch regardless of any magnification factor. Implicitly specified dimensions (such as the paper size values, when specifying a paper option) are normally subject to magnification unless the option truedimen is given.

Shortcuts

The previously described options allow you to specify individual values, but for the most common cases geometry also provides combination options. They allow you to set several values in one pass by specifying either a single value (to be used repeatedly) or a comma-separated list of values (which must be surrounded by braces so that the commas are not mistaken for option delimiters).

The option papersize takes a list of two dimensions denoting the horizontal and vertical page dimensions.

The option hmargin sets the left and right margins, either to the same value if only a single value is given, or to a list of values. Similarly, vmargin sets the top and bottom margins. This operation can sometimes be shortened further by using the option margin, which passes its value (or list) to hmargin and vmargin. In the same way marginratio passes its value to hmarginratio and vmarginratio for further processing.

The text area dimensions can be specified using the body option, which takes one or two values setting textwidth and textheight. Alternatively, you can use the option total, which is a shortcut for setting width and height. You can also provide one or two scaling factors with the option scale that are then passed to hscale and vscale.

Preamble usage

If the geometry package is used as part of a class you may wish to overwrite some of its settings in the preamble of your document. In that case the usepackage option interface is of little use because the package is already loaded. To account for such situations the package offers the command geometry, which takes a comma-separated list of options as its argument. It can be called multiple times in the preamble, each time overwriting the previous settings. In the next example its use is demonstrated by first loading the package and setting all margins to one inch and the header, footer, and marginals to be part of the body area, and then changing the right margin to two inches and excluding the marginals from the calculation.

4-2-10
Image

Two other options might be handy when using the geometry interface. With reset you restore the package defaults and with pass you basically disable the package itself.

4.2.5. lscape—Typesetting individual pages in landscape mode

For most documents the longer side of the paper corresponds to the vertical direction (so-called portrait orientation). However, for some documents, such as slides and tables, it is better to use the other (landscape) orientation, where the longer side is horizontally oriented. Modern printers and dvi drivers usually allow printing in both orientations.

The landscape and portrait orientations require different page layouts, and with packages like geometry you have the tools at hand to design them as needed. But sometimes it is desirable to switch between portrait and landscape mode for only some pages. In that case the previously discussed packages do not help, as they set up the page design for the whole document.

For this case you can use the lscape package by David Carlisle that defines the environment landscape to typeset a selected set of pages in landscape orientation without affecting the running header and footer. It works by first ending the current page (with clearpage, thereby typesetting any dangling floats). It then internally exchanges the values for extheight and extwidth and rotates every produced page body within its scope by 90 degrees. For the rotation it deploys the graphics package, so it works with any output device supported by that package capable of rotating material. When the environment ends it issues another clearpage before returning to portrait mode.

For rotating individual floats, including or excluding their captions, a better alternative is provided by the rotating package, described in Section 6.3.3.

4.2.6. crop—Producing trimming marks

When producing camera-ready copy for publication, the final printing is normally done on “stock paper” having a larger size than the logical page size of the document. In that case the printed copy needs trimming before it is finally bound. For accurate trimming the printing house usually requires so-called crop marks on each page. Another reason for requiring crop marks is the task of mounting two or more logical pages onto a physical one, such as in color production where different colors are printed separately.

The crop package created by Melchior Franz supports these tasks by providing a simple interface for producing different kinds of crop marks. It also offers the ability to print only the text or only the graphics from a document, and the chance of inverting, mirroring, or rotating the output, among other things—all features useful during that part of the printing process.

Crop marks can be requested by using one of the following options:

cam Produces four marks that show the logical paper dimensions without touching them (see Example 4-2-11 on the next page). They are mainly intended for camera alignment.

cross Produces four large crosses at the corners of the logical page touching its edges.

frame Produces a frame around the logical page; mainly intended for clearly visualizing the page dimensions.

The package assumes that the paperheight and paperwidth dimensions correctly reflect the size of the logical page you want to produce. The size of the physical page (the stock paper) you are actually printing on is then given as an option to the package. Options include a0, a1, a2, a3, a4, a5, a6, b0, b1, b2, b3, b4, b5, b6, executive, legal, and letter. If you use the physical paper in landscape orientation (i.e., with the long side horizontally), you can also specify the option landscape. If none of these options matches your physical paper sizes, you can specify the exact sizes through the options width and height, both of which take dimensional values.

The following example sets up an artificially small logical page (to fit the example area of this book) using the geometry package and centers it on a physical page of A5 size. However, since all our examples are actually cropped to their “visible” size and since, for obvious reasons, we have not actually marked the borders of the A5 paper, you cannot see that it was properly centered at one stage—either believe us or try it yourself.

4-2-11
Image

It should be clear from the description and the example that this package should be loaded after the document layout has been specified.

The informational text between the top crop marks is added by default. It can be suppressed by adding the option noinfo, though it is usually a good idea to keep it. The information contains both the page number (as known to LaTeX) and a page index, which starts with 1 and is incremented for every page being printed. Especially with large publications using several page numbering methods at once, this is a helpful device to ensure that pages are not misordered.

Several options of the crop package rely on support given by the printer driver. If no driver option is explicitly given, the package tries to determine the driver from installation settings for the graphics or color package. It is also possible to indicate the driver explicitly by using options such as dvips, pdfLaTeX, or vtex. If one of these options is selected the paper size information is passed to the external driver program, which is important if you want to view the document using ghostview or similar programs.

If you want to print graphics separately—for example, because running the complete document through a color printer is infeasible—you can produce different versions of the same document: one containing only the text but no graphics (or, more precisely, without graphics included via includegraphics) and one containing only the graphics (or, more precisely, with all text printed in the color “white”). These effects can be achieved using the options nographics and notext, respectively. Clearly, the latter option can be used only if the target device is capable of understanding color commands since internally the color package is being deployed. The next example1 shows the use of the nographics and cross options; compare it to the output of Example 4-2-11.

1 The cross crop marks look admittedly rather weird at this measure.

4-2-12
Image

Three other options require the output device to be able to obey the extended commands of the graphics and color packages for rotation, mirroring, and background coloring. With the option rotate the pages are turned through 180 degrees. The option mirror flips each page as shown in the next example. Finally, the option invert will invert white and black, so that the text appears in white on a black surface.

4-2-13
Image

4.3. Dynamic page data: page numbers and marks

LaTeX’s output routine, which produces the typeset pages, works asynchronously. That is, LaTeX assembles and prepares enough material to be sure that a page can be filled and then builds that page, usually leaving some residual material behind to be used on the next page(s). Thus, while preparing headings, paragraphs, and other page elements, it is usually not known on which page this material will eventually be placed because LaTeX might eventually decide that this material will not fit on the current page. (We have already discussed this problem in the section about page-wise footnote numbering.)

When the final page is typeset, we might want to repeat some information from its contents in the running header or footer (e.g., the current section head), to give the reader extra guidance. You cannot save this information in commands when the material is collected; during this phase LaTeX often reads too far ahead and your command would then contain data not appearing on the final page. LaTeX solves this problem by providing a mark mechanism through which you can identify data as being of interest for the assembled page. In the output routine all marks from the page are collected and the first and the last mark are made available. The detailed mechanism is explained in this section together with some useful extension packages.

4.3.1. LaTeX page numbers

The page number is controlled through a counter named page. This counter is automatically stepped by LaTeX whenever it has finished a page—that is, after it has been used. Thus, it has to be initialized to 1, whereas most other LaTeX counters require an initialization to 0 as they are stepped just before they get used.

The command to access the typographical representation of the page number is hepage, following standard LaTeX convention. There is, however, another subtle difference compared to other LaTeX counters: the hepage command is not defined by the LaTeX kernel but instead comes into existence only after the first execution of a pagenumbering declaration, which typically happens in the document class file.

The best (though perhaps not the most convenient) way to get at the page number for the current page in the middle of the text is via a combination of the commands label and pageref, which should be put directly one following the other so that no page break can interfere.

4-3-1
Image

Because of the asynchronous nature of the output routine you cannot safely use hepage within the document body. It is reliable only in declarations that influence the look and feel of the final page built by the output routine.

Image

The pagenumbering command resets the page counter to 1 and redefines the command hepage to style{page}. Ready-to-use page counter styles include: Alph, alph, Roman, roman, and arabic (see Section A.1.4).

For example, an often seen convention is to number the pages in the front matter with roman numerals and then to restart the page numbers using arabic numbers for the first chapter of the main matter. You can manually achieve this effect by deploying the pagenumbering command twice; the frontmatter and mainmatter commands available with the book class implement this set-up implicitly behind the scenes.

4.3.2. lastpage—A way to reference it

Standard LaTeX has no way to refer to the number of pages in a document; that is, you cannot write “this document consists of 6 pages” or generate “page 5 of 10” without manually counting the pages yourself. The package lastpage by Jeffrey Goldberg sets out to overcome this problem by automatically generating a label with the name LastPage on the last page, so that you can refer to its page number via pageref{LastPage}. Example 4-4-5 on page 226 demonstrates its use.

The string produced by that call to pageref is the content of hepage as it would appear on the last page. If your document restarts page numbering midway through—for example, when the front matter has its own numbering—this string will not reflect the absolute number of pages.

The package works by generating the label within the AtEndDocument hook, making sure that any pending floats are placed first. However, as this hook might also be used by other packages to place textual material at the end of the document, there is a chance that the label may be placed too early. In that case you can try to load lastpage after the package that generates this extra material.

4.3.3. chappg—Page numbers by chapters

For some publications it is required to restart numbering with every chapter and to display the page number together with the chapter number on each page. This can already be done with the commands at our disposal by simply putting

Image

after each chapter command. But this technique is clumsy and requires us to put a lot of layout information in our document, something that is better avoided.

A better approach is to use the package chappg, originally written by Max Hailperin and later reimplemented and extended by Robin Fairbairns. It works with any document class that has a chapter command and provides a new page numbering style bychapter to achieve the desired page numbering scheme. Furthermore, it extends the pagenumbering command to accept an optional argument that enables you to put a prefix different from the chapter number before the page number. This ability is, for example, useful in the front matter where typically unnumbered headings are used.

4-3-2
Image

In fact, by exerting some care you can even use this package together with a class that does not define a chapter command. Suppose your highest heading level is section and each section automatically starts a new page (the latter is an important requirement). Then the declaration

Image

will give you page numbers within sections. However, if sections do not start a new page this approach might fail, as LaTeX may have seen an upcoming section and incremented hesection without actually putting that section onto the current page. If so, you will experience the same problem that we saw earlier with respect to hepage.

Finally, the separator between the prefix and the page number is also customizable, since it is produced by the command chappgsep. Thus,

Image

will give you pages like 3/1, 3/2, 3/3, 3/4, and so on, if “3” is the current chapter number.

4.3.4. LaTeX mark commands

The TeX primitive mark, which you may encounter inside package code dealing with page layout or output routines, is ultimately responsible for associating some text (its argument) with a position on a page (i.e., the position where the mark is executed). When producing the final page TeX makes the first mark on the assembled page available in firstmark, the last in otmark, and the otmark from the previous page as opmark. If there are no marks on that page then firstmark and otmark also inherit the value of the previous otmark. Thus, if each heading command would internally issue a mark with the heading text as its argument, then one could display the first or last heading text on a page in the running header or footer by using these commands.

Image Low-level TeX marks cannot be used in LaTeX

However, it is not possible to use these commands directly in LaTeX, as LaTeX uses a higher-level protocol to control marks, so please do not try this. We mention them here only to explain the underlying general mechanism. LaTeX effectively structures the content of the mark argument so that the direct use of this command will most likely result in strange error messages.

As a replacement for the mark command, standard LaTeX offers the following two commands to generate marks:

Image

The first command sets a pair of marker texts at the current point in the document. The second command also internally generates a pair of markers, but it changes only the sub-mark one, inheriting the main-mark text from a previous markboth.

The original intention behind these commands was to provide somewhat independent marks—for example, chapter headings as main-marks and section headings as sub-marks. However, the choice of the command name markright already indicates that Leslie Lamport had a specific marking scheme in mind when he designed those commands, which will become even more apparent when we look at the commands to retrieve the marker values in the output routine.

In the output routine leftmark contains the main-mark argument of the last markboth command before the end of the page. The ightmark command contains the sub-mark argument of the first markright or markboth on the page, if one exists; otherwise, it contains the one most recently defined.

The marking commands work reasonably well for right markers “numbered within” left markers—hence the names (for example, when the left marker is changed by a chapter command and the right marker is changed by a section command). However, it produces somewhat anomalous results if a markboth command is preceded by some other mark command on the same page—see the pages receiving L2 R1.1 and L5 R3.2 in Figure 4.2 on the next page. This figure shows schematically which left and right markers are generated for the pages being shipped out. For some type of running headers it would be better to display the first main-mark or the last sub-mark. For this purpose you could enlist the help of the extramarks package described below, as standard LaTeX does not offer this possibility. Also notice that there is no way to set a main-mark without setting (and thus overwriting) the sub-mark.

Image

Figure 4.2. Schematic overview of how LaTeX’s marker mechanism works

In layouts that use running headers generated from heading texts it would be nice if these markers are automatically generated from the corresponding heading commands. Fortunately, there exists an interface that allows us to define which heading commands produce markers and what text is passed to the mark. This scheme works as follows: all standard heading commands internally invoke a command namemark, where name is the name of the heading command (e.g., chaptermark, sectionmark). These commands have one argument in which they receive the heading text or its short form from the optional argument of the heading command.

By default, they all do nothing. If redefined appropriately, however, they can produce a marker pair as needed by LaTeX. For instance, in the book class these commands are defined (approximately) as follows:

Image

In the case of a chapter, the word “Chapter” (or its equivalent in a given language; see Table 9.2 on page 547 in Section 9.2.1) followed by the sequence number of the chapter (stored in the counter chapter) and the contents of (a short version of) the chapter title will be placed in the main-mark argument of markboth; at the same time the sub-mark will be cleared. For a section, the section number (stored in the counter section) followed by the contents of (a short version of) the section title will be passed to markright, which generates a marker pair with a new sub-mark.

4.3.5. extramarks—Providing new marks

As we have seen so far, LaTeX’s mark mechanism was built with a certain layout in mind and is, therefore, only partially usable for other applications. As a result a number of attempts have been made to extend or replace it with code that supports more complex marking mechanisms.

Part of the limitation is inherent in TeX itself, which provides only one type of marks and thus makes different independent marks difficult (though not impossible) to implement. This issue is resolved in eTeX, which provides independent mark classes. However, since this program is not yet in widespread use, there are no packages available that explore the new possibilities offered by the extension of the marking mechanism.

An extended mechanism within the main LaTeX model is provided by the extramarks package written by Piet van Oostrum (distributed as part of fancyhdr). It offers two additional (partially) independent marks, as well as further control over LaTeX standard marks by allowing one to retrieve the first or the last mark on a page for both main-mark and sub-mark.

To refer to the first or last main-mark on a given page, the package offers the commands firstleftmark and lastleftmark, respectively. Similarly, firstrightmark and lastrightmark allow you to access the first or last sub-mark.1 An application is shown in Example 4-4-9 on page 229.

1 As the reader will notice, lastleftmark and firstrightmark are simply aliases for LaTeX’s leftmark and ightmark, with names providing a clearer indication of their functionalities.

Image

To add additional marks to the document the package provides the command extramarks. It takes two mandatory arguments: the texts for two marks at the current point. To refer to the first left-xmark on a page firstleftxmark is used; lastleftxmark retrieves the last mark. In the same way firstrightxmark and lastrightxmark can be used in the output routine to access the right-xmark.

The next example shows these commands in action. With the help of fancyhdr (described in Section 4.4.2), a page layout is constructed in which the first left-xmark is shown at the top of a page and the last right-xmark is displayed at the bottom right of each page. Of particular interest in the example is the use of the extramarks. We start with an extramarks that contains “A story” in left-xmark and an empty right-xmark. It is immediately followed by a second set of marks, this time with the values “... continued” and “turn page to continue”. As a result the first left-xmark on the first page will contain “A story” while on later pages it will contain “... continued”. The last right-xmark on each page will always contain “turn page to continue”. Thus, as long as our story continues, we will get proper continuation marks on the top and the bottom of each page. However, at the end of the story, there should be no “turn page to continue”. To cancel that bottom mark, the example contains another extramarks at the very end with an empty right-xmark. Its left-xmark still contains “... continued” to ensure that the last page displays the correct text at the top.

4-3-3
Image

The extra marks can be mixed with LaTeX standard marks produced by the sectioning commands or through markboth and markright. Note, however, that the marks are not fully independent of each other: whenever extramarks or one of the standard LaTeX mark commands is issued, LaTeX effectively generates all four marks (reusing the values for those not explicitly set). As a result the first mark of a particular kind may not be what you expect. For example, if your document starts with an extramarks command, it implicitly generates an empty main-mark and sub-mark.

A third type of primitive, opmark, is also present in the mark model of TeX, which is normally not made available by LaTeX. It holds the value of the otmark from the previous page, reflecting the “mark situation” at the very top of the page—hence its name. The reason that it is not made available by standard LaTeX is that it conflicts with LaTeX’s float and marginpar mechanism. In other words, each such object internally triggers the output routine, with the result that the opmark value for the current page is clobbered.

If, however, neither floats nor marginpars are used, the opmark information could be used, and for such situations extramarks offers an interface to it. People, who have an application for such a top mark can, therefore, access the left-xmark and right-xmark produced via extramarks with the commands opleftxmark and oprightxmark, respectively.

4.4. Page styles

While the dimensions remain the same for almost all pages of a document, the format of the running headers and footers may change in the course of a document. In LaTeX terminology the formatting of running headers and footers is called a page style, with different formattings being given names like empty or plain to be easily selectable.

New page styles can be selected by using the command pagestyle or the command hispagestyle, both of which take the name of a page style as their mandatory argument. The first command sets the page style of the current and succeeding pages; the second applies to the current page only.

In small or medium-size documents sophisticated switching of page styles is normally not necessary. Instead, one can usually rely on the page styles automatically selected by the document class. For larger documents, such as books, typographic tradition, publisher requirements, or other reasons might force you to manually adjust the page style at certain places within the document.

LaTeX’s standard page styles

LaTeX predefines four basic page styles, but additional ones might be provided by special packages or document classes.

empty  Both the header and the footer are empty.

plain  The header is empty and the footer contains the page number.

headings  The header contains information determined by the document class and the page number; the footer is empty.

myheadings  Similar to headings, but the header can be controlled by the user.

Suppressing all page numbers

The first three page styles are used in the standard classes. Usually for the title page, a command hispagestyle{empty} is issued internally. For the first page of major sectioning commands (like part or chapter, but also maketitle), the standard LaTeX class files issue a hispagestyle{plain} command. This means that when you specify a pagestyle{empty} command at the beginning of your document, you will still get page numbers on a page where a chapter or maketitle command is issued. Thus, to prohibit page numbers on all pages of your document, you must follow each such command with a hispagestyle{empty} command or redefine the plain style to empty, by using letps@plain=ps@empty in your private customization package.

In the headings page style the sectioning commands set the page headers automatically by using markboth and markright, as shown in Table 4.3 on the facing page.

Image

Table 4.3. Page style defining commands in LaTeX

The standard page style myheadings is similar to headings, but it allows the user to customize a header by manually using the commands markboth and markright. It also provides a way to control the capture of titles from other sectional units like a table of contents, a list of figures, or an index. In fact, the commands ( ableofcontents, listoffigures, and listoftables) and the environments (thebibliography and theindex) use the chapter* command, which does not invoke chaptermark, but rather issues a @mkboth command. The page style headings defines @mkboth as markboth, while the page style myheadings defines @mkboth to do nothing and leaves the decision to the user.

4.4.1. The low-level page style interface

Internally, the page style interface is implemented by the LaTeX kernel through four internal commands, of which two are called on any one page in order to format the running headers and footers. By redefining these commands different actions can be carried out.

@oddhead  For two-sided printing, it generates the header for the odd-numbered pages; otherwise, it generates the header for all pages.

@oddfoot  For two-sided printing, it generates the footer for the odd-numbered pages; otherwise, it generates the footer for all pages.

@evenhead  For two-sided printing, it generates the header of the even-numbered pages; it is ignored in one-sided printing.

@evenfoot  For two-sided printing, it generates the footer of the even-numbered pages; it is ignored in one-sided printing.

A named page style simply consists of suitable redefinitions for these commands stored in a macro with the name ps@ style; thus, to define the behavior of the page style style, one has to (re)define this command. As an example, the kernel definition of the plain page style, producing only a centered page number in the footer, is similar to the following code:

Image

4.4.2. fancyhdr—Customizing page styles

Given that the page styles of standard LaTeX allow modification only via internal commands, it is not surprising that a number of packages have appeared that provide special page layouts—for example, rplain changes the plain page style so that the page number prints on the right instead of being centered. More elaborate packages exist as well. For example, the page style declaration features of the package titlesec (for defining heading commands, see Section 2.2.6) are worth exploring.

A well-established stand-alone package in this area is fancyhdr1 by Piet van Oostrum, which allows easy customization of page headers and footers. The default page style provided by fancyhdr is named fancy. It should be activated via pagestyle after any changes to extwidth are made, as fancyhdr initializes the header and footer widths using the current value of this length.

1 In this book we describe version 2.0 of fancyhdr. Earlier versions were known under the name fancyheadings.

Basic interface

The look and feel of the fancy page style is determined by six declarations that define the material that will appear on the left, center, and right of the header and footer areas. For example, lhead specifies what should show up on the left in the header area, while cfoot defines what will appear in the center of the footer area. The results of all six declarations are shown in the next example.

4-4-1
Image

In many cases only one part of the footer and header areas receives material for typesetting. If you give more than one declaration with a non-empty argument, however, you have to ensure that the printed text does not get too wide. Otherwise, as the above example clearly shows, you will get partial overprints.

The thickness of the rules below the header and above the footer is controlled by the commands headrulewidth (default 0.4pt) and footrulewidth (default 0pt). A thickness of 0pt makes a rule invisible. Note that both are commands, not length parameters, and thus need changing via enewcommand. More complicated changes are possible by redefining the headrule and/or footrule commands that produce the actual rules, as demonstrated in Example 4-4-6 on page 227. If you redefine these commands you may have to add negative vertical spaces because by default your material will appear at a distance of aselineskip below the header text (or above the footer text).

Shown in the next example is the possibility of producing several lines of text in the running header or footer by using \ in any of the declaration commands. If you take this tack, you usually have to enlarge headheight (the height of the running header or footer box) because it is typically set to a value suitable only for holding a single line. If fancyhdr detects that headheight is too small, it will issue a warning suggesting the smallest possible value that would be sufficient for the current document.

4-4-2
Image

Notice in the previous example that the use of \ will result in stacked lines that are aligned according to the type of declaration in which they appear. For example, inside lhead they align on the left and inside head they align on the right. If this outcome is not what you want, consider using a simple tabular environment instead. Note the @{} in the column declaration for the tabular material, which acts to suppress the standard white space after the column. Without it the header material would not align properly at the border.

4-4-3
Image

Full control

The declarations we have seen so far do not allow you to change the page style depending on the type of the current page. This flexibility is offered by the more general declarations fancyhead and fancyfoot. They take an additional optional argument in which you specify to which type of page and to which field of the header/footer the declaration should apply. Page selectors are O or E denoting odd or even pages, respectively; the fields are selected with L, C, or R. If the page or field selector is missing the declaration applies to all page types or all fields.

Thus, LO means the left field on odd pages, while C would denote the center field on all pages. In other words, the declarations discussed earlier are shorthands for the more general form.

As the next example shows the selectors can even be sequenced. For example, RO,LE means apply this in the right field on odd pages and the left field on even pages.

4-4-4
Image

In fact, fancyhead and fancyfoot are derived from an even more general declaration, fancyhf. It has an identical syntax but supports one additional specifier type. In its optional argument you can use H or F to denote header or footer fields. Thus, fancyfoot[LE] and fancyhf[FLE] are equivalent, though the latter is perhaps less readable, which is why we stick with the former forms. The fancyhf declaration is only an advantage if you want to clear all fields.

The next example shows an application of the lastpage package: in the footer we display the current and the total number of pages.

4-4-5
Image

Width and position of header and footer

The headers and footers are typeset in boxes that, by default, have the same width as extwidth. The boxes can be made wider (or narrower) with the help of the command fancyhfoffset.1 It takes an optional argument to denote which box (header or footer) should be modified, at which side (left or right), and on what kind of page (even or odd)—the specification employs a combination of the letters HFLREO for this purpose. The mandatory argument then specifies the amount of extension (or reduction). In the same fashion as seen for other commands there also exist two useful shorthand forms: fancyheadoffset and fancyfootoffset are like fancyhfoffset with H or F preset.

1 This feature was added in version 2.1. Earlier releases used a different method.

For example, to produce a running header that spans marginal notes, use the sum of marginparsep and marginparwidth in the mandatory argument of fancyheadoffset. With the calc package this can be specified elegantly with the declaration

Image

once these parameters have been assigned their correct values (this technique was, for example, used for the page styles used in this book).

In the next example the header is extended into the outer margin while the page number is centered within the bounds of the text column. This result proves that the header and footer settings are, indeed, independent.

Within the header and footer fields the total width is available in the register headwidth (recalculated for header and footer independently). It can be used to position objects in the fields. Below we redefine the headrule command to produce a decorative heading line consisting of two blue rules spanning the whole head width.

4-4-6
Image

The fancyhdr defaults

You may have guessed one or the other default used by fancyhdr from the previous examples. The next example will show all of them (for ease of reference they are repeated as comments in the example code). By default, we have a thin rule below the header and no rule above the footer, the page number is centered in the footer, and the header displays both leftmark and ightmark with the order depending on the page type.

4-4-7
Image

The separation between number and text in the running header is clearly too large but this is due to our extremely small measure in the example, so let us ignore this problem for the moment. How useful are these defaults otherwise? As we already mentioned, LaTeX’s leftmark and ightmark commands have been designed primarily with “sections within chapters” in mind—that is, for the case where the leftmark is associated with a heading that always starts on a new page. If this is not the case then you might end up with somewhat strange headers as exemplified below.

We put a section on page 5 (the page is not shown) that continues onto page 6. As a result we see the subsection 1.1 together with section 2 in the header of page 6, and a similar situation on page 7.

4-4-8
Image

To understand this behavior recall that leftmark refers to the last mark produced by markboth on that particular page, while ightmark refers to the first mark produced from either markright or markboth.

If you are likely to produce pages like the above, such as in a document containing many short subsections, then the fancyhdr defaults are probably not suitable for you. In that case overwrite them in one way or another, as we did in most of the examples in this section. The question you have to ask yourself is this: what information do I want to present to the reader in such a heading? If the answer is, for example, the situation at the top of the page for even (left-hand) pages and the status on the bottom for odd pages, then a possible solution is given through the use of firstleftmark and lastrightmark from the extramarks package.

4-4-9
Image

To test your understanding explain why page 7 now shows only the A-head and try to guess what headers you would get if the first B-head (but not all of its section text) had already been on page 5.

Despite the claim made earlier, there are two more defaults set by the fancy page style. Because they are somewhat hidden we have ignored them until now. We have not said how leftmark and ightmark receive their values; that they receive some data should be clear from the previous examples. As explained in Section 4.3.4 the sectioning commands pass their title argument to commands like sectionmark, which may or may not be set up to produce page marks via markboth or markright. The fancy page style now sets up two such commands: chaptermark and sectionmark if the current class defines a chapter command, or sectionmark and subsectionmark if it does not. Thus, if you want to provide a different marking mechanism or even if you just want to provide a somewhat different layout (for example, suppressing section numbers in the running header or not using MakeUppercase for the mark text), you may have to define these commands yourself.

The next example repeats Example 4-4-7 on the preceding page, except that this time we provide our own sectionmark and subsectionmark that shorten the separation between number and text and avoid using MakeUppercase.

4-4-10
Image

Defining “named” page styles

So far, all of our examples have customized the fancy page style over and over again. However, the fancyhdr package also allows you to save your customizations under a name that can then be selected through the pagestyle or hispagestyle command. This is done with a fancypagestyle declaration. It takes two arguments: the name of the page style and the customizations that should be applied when the page style is later called. Fields not set (or cleared) as well as the rule width settings are inherited from the fancyhdr defaults. This explains why we first use fancyhf to clear all fields.

4-4-11
Image

Some LaTeX commands, like chapter and maketitle, use hispagestyle to automatically switch to the plain page style, thereby overriding the page style currently in effect. To customize page styles for such pages you can either modify the definitions of these commands (which could be painful) or change the meaning of the plain page style by providing a new definition with fancypagestyle. This is, strictly speaking, not really the right approach—just assume that your new plain page style is now doing something fancy. But the fault really lies with LaTeX’s standard classes,1 which failed to use specially named page styles for these cases and instead directly referred to the most likely candidate. In practice, such a redefinition usually works very well for documents that need a fancy page style for most pages.

1 The KOMA-Script classes, for example, use commands like chapterpagestyle to refer to such special page styles, thus allowing easy customization.

Page styles depending on float objects

Sometimes it is desirable to modify the page style depending on the floating objects found on the current page. For this purpose fancyhdr provides a number of control commands. They can be applied in the page style declarations, thereby allowing the page style to react to the presence or absence of footnotes on the current page (iffootnote), floats in the top area (iftopfloat), or floats in the bottom area (ifbottomfloat). Each takes two arguments: the first to typeset when the condition is satisfied, the second to execute otherwise.

In the next example we omit the head rule if there are top floats by redefining headrulewidth. We also show the use of different heading texts on pages with or without top floats.

4-4-12
Image

Layout for float pages

A similar control, iffloatpage, is available to customize page styles for pages consisting only of floats—for example, to suppress running headers on such pages. If the page style is supposed to depend on several variables the controls can be nested, though that soon gets a little muddled. For example, to suppress head rules on all pages that contain either top or page floats, one would have to define headrulewidth as follows:

Image

Dictionary type headers

In dictionaries and similar works the running header often shows the first and the last word explained on a page to allow easy access to the dictionary data. By defining a suitable command that emits a mark for each dictionary item, such a scheme can be easily implemented. In the example below we use LaTeX’s right-mark to store such marks, retrieving them via firstrightmark and lastrightmark from the extramarks package. On pages devoted to only a single entry, we collapse the entry by testing whether both commands contain the same value via commands from the ifthen package. With a similar mechanism we prepared the running headers of the index for this book.

4-4-13
Image

Problems in two-column mode

Dictionaries are often typeset in two or more columns per page. Unfortunately, LaTeX’s standard twocolumn mode is defective with respect to marks—the leftmark always reflects the mark situation of the second column instead of containing the first mark from the first column. If this poses a problem use the reimplementation provided in the package fixltx2e. Alternatively, you can use the multicol package which also handles marks properly.

4.4.3. truncate—Truncate text to a given length

A potential problem when producing running headers or footers is the restricted space available: if the text is too long it will simply overprint. To help in this and similar situations you can deploy the package truncate written by Donald Arseneau. It provides a command to truncate a given text to a given width.

Image

If the argument text is too wide to fit the specified width, it will be truncated and a continuation marker placed at the end. If the optional marker argument is missing, a default marker stored in TruncateMarker is used (its value, as provided by the package, is ,dots).

By default, truncation is done at word boundaries and only if the words are not connected via an unbreakable space specified with a ~. For this reason the following example truncates the text after the word has. It also illustrates the use of a marker that requires an extra set of braces to hide the brackets that are supposed to appear as part of the text. To help you visualize the space occupied by the truncated text, | characters have been added to the left and right.

4-4-14
Image

Truncation within words can be achieved by specifying one of the options hyphenate, breakwords, or breakall to the package. The first two support truncation at hyphenation points, with the difference being that breakwords suppresses the hyphen character (the more common solution). The third option allows truncation anywhere within words. With these options the above example would have the following result:

Image

By default, the text (whether truncated or not) is printed flush left in a box of the specified width. Using the package option fit causes the printed text to have its natural width, up to a maximum of the specified width.

The next example combines the truncate package with fancyhdr. Notice the use of the fit option. Without it the header would always be flush left (the headwidth was slightly reduced to better show its effect).

4-4-15
Image

4.5. Visual formatting

The final stage of the production of an important document often needs some hand-formatting to avoid bad page breaks. For this purpose, standard LaTeX offers the pagebreak, opagebreak, ewpage, and clearpage commands as well as the samepage declaration, although the latter is considered obsolete in LaTeX2ε. A samepage declaration together with a suitable number of obreak commands lets you request that a certain portion of your document be kept together. Unfortunately, the results are often not satisfactory; in particular, LaTeX will never make a page larger than its nominal height ( extheight) but rather moves everything in the scope of the samepage declaration to the next page. The LaTeX2ε command enlargethispage* described below offers an alternative approach.

It is common in book production to “run” a certain number of pages (normally double spreads) short or long to avoid bad page breaks later on. This means that the nominal height of the pages is reduced or enlarged by a certain amount—for example, a aselineskip. To support this practice, LaTeX2ε offers the command enlargethispage{size}.

Image

If, for example, you want to enlarge or reduce the size of some pages by one (or more) additional lines of text, you could define

Image

and use those commands between two paragraphs on the pages in question.1 The enlargethispage command enlarges the extheight for the current page but otherwise does not change the formatting parameters. Thus, if flushbottom is in force, the text will fill the extheight for the page in question, if necessary by enlarging or shrinking vertical space within the page. In this way, the definitions add or remove exactly one line of text from a page while maintaining the positions of the other lines. This consideration is important to give a uniform appearance.

1 Because this book contains so many examples, we had to use this trick a few times to avoid half-empty pages. For example, in this chapter all pages from 222 onward are run short by one line. This was necessary because of the many (large) examples in Section 4.4.2—all other formattings we tried ended in a half-empty page somewhere.

Image

The companion command, enlargethispage*, also enlarges or reduces the page height, but this time the resulting final page will be squeezed as much as possible (i.e., depending on the available white space on the page). This technique can be helpful if you wish to keep a certain portion of your document together on one page, even if it makes the page slightly too long. (Otherwise, just use the minipage environment.) The trick is to request a large enough amount of extra space and then place an explicit page break where you want the page break to happen. For example:

Image

From the description above it is clear that both commands should be used only in the last stages of the production process, since any later alterations to the document (adding or removing a single word, if you are unlucky) can make your hand-formatting obsolete—resulting in ugly-looking pages.

To manually correct final page breaks, such as in a publication like this book (which poses some formidable challenges due to the many examples that cannot be broken across pages), it can be helpful to visualize TeX’s reasons for breaking at a certain point and to find out how much flexibility is available on certain pages. Tools for this purpose are described in Appendix B.3.2.

4.5.1. nextpage—Extensions to clearpage

In standard LaTeX the commands clearpage and cleardoublepage terminate the current paragraph and page after placing all dangling floats (if necessary, by producing a number of float pages). In two-sided printing cleardoublepage also makes sure that the next page is a right-hand (odd-numbered) one by adding, if necessary, an extra page with an empty text body. However, this extra page will still get a page header and footer (as specified by the currently active page style), which may not be desirable.

4-5-1
Image

The package nextpage by Peter Wilson extends this concept by providing the commands cleartoevenpage and cleartooddpage. Both commands accept an optional argument in which you can put text that should appear on the potentially generated page. In the next example we use this ability to provide a command myclearpage that writes BLANK PAGE on such generated pages.

4-5-2
Image

This code still results in a running header, but by now you surely know how to fix the example: just add a hispagestyle{empty} to the above definition.

The nextpage package also provides two commands, movetoevenpage and movetooddpage, that offer the same functionality, except that they do not output dangling floats.

4.6. Doing layout with class

Page layout is normally defined by the document class, so it should come as no great surprise that the techniques and packages described in this chapter are usually applied behind the scenes (within a document class).

The standard classes use the LaTeX parameters and interfaces directly to define the page proportions, running headers, and other elements. More recently developed classes, however, often deploy packages like geometry to handle certain aspects of the page layout.

In this section we introduce two such implementations. By searching through the CTAN archive you might discover additional treasures.

4.6.1. KOMA-Script—A drop-in replacement for article et al.

The KOMA-Script classes, developed by Markus Kohm and based on earlier work by Frank Neukam, are drop-in replacements for the standard article/report/book classes that emphasize rules of typography laid down by Tschichold. The article class, for example, becomes scrartcl.

Page layout in the KOMA-Script classes is implemented by deploying the typearea package (see Section 4.2.3), with the classes offering the package options as class options. Extended page style design is done with the package scrpage2 (offering features similar to those provided by fancyhdr). Like typearea this package can also be used on a stand-alone basis with one of the standard classes. Layout specifications such as font control, caption layout, and so on have been extended by providing customization possibilities that allow manipulation in the preamble of a document.

Besides offering all features available in the standard classes, the KOMA-Script classes provide extra user control inside front and back matter as well as a number of other useful extensions.

The distribution is well documented. There exists both a German and an English guide explaining all features in detail. The German documentation is also available as a nicely typeset book [100], published by DANTE, the German TeX Users Group.

4.6.2. memoir—Producing complex publications

The memoir class written by Peter Wilson was originally developed as an alternative to the standard book class. It incorporates many features otherwise found only as add-on packages. The current version also works as a replacement for article and can, therefore, be used for all types of publications, from small memos to complex books.

Among other features it supports an extended set of document sizes (from 9pt to 17pt), configurable sectional headings, page headers and footers, and captions. Predefined layout styles are available for all such objects and it is possible to declare new ones as needed. The class supports declarative commands for all aspects of setting the page, text, and margin sizes, including support for trimming (crop) marks. Many components of the class are also available as stand-alone packages, for those users who wish to add a certain functionality to other classes (e.g., epigraphs, caption formatting).

Like the KOMA-Script classes, the memoir class is accompanied by an excellent manual of nearly 200 pages, discussing all topics related to document design and showing how to resolve potential problems with memoir.

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

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