Appendix A. A LaTeX Overview for Preamble, Package, and Class Writers

This appendix gives an overview of the basic programming concepts underlying the LaTeX formatter. We explain how to define new commands and environments, including those with an optional argument. We discuss how LaTeX handles counters and their representation; we also introduce horizontal and vertical space parameters and explain how they are handled. The second section reviews the important subject of (La)TeX boxes and their use. A good understanding of this topic is very important to fully appreciate and exploit the information presented in this book. The third section is devoted to two package files, calc and ifthen, that make calculations and building control structures with LaTeX easier. They have been used in many examples of LaTeX code throughout this book. Finally, we describe in detail the LaTeX2ε interface that allows you to define your own options for packages and class files.

A.1. Linking markup and formatting

This section reviews the syntax for defining commands and environments with LaTeX. It is important that you exclusively use the LaTeX constructs described below, rather than the lower-level TeX commands. Then, not only will you be able to take advantage of LaTeX’s consistency checking, but your commands will also be portable, (probably) without modification, to future versions of LaTeX.

A.1.1. Command and environment names

Commands

In the current LaTeX incarnation, it is possible to enter accented characters and other non-ASCII symbols directly into the source, so it would seem reasonable to expect that such characters could also be used in command and environment names (e.g., größer). However, this is not the case—LaTeX multi-character command names must be built from basic ASCII letters (i.e., a... z and A... Z).1 This means that vspace* is actually not a command by itself; rather, it is the command vspace followed by the modifier *. Technically, you could write vspace* (as the space is ignored) or even put the * on the next line of your document.2

1 Strictly speaking this is not true, as TeX can be configured to support other configurations. There are, however, valid reasons why this is not being done for standard LaTeX. Some of these reasons are discussed in Section 7.11 describing LaTeX’s encoding model.

2 It is bad style to use this in your documents but there is unfortunately no way to prevent it.

Environments

On the other hand, names of environments are different. In this case the * is part of the name and spaces preceding it are not ignored. Thus, when writing egin{figure*}, the space would become part of the name and is not recognized as the start of a figure* environment. This is due to implementation details and seems to indicate that with environment names some additional ASCII characters work. For example:

Image

However, this is not true in general because, depending on additional packages being loaded, such environment names may no longer be recognized or may produce strange errors. Thus, it is best not to explore that implementation (mis)feature and instead to rely on officially supported names—those containing only lowercase and uppercase letters and the star character.

Citation and label keys

Strictly speaking, cite and label keys have the same kind of restriction. Nevertheless, it has become common practice to use keys containing colons (e.g., sec:cmds), so that most packages provide extra support to allow for at least the colon character in such keys. Characters outside the ASCII range and characters used in LaTeX’s syntax (e.g., _ or #) can never be used in names, whether they are keys, counters, environments, or multi-character command names.

With single-character command names, the situation is different again: any (single) character can be used. For example, $ is a perfectly valid LaTeX command, but foo$bar would be interpreted as the command foo followed by the start of a math formula (signaled by $) followed by the (math) characters b, a, and r. Any following text will also be typeset in math mode.

LaTeX commands (i.e., those constructs starting with a backslash) are classified into three basic categories: document-level commands, package and class writer commands, and internal “kernel” commands.

Document-level commands

Document-level commands, such as section, emph, and sum, usually have (reasonably) short names, all in lowercase.

Class and package writer commands

Class and package writer commands, by convention, have longer mixed-case names, such as InputIfFileExists and RequirePackage. Some of them can be usefully applied in the document source, but many will stop working after egin{document} has been processed.

Internal LaTeX commands

Most of the internal commands used in the LaTeX implementation, such as @tempcnta, @ifnextchar, and z@ contain @ in their name. This effectively prevents these names from being used in documents for user-defined commands. However, it also means that they cannot appear in a document, even in the preamble, without taking special precautions.

Image Careful with internal commands!

As a few of the examples in this book demonstrate, it is sometimes necessary to have such bits of “internal code” in the preamble. The commands makeatletter and makeatother make this easy to do; the difficult bit is to remember to add them, failure to do so can result in some strange errors. For an example of their use, see page 852. Note that package and class files should never contain these commands: makeatletter is not needed as this is always set up when reading such files; and the use of makeatother would prematurely stop this behavior, causing all kinds of havoc.

Unfortunately, for historical reasons the distinction between these categories is often blurred. For example, hbox is an internal command that should preferably be used only in the LaTeX kernel, whereas m@ne is the constant -1 and could have been MinusOne.

Nevertheless, this rule of thumb is still useful: if a command has @ in its name, then it is not part of the supported LaTeX language—and its behavior may change in future releases! Any such command should be used with great care. On the other hand, mixed-case commands or those described in the LaTeX Manual [104] are guaranteed to be supported in future releases of LaTeX2ε.

A.1.2. Defining new commands

It is often advantageous to define new commands (e.g., for representing repetitive input strings or recurring combinations of commands). A new command is defined using the ewcommand command sequence, which can have one optional argument, defining the number of arguments taken by the new command.

Image

The number of arguments is in the range 0 ≤ narg ≤ 9. If your new command has no arguments, then the [0] can be omitted. Inside the command definition part, the arguments are referenced as #1 to #narg.

A-1-1
Image

Omitting argument braces

The cmd argument always has to contain a single “token” (the name of the command to be defined), so one can omit the braces around this argument. While we do not recommend the use of this TeX syntax feature in other places, it is commonly used with ewcommand and similar declarations. In fact, we have often used this more concise syntax in this book:

Image

Note, however, that this is only possible with arguments that are single tokens to TeX (i.e., names starting with a backslash). Trying to do the same with, for instance, environment or counter names will fail. For example,

Image

is invalid LaTeX syntax.

If a command should work both in math mode and in text mode, special care should be taken in its definition. One could, for example, use mbox but this has a number of drawbacks.

A-1-2
Image

A better solution is offered by the LaTeX2ε command ensuremath. As the name implies, ensuremath ensures that its argument is always typeset in math mode by surrounding it, if necessary, with $ signs. Thus, the definition in the above example should be replaced as follows:

A-1-3
Image

This has the additional advantage of producing correctly sized symbols in subscripts or superscripts, which is not the case if an mbox is used in the definition.

Existing commands must be redefined with the command enewcommand, which otherwise has the same syntax as ewcommand. Note that you can redefine a command with a different number of arguments than the original one has. Therefore, you could redefine the xvec command of the above example, so that it now takes one argument:

A-1-4
Image

When redefining a command (or an environment—see below), you must, of course, be cautious. Commands that you are planning to redefine might be used in the class or packages you have loaded (try redefining uppercase in a document that is formatted with the class book).

Commands with one optional argument

In LaTeX, you can also define commands so that their first argument is optional. The syntax is

Image

An example of such a command definition is shown below:

Image

The default for the optional argument is given between the second pair of square brackets—the string “3” in this case. Inside the command definition, the optional argument has the number #1, while the mandatory arguments (when present) are addressed #2 to #narg. Thus, typing LB is a short way of saying linebreak[3], while LB[2] uses the actual specified value. That is, you will obtain the same effect as when typing linebreak[2].

In the next example we define the command lvec, which can be used inside or outside of formulas (due to ensuremath). Under the assumption that the upper subscript is usually n we made it optional, while the vector variable has to be given explicitly.

A-1-5
Image

In general, it is most practical to associate the case that occurs most often with the form of the command without parameters and to represent the cases that are used less often with longer command strings with an optional argument.

Argument restrictions

As explained above, user-defined commands can have one optional argument and up to nine arguments in total. If defined with ewcommand, each of the arguments can receive arbitrary text with a small number of restrictions:

• Braces must be properly balanced because otherwise LaTeX will be unable to determine where the argument ends.

• The verb command, the verbatim environment, and related commands or environments are not supported within arguments.

• In an optional argument a closing bracket “]” is allowed only if hidden inside braces (e.g., item[{a]}] is allowed). Without the braces the first ] would be misinterpreted as the end of the optional argument.

Deliberately restricting argument contents

The allowed content of arguments can be deliberately further restricted by using the ewcommand* variant of the declaration.

Image

The starred form works like ewcommand but defines a cmd that is not, in TeX terms, long. This means that the newly defined command does not accept empty lines or par commands in its argument(s). This restriction can be useful for commands whose arguments are not intended to contain whole paragraphs of text.

Image Relation to TeX primitives

Commands that have been defined with the low-level TeX primitive def do not accept par in their argument. Thus, they are equivalent to being defined with ewcommand*. The low-level TeX equivalent to ewcommand is longdef.

Nesting new commands in each other

Sometimes it is necessary to nest command definitions, most commonly in the combination of commands being defined as part of the definition of some new environment. If the inner command (or environment) has arguments there is a problem referring to them. Clearly we cannot use #1, #2, and so on, since this notation already denotes the argument(s) of the outer command or environment. The TeX solution is to double the hash marks; thus, ##1 would refer to the first argument of the inner definition and in case of three nested definitions we would need ####1.

To make this abstract concept a bit clearer, we define a command DEFlvec that (re)defines the lvec command from Example A-1-5 on the preceding page over and over again. As a first argument to DEFlvec we pass the vector name that is being hard-wired into the redefinition of lvec. As the second argument we pass the upper index that will become the default value for the optional argument of lvec. Thus, since the vector name is now part of the definition, lvec has only an optional argument.

A-1-6
Image

The technique used in the above example is worth studying. Try to visualize the actual definitions being carried out, for example, when the “initial definition” is executed. Also note the need for a top-level definition for lvec: the actual definition is irrelevant but without it we would be unable to “redefine” it inside DEFlvec command.

Special declarations for use in packages and classes

Beside ewcommand and enewcommand, which were originally provided as user commands (e.g., for the document preamble), LaTeX offers some extra methods of (re)defining commands that are intended for use in class and package files.

Image

This declaration works exactly like ewcommand and ewcommand*, except that it is ignored if the command to be defined already exists. Such a feature is useful in sources that may get used in several documents, such as bibliography entries. For example, instead of using ewcommand in the @preamble of BibTeX for logos and other constructs used in the BibTeX entries, you can use providecommand to avoid error messages if such commands are already defined in the document.

Image

This command takes the same arguments as ewcommand and ewcommand* but declares a robust command, even if some code within the command definition is fragile. You can use this command to define new robust commands, or to redefine existing commands and make them robust. Information is placed into the transcript file if cmd is redefined, so it does not produce an error in this case.

Image

This command takes the same arguments as ewcommand and ewcommand* but, rather than defining cmd, checks that the current definition of cmd is exactly as given by command definition. An error is raised if the definitions differ, or if one accepts par in its arguments and the other does not (i.e., was defined using a starred form). This command is useful for checking the state of the system before a package starts altering the definitions of commands. It allows you to check, in particular, that no other package has redefined the same command.

A.1.3. Defining new environments

You can define and redefine an environment with the ewenvironment and enewenvironment commands, respectively. You must specify, in each case, which actions should take place when you enter and leave an environment. For an environment called “myenv” this is signaled by the commands egin{myenv} and end{myenv} inside your document.

Image

As with the ewcommand declaration, the number of arguments is in the range 0 ≤ narg ≤ 9. In the case of no parameters, you can omit [0]. Inside the definition part, begdef, these parameters are referenced as #1 to #narg. If arguments are present, then they are defined when entering the environment by specifying them on the command egin{myenv}, as shown below:

Image

Image Arguments not available in end-tag

When exiting an environment with the command end{myenv} no parameters can be specified. Moreover, the parameters specified with the egin{myenv} command when entering the environment (see above) are no longer available in the definition part enddef, where you define the actions that should take place when leaving the myenv environment. This means that it is your responsibility to store information needed at the end of an environment (see the Citation environment defined below).

Technically, a ewenvironment declaration for the environment myenv defines a command myenv that is called during the egin{myenv} processing and a command endmyenv that is executed (besides other things) by end{myenv}. You may find that it is sometimes these commands rather than the environment tags that are used inside packages and classes to define related environments or commands. An example where this might be useful is given on page 468. In other situations, it is not advisable to follow this practice without a thorough understanding of LaTeX’s kernel implementation.

Our first example defines an environment of type “Abstract”, which is often used to give a short summary of the contents of an article or a book. It starts by typesetting a boldfaced and centered title, followed by the text of the abstract inside a quote environment. The final par command ensures that any following text starts a new paragraph.

A-1-7
Image

Our second example is somewhat more complex. It shows you how a Citation environment can be defined for quoting citations by famous people.

The LaTeX code shown below defines the counter Citctr, for numbering the citations, and a box Citname, for storing the name of the person whom we are citing so that we can typeset it at the end of the citation, when the end{Citation} command is encountered (remember that the value of the argument specified on the egin{Citation} command is no longer available at that stage). When entering the environment, we save the value of the argument, typeset in italic, in the box Citname and increment our counter. We then start a description environment. This environment will have a single item containing the counter value preceded by the word “Citation”. When exiting the Citation environment, we twice issue a stretchable horizontal space separated by an allowed—but discouraged—line break. It is important that this space survives if a line break happens before or after it, so hspace* is used. We also throw in a quad of space that ensures a proper separation between the citation and the name if they appear on the same line, but will vanish if a break is taken between them. Then we typeset the contents of the box Citname before leaving the description environment. This will put the author’s name flush right and the last line of the citation flush left, regardless of whether they end up on separate lines, as you can see in the next example. Without this adjustment the text of the citation would always be fully justified, often with a lot of white space between the words. For a discussion of the counter and box commands used in this example, see Sections A.1.4 and A.2.

A-1-8
Image

Surprisingly, the name in the last citation is typeset on a line of its own, even though there is clearly enough space to place it alongside with the citation. The reason is that TeX’s paragraph-breaking algorithm prefers solutions that do not have the second-to-last line ending in a hyphen and therefore selects a three-line paragraph breaking at the olinebreak.

Image A hyphen on the second-to-last line of a paragraph

There are two ways to correct this behavior. First, we can discourage breaking at this point by using an optional argument of [3] instead of [1], which would work in that particular example but may not work always. Second, we can tell TeX’s algorithm not to take that hyphen into account by setting the low-level TeX integer parameter finalhyphendemerits to zero. This requires a somewhat unusual syntax, as shown in the example code above (though commented out there to display the behavior without it).

As with ewcommand one can make the first argument of an environment optional:

Image

The default value for the optional argument is given between the second pair of square brackets. Inside the begdef part, which is executed when the environment name is entered, the optional argument can be accessed with #1. The mandatory arguments (when present) are addressed as #2 to #narg. When the name environment is used without an optional parameter, #1 will contain the string specified as default.

As an example, we reimplement the altDescription environment from Example 3-3-27 on page 149, this time with an optional argument instead of a mandatory argument specifying the width of the indentation. Another difference from the earlier definition is that the list labels will be placed flush right if possible (by placing hfil at the left in makelabel). When used without an optional argument the indentation will be 1em (i.e., a quad). By specifying the widest entry as an optional argument, you will make sure that the description parts of all your entries line up nicely.

The example first shows the (default) behavior of the altDescription list, then displays what it looks like when using the optional argument.

A-1-9
Image

A.1.4. Defining and changing counters

Every number internally generated by LaTeX has a counter (register) associated with it. The name of the counter is usually identical to the name of the environment or the command that generates the number except that it does not start with . The following is the list of all counters used in LaTeX’s standard document classes:

Image

An environment declared by ewtheorem can also have a counter with the same name associated with it, unless the optional argument indicates that it is to be numbered together with another environment.

The value of a counter is a single integer. Several counters can be combined into a number, as is usually the case for numbering section headings. For example, in the book or report classes, 7.4.5 identifies the fifth subsection of the fourth section in the seventh chapter.

Below we describe all the basic LaTeX commands that define counters and modify or display their values. These commands are much more powerful if used in conjunction with the calc package, which is discussed in Section A.3.1.

Image

This command globally defines a new counter, newctr, and initializes it to zero. If a counter with the name newctr is already defined, an error message is printed. When you specify the name of another counter as the optional argument, oldctr, then the newly defined newctr is reset when the counter oldctr is incremented with the stepcounter or efstepcounter command. It also defines the command henewctr to expand to arabic{newctr}.

Image

Image Warning: @removefromreset needs a package!

The operation that defines that one counter is reset whenever another counter is stepped is also available as the kernel command @addtoreset.1 Unfortunately, the opposite declaration is not available in the kernel, but only when loading the package remreset. If this small package is loaded, then counters can be unraveled if necessary. For example, the report class defines that the footnote counter is to be reset whenever a new chapter starts. If you want your footnotes nevertheless to be numbered sequentially throughout a document, then specifying

1 See also the umberwithin declaration provided by the amsmath package. It is discussed in Section 8.2.14 on page 485.

Image

in the preamble, or the equivalent code1 in a package or class, will do the job.

1 In that case use RequirePackage and omit makeatletter and makeatother!

Image

With setcounter the value of counter ctr is globally set equal to the value val. With addtocounter it is globally incremented by val.

Image

Both commands globally increment the counter ctr and reset all subsidiary counters—that is, those declared with the optional argument oldctr on the ewcounter command or with the first argument of @addtoreset. The efstepcounter command additionally defines the current ef value to be the text generated by the command hectr. Note that whereas stepping a counter is a global operation, setting the current ef value is done locally and thus is only valid inside the current group. As a result the next example does not produce the desired result but instead picks up the section number. The correct solution would be to move efstepcounter before the extbf command.

A-1-10
Image
Image

The value command produces the current value of a counter to be used in places where LaTeX expects to see a number, such as in the val argument of the command setcounter or addtocounter or when comparing numbers using the ifthenelse command from the ifthen package. However, the command cannot be used to typeset the value of the counter! For that purpose a set of presentation commands are available, all of which take a counter name as argument.

With arabic the counter value is represented as an Arabic numeral. With oman and Roman lowercase and uppercase Roman numerals are produced, respectively.

Image Counter presentations with restricted ranges

The remaining commands can be used only if the counter value is within a certain range. The alph command displays the value as a lowercase letter: a, b, c, ..., z. Thus, the value should lie in the range 1, ..., 26; otherwise, an error is signaled. The Alph command is similar but produces uppercase letters. Finally, fnsymbol represents the counter value as a traditional footnote symbol (e.g., *, ). In that case the value must not be greater than 9, unless an extension package, like footmisc, is used. The next example shows all of these commands in action.

A-1-11
Image
Image

A shorthand to produce the default visual representation for a counter ctr is provided by the command he ctr (e.g., hesection for the section counter). As mentioned earlier this command is initialized by the ewcounter declaration to produce arabic{ctr}. However, in LaTeX such a visual representation often involves more than a single number. For example, with sectioning counters one usually displays the value of the current section as well as the value of the current subsection, and so on. For this reason he ctr is typically (re)defined to produce a more complex representation. This practice becomes even more important when you consider that efstepcounter not only increments a certain counter and resets lower-level counters but also defines the “current” label (as picked up by label) to be the result of hectr for the counter being stepped.

As an example, inside the standard article class, we find definitions for sectioning counters equivalent to the following:

Image

You see how lower-level counters are reset when upper-level counters are stepped, as well as how the representation of the counters (the he... commands) are constructed from the current counter and the counters at a higher level. Note how the part counter does not influence any of the lower levels.

As another example, we look at Table 3.6 on page 130, which shows the structure of the enumeration list counters. In fact, these counters are defined inside the file LaTeX.ltx, which contains the kernel code for LaTeX. Only the representation, prefix, and label field commands are defined in the standard class files as follows:

Image

Finally, we show how the standard classes handle the equation counter. Like the enumeration counters, this counter is declared inside LaTeX.ltx. In the article class the counter is never reset:

Image

In the report and book classes the equation number is reset for each chapter with the @addtoreset command:

Image

Also, the representation differs in both cases.1

1 The actual definition is somewhat more complex, since some low-level code is used to suppress the chapter number if it is zero.

A.1.5. Defining and changing space parameters

In (La)TeX two kinds of space parameters (lengths) exist: “rigid” lengths (called <dimen> in The TeXbook [82]), which are fixed, and “rubber” lengths (called <skip> in The TeXbook), which have a natural length and a degree of positive and negative elasticity. New lengths in LaTeX are allocated as type <skip>, so that you always have the choice of initializing them as rigid or rubber lengths (by specifying plus and minus parts). On the other hand, all standard lengths in LaTeX are of type rigid, unless specifically declared in Appendix C of the LaTeX Manual to be rubber. Here we discuss the commands provided by LaTeX for dealing with lengths.

Image

The declaration ewlength allocates a new (rubber) length register and associates the command name cmd with it. If a command cmd already exists, you will get an error message. The new length is preset to zero. Just like with ewcommand you will find that the braces around cmd are often omitted in actual code since the argument must consist of a single command name.

Image

This sets the value of the length command cmd equal to the length length or, in case of addtolength, adds the specified amount to the existing value. In the examples below, the TeX command he is used to typeset the actual contents of the length variable. It requires the register command name without braces!

A-1-12
Image

Lengths can be specified in various units, as shown in Table A.1. Notice the difference between the typographic point (pt), which is normally used in TeX, and the (big) point used by PostScript, for example. Thus, when reserving space for an EPS picture you need to specify the bounding box dimension in bp to get the correct space.

Image

Table A.1. LaTeX’s units of length

Image

Instead of specifying a length value explicitly, three commands are available that allow you to measure a given text and assign the result. With settowidth the value of the length command cmd is set equal to the natural width of the typeset version of text. This command is very useful for defining lengths that vary with the string contents or the type size. The other two commands work similarly but measure the height and the depth rather than the width of the typeset text.

A-1-13
Image
Image

These two rubber lengths are intended to be used in the argument of vspace and similar commands. The fill rubber length is preset with a natural length of zero but can stretch to any positive value. Do not change its value! It is used in various places in the kernel and a change would produce strange effects.

An often more useful rubber length is provided by the stretch command—in fact, fill is equivalent to stretch{1}. More generally, stretch{dec-num} has a stretchability of dec-num times fill. It can be used to fine-tune the positioning of text horizontally or vertically—for instance, to provide spaces that have a certain relation to each other. Example A-1-15 demonstrates its application.

Horizontal space

Table A.2 shows horizontal space commands known to LaTeX. A flexible horizontal space of any desired width is produced by the hspace command. The command hspace* is the same as hspace, but the space is never removed—not even at a line boundary.

Image

Table A.2. Predefined horizontal spaces

A space in front of or following an hspace or hspace* command is significant, as the following example shows:

A-1-14
Image

The next example shows how rubber lengths can be used to fine-tune the positioning of information on a line. Note that the hfill command is, in fact, an abbreviation for hspace{fill}. To save typing, we also defined a command with an optional argument, HS, which behaves like hfill when used without an argument, but can be made less or more flexible than that command by specifying the stretchability (a value of 1 has the same effect as hfill).

A-1-15
Image
Vertical space

A vertical space is produced with the vspace command, which works similarly to hspace. In particular, a vspace* command will generate vertical space that will never be eliminated, even when it falls on a page break where a vspace command will be ignored at this point. Table A.3 shows vertical space commands known to LaTeX that are common to all standard classes.

Image

Table A.3. Predefined vertical spaces

LaTeX users are often confused about the behavior of the vspace command. When used inside a paragraph, the vertical space is added after the end of the line with vspace; between paragraphs it behaves as you would expect.

A-1-16
Image

Stretchable space as introduced on page 856 can also be used for vertical material. The vfill command is, in fact, an abbreviation for a blank line followed by vspace{fill}. More generally, you can use the stretch command in combination with vspace to control the layout of a complete page. This could be useful for designing a title page: if the title should be placed one third of the way down the page, one simply has to place vspace*{stretch{1}} before it and vspace*{stretch{2}} after it.

A-1-17
Image
Image

Image Use with care—if at all

While LaTeX’s user command vspace unconditionally adds a vertical space (which is removed only at page boundaries, while its starred form even suppresses this action), there exists another command for adding vertical space that is often used in the kernel and in some package files. The addvspace command has somewhat different semantics, and although it appears to be a user-level command judging from its name, in fact it is not.

In contrast to vspace the command addvspace is allowed only in vertical mode (i.e., between paragraphs). If used in horizontal mode, it issues the famous “Something's wrong–perhaps a missing item” error, which most LaTeX users know and love. Most of the time this error has nothing to do with a missing or misplaced item but simply signals a misplaced addvspace command. But it shows some of the history of this command: originally, it was developed and used solely for spacing items in list environments.

The other important semantic difference between vspace and addvspace is that the latter adds a space whose size depends on any directly preceding space. The precise rules are inherited from LaTeX 2.09 and show some strange discontinuities that nobody these days seems to be able to explain fully, though for backward compatibility the command is retained in this form. If s is the space to be added by addvspace and is the size of the vertical space (if any) before the current point, then the following rules apply:

Image

If we ignore for the moment the special cases in the first two lines of the rules, then the idea behind addvspace can be described as follows: if we have two vertically oriented constructs, such as a list and a heading, and both want to surround themselves with some vertical spacing before and after, it is probably not a good idea if both such spaces are applied if the objects directly follow each other. In that case using the maximum of both spaces is usually a better solution. This is why lists, headings, and other typeset elements use addvspace rather than vspace.

Image Surprising space size changes

This has some rather surprising effects. If you have two such display objects following each other, then only the maximum of the space surrounding them is used. But if you try to enlarge that space slightly, such as by placing vspace{4pt} between them, then suddenly the space will be far larger. This result occurs because in a sequence like

Image

the second addvspace will be unable to see the first and will add all of its space (with the result that the total space is 22pt); without the vspace in the middle you would get 10pt total. The vspace does not interact with the following addvspace because it actually generates a space of 4pt followed by a space of 0pt, so that the second rule applies.

If you notice that your space got too large and you reduce your correction to, say, vspace{2pt}, nothing will change substantially (you still get 20pt). Even more surprisingly, if you try to make the original space smaller by using, say, vspace{-3pt}, you will end up with 15pt total space—still more than before.

To actually get a space of 7pt in that place, you would need to back up by 11pt. Unfortunately, there is no way to determine the size of the necessary space other than by experimenting or looking into the definitions of the objects above and below, to find out what addvspace values are used at a given point.

The same problem arises if some other invisible object separates two consecutive addvspace commands. For example, a color-changing command or a label will effectively hide a previous addvspace, with the result that suddenly not the maximum, but the sum of both spaces, appears.

Image

Although addpenalty is not a spacing command it is described here because it is intended to work together with addvspace. A penalty is TeX’s way of assigning a “badness” to break points. A high penalty means that this is a bad place to break, while a negative penalty indicates to TeX that this is a rather good place to start a new line or a new page. Details of this mechanism can be found in Chapters 14 and 15 of [82].

The addpenalty command requires a TeX penalty value as an argument (useful values are between -10000 and 10000). For example, @startsection discussed in Chapter 2 uses addpenalty to make the space before a heading become a good place to break (default value -300). If addpenalty and addvspace are mixed, then this has two effects:

• LaTeX will still use the maximum of the spaces even if addpenalty appears between two addvspace commands.

• LaTeX moves the potential break “visually” to the beginning of the white space, even if there is an addvspace before the addpenalty.

The second feature is important to avoid white space remaining at the bottom of pages. See page 937 for a discussion of how this is achieved.

A.2. Page markup—Boxes and rules

The theory of composing pages out of boxes lies at the very heart of TeX, and several LaTeX constructs are available to take advantage of this method of composition. A box is a rectangular object with a height, depth, and width. Its contents can be arbitrarily complex, involving other boxes, characters, spaces, and so forth. Once built it is used by LaTeX as a single, fixed object that behaves much like a (potentially huge) character. A box cannot be split and broken across lines or pages. Boxes can be moved up, down, left, and right. LaTeX has three types of boxes:

LR (left–right) The contents of this box are typeset from left to right. Line breaking is impossible and commands like \ and ewline are ignored or produce error messages.

Par (paragraphs) This kind of box can contain several lines, which will be typeset in paragraph mode just like normal text. Paragraphs are put one on top of the other. Their widths are controlled by a user-specified value.

Rule This (thin or thick) line is often used to separate various logical elements on the output page, such as table rows and columns, and running titles and the main text.

LaTeX’s boxes all start a paragraph (just like characters) if used in vertical mode, while TeX’s primitive box commands (e.g., hbox) behave differently depending on where they are used. There are a number of reasons to avoid using the TeX primitives directly; see the discussion in Section A.2.5. The situation with rules is slightly different; we therefore will discuss TeX’s primitive rule commands below.

A.2.1. LR boxes

Image

The first line considers the text inside the curly braces as a box, without or with a frame drawn around it. For example, fbox{some words} gives Image. The two commands on the second line are a generalization of these commands. They allow the user to specify the width of the box and the positioning of the text inside.

A-2-1
Image

In addition to centering the text with the positional argument [c] (the default), you can position the text flush left ([l]) or flush right ([r]). There is also an [s] specifier that will stretch your text from the left margin to the right margin of the box provided it contains some stretchable space (e.g., some hspace or the predefined spaces given in Table A.2 on page 856). Interword spaces are also stretchable (and shrinkable to a certain extent), as explained on page 428. The appearance of frameboxes can be controlled by two style parameters:

fboxrule The width of the lines for the box produced with the command fbox or framebox. The default value in all standard classes is 0.4pt.

fboxsep The space left between the edge of the box and its contents by fbox or framebox. The default value in all standard classes is 3pt.

Any changes to these parameters obey the normal scoping rules and affect all frameboxes within the scope. The change to fboxsep in the next example, for instance, applies only to the second box.

A-2-2
Image

The box commands with arguments for specifying the dimensions of the box allow you to make use of four special length parameters: width, height, depth, and otalheight. They specify the natural size of the text, where otalheight is the sum of height and depth.

A-2-3
Image

Zero-width boxes are very handy if you want to put a marker on the page (e.g., for placement of figures) or to allow text to be put into the margins. The principle of operation is shown below, where a zero-width box is used to tag text, without influencing the centering. Note that the optional parameter [l] ([r]) makes the material stick out to the right (left).

A-2-4
Image

⇔ As seen in the margin of the current line, boxes with a vanishing width can be used to make text stick out into the margin. This effect was produced by beginning the current paragraph in the following way:

Image

An interesting possibility is to raise or lower boxes. This can be achieved by the very powerful aisebox command, which has two mandatory arguments and two optional arguments:

Image

To raise or lower the box produced from the contents, one specifies the amount of lift as a dimension, with negative values lowering the box. As with other boxes, one can make use of the special commands height, depth, otalheight, or even width to refer to the natural dimensions of the box produced from contents. This is used in the next example to raise the word “upward” so that the descender of the “p” aligns with the baseline and to lower the word “downward” so that it is placed completely below the baseline.

A-2-5
Image

Normally, LaTeX takes the added height and depth into account when calculating the distance between the lines, so that a raised or lowered box can result in spreading lines apart. This can be manipulated by specifying a height and a depth that the user wants LaTeX to actually use when placing its material on the page. The second pair of lines below shows that LaTeX does not realize that text has been moved upward and downward; thus, it composes the lines as though all the text was on the baseline.

A-2-6
Image

A somewhat more useful application is discussed in Section 5.7 on page 272, which addresses the subject of columns spanning multiple rows in tabular material.

A.2.2. Paragraph boxes

Paragraph boxes are constructed using the parbox command or minipage environment. The text material is typeset in paragraph mode inside a box of width width. The vertical positioning of the box with respect to the text baseline is controlled by the one-letter optional parameter pos ([c], [t], or [b]).

Image

The center position is the default, as shown in the next example. Note that LaTeX might produce wide interword spaces if justification is requested (default) and the measure is incredibly small.

A-2-7
Image

The minipage environment is very useful for the placement of material on the page. In effect, it is a complete miniversion of a page and can contain its own footnotes, paragraphs, and array, tabular, multicols, and other environments. Note, however, that it cannot contain floats or marginpar commands, but it can appear inside figure or table environments, where it is often used for constructing a pleasing layout of the material inside the float. A simple example of a minipage environment at work is given below. The baseline is shown with an en dash generated by the command HR. Note the use of the pos placement parameter ([c], [t], or [b]) on the three minipage environments.

A-2-8
Image

If you desire more complicated alignments, then you might have to stack the different minipage environments. Compare the behavior of the next examples. Below, we try to align the two leftmost blocks at their top and align the resulting block at the bottom with a third block by adding another level of minipages.

A-2-9
Image

However, we do not get the expected result. Instead, the two top-aligned minipages inside the bottom-aligned minipage form a paragraph with a single line (the minipages are considered to be large units in the line containing xx). Thus, the bottom line of the outer minipage is still the one containing the xx characters. To prevent this we need to add some invisible space after the paragraph, as shown next.

A-2-10
Image

In the case below, the two rightmost environments are aligned at their top inside another enclosing environment, which is aligned at its bottom with the first one. If you compare it with the previous example, then you see that you obtain a quite different result, although the sequence of alignment parameters is the same. Only the stacking order of the minipage environments is different.

A-2-11
Image

Again, we had to add some vertical space to achieve alignment. This does not, however, always produce the desired result. If, for instance, a letter with a descender appears in the last line of the stacked minipage, as in the example below, then the alignment of the baselines is not perfect.

A-2-12
Image

To correct this problem, you have to add (negative) vertical space that compensates for the depth of the letters.

Perhaps the easiest way (albeit the most dangerous) is to use the TeX primitive prevdepth. This dimension register can be used only in vertical mode (i.e., after a paragraph has ended), and contains the depth of the previous line. In the next example this primitive is used to back up by this amount, thereby pretending that the bottom of the box is located at the baseline of the last line.

Image Surprising effects of prevdepth

When using prevdepth in this way one has to be careful. As already mentioned, it gives an error if used outside vertical mode. Furthermore, TeX overloads this primitive by setting it to -1000pt at the beginning of a vertical box and after a horizontal rule.1 Thus, using vspace* instead of vspace in the example would give a nasty surprise, because vspace* actually puts in an invisible rule to ensure that the space will survive at a page break. As a result the value of prevdepth inside would be -1000pt and we would effectively be adding a space of 1000 points at the bottom of the box.

1 TeX uses prevdepth to calculate the interline space needed and -1000pt indicates that this space should be suppressed.

A-2-13
Image

Sometimes it is helpful to predefine the vertical dimension of a paragraph box. For this purpose today’s LaTeX offers additional optional arguments for parbox and the minipage environment.

Image

The inner-pos argument determines the position of the text within the box. It can be t, c, b, or s. If not specified, the value of pos will be used. You can think of height and inner-pos as the vertical equivalent of the width and pos arguments of a makebox. If you use the s position, the text will be vertically stretched to fill the given height. Thus, in this case you are responsible for providing vertically stretchable space if necessary, using, for example, the vspace command.

As with the other box commands you can use height, otalheight, and so on to refer to the natural dimensions of the box when specifying the optional argument.

A-2-14
Image

A.2.3. Rule boxes

LaTeX’s rule boxes are drawn with the ule command:

Image

If we write ule[4pt]{2cm}{1mm} then we get a 2cm long rule that is 1mm thick and raised 4pt above the baseline: Image. The ule command can also be used to construct rule boxes with zero width, that is invisible rules (also called struts). These struts are useful if you need to control the height or width of a given box (for example, to increase the height of a box framed with fbox or framebox, or to adjust locally the distance between rows in a table). Compare the following:

A-2-15
Image

As mentioned earlier, LaTeX makes boxes (including rules) behave like characters. For example, if used outside a paragraph they automatically start a new paragraph. With rules this is not always the desired behavior. To get a rule between two paragraphs, for instance, we have to use oindent to suppress a paragraph indentation; otherwise, the line would be indented and stick out to the right.

A-2-16
Image

Due to this behavior the rule sits on the baseline of a one-line paragraph and is therefore visually much closer to the following paragraph. To place it at equal distance between the two lines, one could use the optional lift argument, but determining the right value (roughly 2.5pt in this particular case) remains a matter of trial and error.

One solution is to suppress the generation of interline space, using the low-level TeX command ointerlineskip, and to add the necessary spaces explicitly as shown in the next example. This time we omit oindent so that the rule is indented by parindent, and we use calc to calculate the rule width such that it leaves a space of size parindent on the right as well.

A-2-17
Image

The sum of the vertical spaces used plus the height of the rule amounts to 12 points (i.e., aselineskip). However, this does not make the baselines of the two paragraphs 12 points apart; rather, it makes the distance from the bottom of the last line in the first paragraph (i.e., as produced by the “g” in “again”) to the top of the first line in the next paragraph (i.e., as produced by the “A”) be 12 points. Thus, if the text baselines should preferably fall onto a grid, a variant of Example A-2-16 using the optional lift argument is more appropriate.

Instead of using ule together with ointerlineskip, package or class writers often use the primitive TeX rule commands. They have the advantage of automatically suppressing interline space and do not require you to specify all dimensions. On the downside, they have an unusual syntax and cannot be used if the rule needs horizontal or vertical shifting, as in the previous example.

Image

The hrule primitive can only be used between paragraphs, while the vrule primitive has to appear within paragraphs. If encountered in the wrong place, the commands stop or start a paragraph as necessary. The commands can be followed by one or more of the keywords height, depth, and width together with a dimension value. Any order is allowed, and missing keywords get the defaults shown in Table A.4. An asterisk in that table means that the rule will extend to the boundary of the outer box. The elax command at the end is not required but ensures that TeX knows that the rule specification has ended and will not misinterpret words in the text as keywords.

Image

Table A.4. Default values for TeX’s rule primitives

In the next example we use the default value for hrule, resulting in a rule of 0.4pt height running through the whole galley width (since this is effectively the next outer box).

A-2-18
Image

A.2.4. Manipulating boxed material

Material can be typeset once and then stored inside a named box, whose contents can later be retrieved.

Image

The command ewsavebox globally declares a command cmd (for example, mybox), which can be thought of as a named bin. Typeset material can be stored there for later (multiple) retrieval.

The sbox and savebox commands are similar to mbox and makebox, except that they save the constructed box in the named bin (previously allocated with ewsavebox) instead of directly typesetting it. The usebox command then allows the nondestructive use of the material stored inside such named bins. You can reuse the same bin (e.g., mybox) several times within the scope of the current environment or brace group. It will always contain what was last stored in it.

Be careful not to use the command name mybox directly, since it contains only the TeX number of the box in question. As a consequence, mybox on its own will merely typeset the character at the position corresponding to the box number in the current font. Thus, you should manipulate boxes exclusively using the commands described above.

A-2-19
Image

In addition to the above commands, there exists the lrbox environment with the following syntax:

Image

Here cmd should be a box register previously allocated with ewsavebox. The environment lrbox will save the text in this box for later use with usebox. Leading and trailing spaces are ignored. Thus, lrbox is basically the environment form of sbox. You can make good use of this environment if you want to save the body of some environment in a box for further processing. For example, the following code defines the environment fcolumn, which works like a column-wide minipage but surrounds its body with a frame.

A-2-20
Image

The above definition is interesting in several respects. The environment is defined with one optional argument denoting the width of the resulting box (default linewidth). On the next line we calculate (using the calc package) the internal line length that we have to pass to the minipage environment. Here we have to subtract the extra space added by the fbox command on both sides. Then the lrbox and minipage environments are started to typeset the body of the fcolumn environment into the box fcolbox. When the end of the environment is reached those environments are closed. Then the fcolbox is typeset inside an fbox command. The oindent in front suppresses any indentation in case the environment is used at the beginning of a paragraph or forms a paragraph by itself.

The boxedminipage described in Section 10.1.1 on page 595 can be implemented in a similar fashion. The only essential difference from the previous code is that we omit oindent and pass the width as a mandatory argument and the position as an optional argument.

A-2-21
Image

If you compare this definition with the actual code in the package (which originates in LaTeX 2.09), it will be apparent that the coding features offered with the current version of LaTeX have their advantages.

A.2.5. Box commands and color

Even if you do not intend to use color in your own documents, by taking note of the points in this section you can ensure that your class or package is compatible with the color package. This may benefit people who choose to use your class or package together with the color package extensions.

The simplest way to ensure “color safety” is to always use LaTeX box commands rather than TeX primitives—that is, to use sbox rather than setbox, mbox rather than hbox, and parbox or the minipage environment rather than vbox. The LaTeX box commands have new options that make them as powerful as the TeX primitives.

As an example of what can go wrong, consider that in { tfamily text} the font is restored just before the }, whereas in the similar-looking construct {color{green} text} the color is restored just after the final }. Normally, this distinction does not matter. But consider a primitive TeX box assignment such as

Image

Now the color-restore operation occurs after the } and so is not stored in the box. Exactly which bad effects this introduces will depend on how color is implemented: the problems can range from getting the wrong colors in the rest of the document to causing errors in the dvi driver used to print the document.

Also of interest is the command ormalcolor. This is normally just elax (i.e., does nothing), but you can use it like ormalfont to set regions of the page, such as captions or section headings, to the “main document color”.

A.3. Control structure extensions

A.3.1. calc—Arithmetic calculations

The package calc (by Kresten Thorup and Frank Jensen) contains a set of macros for enhanced arithmetic in LaTeX. Usual arithmetic in TeX is done by simple low-level operations like advance and multiply. This package defines an infix notation arithmetic for LaTeX. In fact, it reimplements the LaTeX commands setcounter, addtocounter, setlength, and addtolength so that they can accept integer and length expressions rather than simple numbers and lengths.

An integer expression can contain integer numbers, TeX’s integer registers, LaTeX’s counters (e.g., value{ctr}), parentheses, and binary operators (-, +, *, /). For instance, to advance a counter by five:

A-3-1
Image

An example is the definition of a command to print the time (note that the TeX register ime contains the number of minutes since midnight):

A-3-2
Image

When dealing with lengths, the subexpressions that are added or subtracted must be of the same type. That is, you cannot have “2cm+4”, but an expression like “2cm+4pt” is legal because both subexpressions have dimensions. You can only divide or multiply by integers, so “2cm*4” is a legal subexpression but “2cm*4pt” is forbidden. Also, the length part must come first in an expression; thus, “4*2cm” is not allowed.

The commands described above allow you to calculate the width of one column in an n-column layout using the following single command (supposing that the variable n is stored as the first argument of a LaTeX macro):

Image

The restriction that you can only multiply and divide by integers has been relaxed for calculations on lengths (dimensions). Those operations are allowed with real numbers.

Image

A real number can be represented in two forms: the first command converts the decimal constant into a form that can be used in a calc formula. The second form denotes the real number obtained by dividing the value of the first expression by the value of the second expression.

As an example, assume you want to scale a figure so that it occupies the full width of the page ( extwidth). If the original dimensions of the figure are given by the length variables Xsize and Ysize, then the height of the figure after scaling will be:

Image

The calc package is used in many examples in this book. If you do not want to apply it, you need to express the code given in the examples in the form of primitive (La)TeX constructs. For example, the setting of fcolwidth on page 869 has to be translated from

Image

to the following statements:

Image

Besides the fact that the infix notation provided by the calc package is certainly more readable (and much easier to modify), it contains constructs for division and multiplication that cannot be expressed with standard LaTeX constructs. For example, to express the opmargin calculation from page 198, the following code is necessary:

Image

A.3.2. ifthen—Advanced control structures

Sometimes you may want to typeset different material depending on the value of a logical expression. This is possible with the standard package ifthen (written by Leslie Lamport, and reimplemented for the current LaTeX version by David Carlisle), which defines commands for building control structures with LaTeX.

Image

If the condition test is true, the commands in the then-code part are executed. Otherwise, the commands in the else-code part are executed.

A simple form of a condition is the comparison of two integers. For example, if you want to translate a counter value into English:

A-3-3
Image

The following example defines a command to print the time in short form. It shows how complex operations (using the calc package) can be combined with conditional control statements.

A-3-4
Image
Image

The equal command evaluates to true if the two strings string1 and string2 are equal after they have been completely expanded. You should be careful when using fragile commands in one of the strings; they need protection with the protect command.

A-3-5
Image

One application for the preceding command could be in the definition of a command for printing an item and for entering it in the index. In the case where it is defined, the index entry will be typeset in boldface; otherwise, it will appear in a normal face. We use an optional argument for the least frequently occurring situation of the definition.

A-3-6
Image

This gives the required visual representation in the .idx file by specifying entries of the following type:

Image

A more complicated example, where you have complete control of what goes or does not go into the index or in the text, involves the extended index command IXE, defined in the following example. Its default optional argument “!*!,!” contains a string that you will probably never want to use in the text (we hope). If you use the command IXE with only one (normal) argument, then you will enter the same information into the index and the text. By specifying an optional argument, you can enter something in the index that is different from what is printed in the text. All possible combinations are shown below. The vertical bars around the commands show that no unwanted spaces are generated.

A-3-7
Image

The .idx file contains only three entries, since the case with the empty optional argument “[]” does not generate an index entry:

Image

Basic TeX knows about some switches that can have the value true or false.1 To define your own switch, use ewboolean where string is a sequence of letters. This switch is initially set to false. To change its value, use setboolean where the value argument is either the string true or false. You can then test the value by using oolean in the first argument of ifthenelse. It is also possible to test all such internal flags of LaTeX with this command (the most common ones are shown in Table A.5). An example could be a test to see whether a document is using a one- or two-sided layout.

1 In the LaTeX kernel they are normally built using the more primitive ewif command.

Image

Table A.5. LaTeX’s internal oolean switches

A-3-8
Image
Image

To compare dimensions, use lengthtest. In its test argument you can compare two dimensions (either explicit values like 20cm or names defined by ewlength) using one of the operators <, =, or >.

As an example, let us consider a figure characterized by its dimensions Xsize and Ysize. It should be made to fit into a rectangular area with dimensions Xarea and Yarea, but without changing the aspect ratio of the figure. The following code calculates the new dimensions of the figure ( ewX and ewY). The trick is to first calculate and compare the aspect ratios of both the rectangle and the figure, and then to use the result to obtain the magnification factor.

Image
Image

With the isodd command you can test whether a given number is odd. If, for example, the string generated by a pageref command is a valid number (as it normally is), then you can use the command in the following way:

A-3-9
Image

The isodd command is specially tailored to support the above application even though the result of pageref might be undefined in the first LaTeX run. Note that you cannot omit the label and pageref and instead simply use hepage. The reason is that pages are built asynchronously. As a consequence, your code might get evaluated while a page is being built, and later on LaTeX’s output routine might decide to move that bit of the text to the next page, making the evaluation invalid if hepage were used.

Image

The whiledo command is valuable for executing certain repetitive command sequences. The following simple example shows how the command works:

A-3-10
Image
Image

Multiple conditions can be combined into logical expressions via the logical operators (or, and, and ot), using the commands ( and ) as parentheses. A simple example is seen below.

A-3-11
Image

A.4. Package and class file structure

In this section we discuss what commands are available for the authors of package or class files. Even if you do not intend to write your own package, this section will help you understand the structure and content of class and package files like book or varioref, and thus help you to make better use of them.

The general structure of class and package files is identical and consists of the following parts:

Image

All these parts are optional. We discuss the commands available in each of the individual parts below. Table A.6 on page 879 gives a short overview.

Image
Image

Table A.6. Commands for package and class files

A.4.1. The identification part

This part of a class or package file is used to define the nature of the file and may also state the LaTeX2ε distribution release minimally required.

Image

A class file identifies itself with a ProvidesClass command. The argument name corresponds to the name of the class as it will be used in the mandatory argument of the documentclass command (i.e., the file name without an extension). The optional argument release information, if present, should begin with a date in the form YYYY/MM/DD, separated with a space from the version number or identification, followed optionally by some text describing the class. For example, the class report contains something like

Image

In a document you can make use of the release information by specifying the date as a second optional argument to the documentclass command as follows:

Image

This enables LaTeX to check that the report class used has at least a release date of 2001/04/21 or is newer. If the class file is older, a warning is issued. Thus, if you make use of a new release of a class file and send your document to another site, the people there will be informed if their LaTeX distribution is out of date.

Image

This command identifies a package file. The structure is the same as for the ProvidesClass command. Again, the date in the release information can be used in a second optional argument to usepackage to ensure that an up-to-date version of the package file is loaded. For example:

Image
Image

This command identifies any other type of file. For this reason filename must contain the full file name including the extension.

Image

In addition to one of the above commands, the identification part usually contains a NeedsTeXFormat declaration. The format must be the string LaTeX2e. If the optional release argument is specified, it should contain the release date of the required LaTeX2ε distribution in the form YYYY/MM/DD. For example,

Image

would require at least the LaTeX2ε release distributed on June 1, 2001. If this command is present, anyone who tries to use your code together with an older LaTeX release will receive a warning message that something might fail. A newer release date is accepted without a warning.

All four declarations are optional. Nevertheless, their use in distributed class and package files will ease the maintenance of these files.

A.4.2. The initial code part

You can specify any valid LaTeX code in the initial code part, including code that loads packages with the RequirePackage command (see Section A.4.5) if their code is required in one of the option declarations. For example, you might want to load the calc package at this point, if you plan to use it later. However, normally this part is empty.

A.4.3. The declaration of options

In this part all options known to the package or class are declared using the DeclareOption command. It is forbidden to load packages in this part.

Image

The argument option is the name of the option being declared and code is the code that will execute if this option is requested. For example, the paper size option a4paper normally has a definition of the following form:

Image

In principle, any action—from setting a flag to complex programming instructions—is possible in the code argument of DeclareOption.

An important function for use in DeclareOption is the command PassOptionsToPackage. It can pass one or more options to some other package that is loaded later.

Image

The argument option-list is a comma-separated list of options that should be passed to the package with name package-name when it is loaded in the package loading part.1 Suppose, for example, that you want to define a class file that makes use of two packages, say, A and B, both supporting the option infoshow. To support such an option in the class file as well, you could declare

1 It is the responsibility of the package writer to actually load such packages. LaTeX does not check that packages receiving options via PassOptionsToPackage are actually loaded later on.

Image

If a package or class file is loaded with an option that it does not recognize, it will issue a warning (in case of a package file) or silently ignore the option (in case of a class file), assuming that it is a global option to be passed to other packages subsequently loaded with usepackage. However, this behavior is not hard-wired and can be modified using a DeclareOption* declaration.

Image

Image Command does not act on global options!

The argument code specifies the action to take if an unknown option is specified on the usepackage or RequirePackage command. Within this argument CurrentOption refers to the name of the option in question. For example, to write a package that extends the functionality of some other package, you could use the following declaration:

Image

This would pass all options not declared by your package to package A. If no DeclareOption* declaration is given, the default action, described above, will be used.

By combining DeclareOption* with InputIfFileExists (see below), you can even implement conditional option handling. For example, the following code tries to find files whose names are built up from the option name:

Image

If the file g-option.xyz can be found, it will be loaded; otherwise, the option is ignored with a warning.

A.4.4. The execution of options

Two types of actions are normally carried out after all options are declared. You might want to set some defaults, such as the default paper size. Then the list of options specified needs to be examined and the code for each such option needs to be executed.

Image

The ExecuteOptions command executes the code for every option listed in option-list in the order specified. It is just a convenient shorthand to set up defaults by executing code specified earlier with a DeclareOption command. For example, the standard class book issues something similar to

Image

to set up the defaults. You can also use ExecuteOptions when declaring other options, such as a definition of an option that automatically implies others. The ExecuteOptions command can be used only prior to executing the ProcessOptions command because, as one of its last actions, the latter command reclaims all of the memory taken up by the code for the declared options.

Image

When the ProcessOptions command is encountered, it examines the list of options specified for this class or package and executes the corresponding code. More precisely, when dealing with a package the global options (as specified on the documentclass command) and the directly specified options (the optional argument to the usepackage or RequirePackage command) are tested. For every option declared by the package, the corresponding code is executed. This execution occurs in the same order in which the options were specified by the DeclareOption declarations in the package, not in the order in which they appear on the usepackage command. Global options that are not recognized are ignored. For all other unrecognized options the code specified by DeclareOption* is executed or, if this declaration is missing, an error is issued.

Thus, packages that use only DeclareOption* when declaring options will not act upon global options specified on the documentclass, but rather will accept only those that are explicitly given on the usepackage or RequirePackage declaration.

In the case of a class file, the action of ProcessOptions is the same without the added complexity of the global options.

Preventing unwanted expansion

There is one potential problem when using ProcessOptions: the command searches for a following star (even on subsequent lines) and thereby may incorrectly expand upcoming commands following it. To avoid this danger use elax at the end to stop the search immediately and start the execution of the options.

Image

For some packages it may be more appropriate if they process their options in the order specified on the usepackage command rather than using the order given through the sequence of DeclareOption commands. For example, in the babel package, the last language option specified is supposed to determine the main document language. Such a package can execute the options in the order specified by using ProcessOptions* instead of ProcessOptions.

A.4.5. The package loading part

Once the options are dealt with, it might be time to load one or more additional packages—for example, those to which you have passed options using PassOptionsToPackage.

Image

This command is the package/class counterpart to the document command usepackage. If package was not loaded before, it will be loaded now with the options specified in option-list, the global options from the documentclass command, and all options passed to this package via PassOptionsToPackage.

LaTeX loads a package only once because in many cases it is dangerous to execute the code of a package several times. Thus, if you require a package with a certain set of options, but this package was previously loaded with a different set not including all options requested at this time, then the user of your package has a problem. In this situation LaTeX issues an error message informing users of your package about the conflict and suggesting that they load the package with a usepackage command and all necessary options.

The optional release argument can be used to request a package version not older than a certain date. For this scheme to work, the required package must contain a ProvidesPackage declaration specifying a release date.

Image

This command works like RequirePackage except that the options passed to it are exactly those specified for the calling package or class. This facilitates the generation of variant packages that take exactly the same set of options as the original. See also the discussion of LoadClassWithOptions on page 887.

A.4.6. The main code part

This final part of the file defines the characteristics and implements the functions provided by the given class or package. It can contain any valid LaTeX construct and usually defines new commands and structures. It is good style to use standard LaTeX commands, as described in this appendix, such as ewlength, ewcommand, CheckCommand, and so on, rather than relying on primitive TeX commands, as the latter do not test for possible conflicts with other packages.

A.4.7. Special commands for package and class files

Image

Sometimes it is necessary to defer the execution of some code to the end of the current package or class file. The above declarations save the code argument and execute it when the end of the package or class is reached. If more than one such declaration is present in a file, the code is accumulated and finally executed in the order in which the declarations were given.

Image

Other important points at which you might want to execute deferred code are the beginning and the end of the document or, more exactly, the points where the egin{document} and end{document} are processed. The above commands allow packages to add code to this environment without creating any conflicts with other packages trying to do the same.

Note, however, that code in the AtBeginDocument hook is part of the preamble. Thus, restrictions limit what can be put there; in particular, no typesetting can be done.

Image

If your package or class tries to input a file that does not exist, the user ends up in TeX’s file-error loop. It can be exited only by supplying a valid file name. Your package or class can avoid this problem by using IfFileExists. The argument file is the file whose existence you want to check. If this file is found by LaTeX, the commands in then-code are executed; otherwise, those in else-code are executed. The command InputIfFileExists not only tests whether file exists, but also inputs it immediately after executing then-code. The name file is then added to the list of files to be displayed by listfiles.

Image

When a package detects a problem it can alert the user by printing a warning message on the terminal. For example, when the multicol package detects that multicols* (which normally generates unbalanced columns) is used inside a box, it issues the following warning:1

1 In a box, balancing is essential since a box can grow arbitrarily in vertical direction, so all material would otherwise end up in the first column.

Image

This will produce a warning message, which is explicitly broken into two lines via the MessageBreak command:

Image

The current line number is automatically appended. Sometimes it would be nice to display the current file name as well, but unfortunately this information is not available on the macro level.

Depending on the nature of the problem, it might be important to tell the user the source line on which the problem was encountered. In other cases this information is irrelevant, such as when the problem happens while the package is being loaded. In this situation PackageWarningNoLine should be used; it produces the same result as PackageWarning but omits the phrase “on input line num”.

If the information is of lower importance and should appear just in the transcript file, then one can use PackageInfo. For example, after loading the shortvrb package and issuing the declaration MakeShortVerb=, the transcript file will show the following:

Image

A PackageInfoNoLine command is not provided. If you really want to suppress the line number in an informational message, use @gobble as the last token in the second argument of PackageInfo.

Image

If the problem detected is severe enough to require user intervention, one can signal an error instead of a warning. If the error is encountered, the short-text is displayed immediately and processing stops. For example, if inputenc encounters an 8-bit character it does not recognize, it will produce the following error:

Image

If the user then presses “h” or “H”, the long-text is offered. In this case it is:

Image

As before, you can explicitly determine the line breaks in the error and help texts by using MessageBreak.

Image

Information, warning, and error commands are not only available for packages—similar commands are provided for document classes. They differ only in the produced texts: the latter commands print “Class” instead of “Package” in the appropriate places.

A.4.8. Special commands for class files

It is sometimes helpful to build a class file as a customization of a given general class. To support this concept two commands are provided.

Image

The LoadClass command works like the RequirePackage command with the following three exceptions:

• The command can be used only in class files.

• There can be at most one LoadClass command per class.

• The global options are not seen by the class unless explicitly passed to it via PassOptionsToClass or specified in the option-list.

Image

The command PassOptionsToClass can be used to pass options to such a general class. An example of such a class file augmentation is shown in Figure A.1. It defines a class file myart that accepts two extra options, cropmarks (making crop marks for trimming the pages) and bind (shifting the printed pages slightly to the outside to get a larger binding margin), as well as one additional environment, Notes.

Image

Figure A.1. An example of a class file extending article

The cropmarks option is implemented by setting a Boolean switch and redefining various pagestyles if this switch is true. The bind option modifies the values of oddsidemargin and evensidemargin. These length registers do not have their final values at the time the bind option is encountered (they are set later, when the article class is loaded by LoadClass), so the modification is deferred until the end of the myart class file using the AtEndOfClass command.

Image

If your code for DeclareOption* inside a class file is more complex (e.g., trying to handle some options but rejecting others), you might need to explicitly inform LaTeX that the option was not accepted with the help of the OptionNotUsed command. Otherwise, LaTeX will think that the option was used and will not produce a warning if the option is not picked up by a later package.

Image

This command is similar to LoadClass, but it always calls the class with exactly the same option list that is being used by the current class, rather than the options explicitly supplied or passed on by PassOptionsToClass. It is mainly intended to allow one class to build on another. For example:

Image

This should be contrasted with the following slightly different construction:

Image

As used here, the effects are more or less the same, but the version using LoadClassWithOptions is slightly quicker (and less onerous to type). If, however, the class declares options of its own, then the two constructions are different. Compare, for example,

Image

with:

Image

In the first example, the article class will be called with the option landscape only when the current class is called with this option. In the second example, however, the option landscape will never be passed to the article class, because the default option handler only passes options that are not explicitly declared.

Image

Sometimes it is useful to be able to find out if a package was already loaded, and if so, how. For this purpose, three commands are made available to class (and package) writers. To find out if a package has already been loaded, use @ifpackageloaded. If it was loaded, the true-code is executed; otherwise, the false-code is executed. To find out if a package has been loaded with a version more recent than date, use @ifpackagelater. Finally, to find out if a package has been loaded with at least the options in the (comma-separated) list options, use @ifpackagewith.

The fontenc package cannot be tested with the above commands. That’s because it pretends that it was never loaded to allow for repeated reloading with different options (see the file ltoutenc.dtx in the LaTeX distribution for details).

A.4.9. A minimal class file

Every class file must contain four things: a definition of ormalsize, values for extwidth and extheight, and a specification for page numbering. Thus, a minimal document class file1 looks like this:

1 This class is in the standard distribution, as minimal.cls.

Image

This class file will, however, not support footnotes, marginals, floats, or other features. Naturally, most classes will contain more than this minimum!

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

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