# IATEX for package and class authors -- current version

(c) Copyright 2023, LaTeX Project Team.

All rights reserved.

This file may distributed and/or modified under the conditions of the LaTeX Project Public License, either version 1.3c of this license or (at your option) any later version. See the source clsguide.tex for full details.

2023-01-12

###### Contents

* 1 Introduction
* 2 Writing classes and packages
	* 2.1 Is it a class or a package?
	* 2.2 Using 'docstrip' and 'doc'
	* 2.3 Policy on standard classes
	* 2.4 Command names
	* 2.5 Programming support
	* 2.6 Box commands and color
	* 2.7 General style
* 3 The structure of a class or package
	* 3.1 Identification
	* 3.2 Using classes and packages
	* 3.3 Declaring options
	* 3.4 A minimal class file
	* 3.5 Example: a local letter class
	* 3.6 Example: a newsletter class
* 4 Commands for class and package writers
	* 4.1 Identification
	* 4.2 Loading files
	* 4.3 Delaying code
	* 4.4 Creating and using keyval options
	* 4.5 Passing options around
	* 4.6 Safe file commands
	* 4.7 Reporting errors, etc
* 5Miscellaneous commands, etc. * 5.1 Layout parameters * 5.2 Case changing * 5.3 Better user-defined math display environments * 5.4 Normalising spacing * 5.5 Querying localisation
* 6 Commands superseded for new material
	* 6.1 Defining commands
	* 6.2 Option declaration
	* 6.3 Commands within option code
	* 6.4 Option processing

## 1 Introduction

\(\mathsf{LaTeX}\,2_{\varepsilon}\) was released in 1994 and added a number of then-new concepts to \(\mathsf{LaTeX}\). For package and class authors, these are described in clsguide-historic, which has largely remained unchanged. Since then, the \(\mathsf{LaTeX}\) team have worked on a number of ideas, firstly a programming language for \(\mathsf{LaTeX}\) (L3 programming layer) and then a range of tools for authors which build on that language. Here, we describe the current, stable set of tools provided by the \(\mathsf{LaTeX}\) kernel for package and class developers. We assume familiarity with general \(\mathsf{LaTeX}\) usage as a document author, and that the material here is read in conjunction with usrguide, which provides information for general \(\mathsf{LaTeX}\) users on up-to-date approaches to creating commands, etc.

## 2 Writing classes and packages

This section covers some general points concerned with writing \(\mathsf{LaTeX}\) classes and packages.

### Is it a class or a package?

The first thing to do when you want to put some new \(\mathsf{LaTeX}\) commands in a file is to decide whether it should be a _document class_ or a _package_. The rule of thumb is:

If the commands could be used with any document class, then make them a package; and if not, then make them a class.

There are two major types of class: those like article, report or letter, which are free-standing; and those which are extensions or variations of other classes--for example, the proc document class, which is built on the article document class.

Thus, a company might have a local ownlet class for printing letters with their own headed note-paper. Such a class would build on top of the existing letter class but it cannot be used with any other document class, so we have ownlet.cls rather than ownlet.sty.

The graphics package, in contrast, provides commands for including images into a LaTeX document. Since these commands can be used with any document class, we have graphics.sty rather than graphics.cls.

### Using 'docstrip' and 'doc'

If you are going to write a large class or package for LaTeX then you should consider using the doc software which comes with LaTeX. LaTeX classes and packages written using this can be processed in two ways: they can be run through LaTeX, to produce documentation; and they can be processed with docstrip, to produce the.cls or.sty file.

The doc software can automatically generate indexes of definitions, indexes of command use, and change-log lists. It is very useful for maintaining and documenting large TeX sources.

The documented sources of the LaTeX kernel itself, and of the standard classes, etc., are doc documents; they are in the.dtx files in the distribution. You can, in fact, typeset the source code of the kernel as one long document, complete with index, by running LaTeX on source2e.tex. Typesetting these documents uses the class file ltxdoc.cls.

For more information on doc and docstrip, consult the files docstrip.dtx, doc.dtx, and _The LaTeX Companion_. For examples of its use, look at the.dtx files.

### Policy on standard classes

Many of the problem reports we receive concerning the standard classes are not concerned with bugs but are suggesting, more or less politely, that the design decisions embodied in them are 'not optimal' and asking us to modify them.

There are several reasons why we should not make such changes to these files.

* However misguided, the current behaviour is clearly what was intended when these classes were designed.
* It is not good practice to change such aspects of'standard classes' because many people will be relying on them.

We have therefore decided not to even consider making such modifications, nor to spend time justifying that decision. This does not mean that we do not agree that there are many deficiencies in the design of these classes, but we have many tasks with higher priority than continually explaining why the standard classes for LaTeX cannot be changed.

We would, of course, welcome the production of better classes, or of packages that can be used to enhance these classes. So your first thought when you consider such a deficiency will, we hope, be "what can I do to improve this?"

### Command names

Prior to the introduction of the L3 programming layer described in the next section, LaTeX had three types of command.

There are the author commands, such as \section, \emph and \times: most of these have short names, all in lower case.

There are also the class and package writer commands: most of these have long mixed-case names such as the following.

\InputIfFileExists \RequirePackage \PassOptionsToClass

Finally, there are the internal commands used in the LaTeX implementation, such as \@tempcnta, \@ifnextchar and \@eha: most of these commands contain \@ in their name, which means they cannot be used in documents, only in class and package files.

Unfortunately, for historical reasons the distinction between these commands is often blurred. For example, \bbox is an internal command which should only be used in the LaTeX kernel, whereas \m@ne is the constant \(-1\) and could have been \MinusOne.

However, 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 behaviour may change in future releases! If a command is mixed-case, or is described in _LaTeX: A Document Preparation System_, then you can rely on future releases of LaTeX supporting the command.

### Programming support

As noted in the introduction, the LaTeX kernel today loads dedicated support from programming, here referred to as the L3 programming layer but also often called \expl3. Details of the general approach taken by the L3 programming layer are given in the document expl3, while a reference for all current code interfaces is available as interface3. This layer contains two types of command: a documented set of commands making up the API and a large number of private internal commands. The latter all start with two underscores and should not be used outside of the code module which defines them. This more structured approach means that using the L3 programming layer does not suffer from the somewhat fluid situation mentioned above with '\@ commands'.

We do not cover the detail of using the L3 programming layer here. A good introduction to the approach is provided at [https://www.alanshawn.com/latex3-tutorial/](https://www.alanshawn.com/latex3-tutorial/).

### 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 compatiblewith the color package. This may benefit people using your class or package and wish to use color.

The simplest way to ensure 'color safety' is to always use LaTeX box commands rather than TeX primitives, that is use \sbox rather than \ssetbox, \mbox rather than \hbox and \parbox or the minipage environment rather than \vbox. The LaTeX box commands have new options which mean that they are now as powerful as the TeX primitives.

As an example of what can go wrong, consider that in {\ttfamily <text>} the font is restored just _before_ the }, whereas in the similar looking construction {\color{green} <text>} the color is restored just _after_ the final }. Normally this distinction does not matter at all; but consider a primitive TeX box assignment such as:

\ssetbox0=\hbox{\color{green} <text>}

Now the color-restore occurs after the } and so is _not_ stored in the box. Exactly what bad effects this can have depends on how color is implemented: it 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 \normalcolor. This is normally just \relax (i.e., does nothing) but you can use it rather like \normalfont to set regions of the page such as captions or section headings to the'main document color'.

### General style

LaTeX provides many commands designed to help you produce well-structured class and package files that are both robust and portable. This section outlines some ways to make intelligent use of these.

#### Loading other files

LaTeX provides these commands:

\LoadClass \LoadClassWithOptions \RequirePackage \RequirePackageWithOptions

for using classes or packages inside other classes or packages. We recommend strongly that you use them, rather than the primitive \input command, for a number of reasons.

Files loaded with \input <filename> will not be listed in the \listfiles list.

If a package is always loaded with \RequirePackage... or \usepackage then, even if its loading is requested several times, it will be loaded only once. By contrast, if it is loaded with \input then it can be loaded more than once; such an extra loading may waste time and memory and it may produce strange results.

If a package provides option-processing then, again, strange results are possible if the package is \input rather than loaded by means of \usepackage or \RequirePackage....

If the package foo.sty loads the package baz.sty by use of \input baz.sty then the user will get a warning:

 LaTeX Warning: You have requested package 'foo',  but the package provides 'baz'.

Thus, for several reasons, using \input to load packages is not a good idea.

For example, article.sty contains just the following lines:

 \NeedsTeXFormat{LaTeX2e}  \@obsoletefile{article.cls}{article.sty}  \LoadClass{article}

You may wish to do the same or, if you think that it is safe to do so, you may decide to just remove myclass.sty.

#### 2.7.2 Make it robust

We consider it good practice, when writing packages and classes, to use LaTeX commands as much as possible.

Thus, instead of using \def... we recommend using one of \newcommand, \renewcommand or \providecommand for programming and for defining document interfaces \NewDocumentCommand, etc. (see usrguide for details of these commands).

When you define an environment, use \NewDocumentEnvironment, etc., (or \newenvironment, etc., for simple cases) instead of using \def\foo{...} and \def\endfoo{...}.

If you need to set or change the value of a \(\mathit{dimen}\) or \(\mathit{skip}\) register, use \setlength.

To manipulate boxes, use LaTeX commands such as \sbox, \mbox and \parbox rather than \setbox, \hbox and \vbox.

Use \PackageError, \PackageWarning or \PackageInfo (or the equivalent class commands) rather than \@latexerr, \@warning or \wlog.

The advantage of this kind of practice is that your code is more readable and accessible to other experienced LaTeX programmers.

#### 2.7.3 Make it portable

It is also sensible to make your files are as portable as possible. To ensure this, files must not have the same name as a file in the standard LaTeX distribution, however similar its contents may be to one of these files. It is also still lower risk to stick to file names which use only the ASCII range: whilst LaTeX works natively with UTF-8, the same cannot be said with certainty for all tools. For the same reason, avoid spaces in file names.

It is also useful if local classes or packages have a common prefix, for example the University of Nowhere classes might begin with unw. This helps to avoid every University having its own thesis class, all called thesis.cls.

If you rely on some features of the LaTeX kernel, or on a package, please specify the release-date you need. For example, the package error commands were introduced in the June 2022 release so, if you use them then you should put:

\NeedsTeXFormat{LaTeX2e}[2022-06-01]

#### 2.7.4 Useful hooks

It is sometimes necessary for a package to arrange for code to be executed at the start or end of the preamble, at the end of the document or at the start of every use of an environment. This can be carried out by using hooks. As a document author, you will likely be familiar with \AtBeginDocument, a wrapper around the more powerful command \AddToHook. The LaTeX kernel provides a large number of dedicated hooks (applying in a pre-defined location) and generic hooks (applying to arbitrary commands): the interface for using these is described in 1thooks. There are also hooks to apply to files, described in 1tfilehooks.

## 3 The structure of a class or package

The outline of a class or package file is:

**Identification**: The file says that it is a LaTeX 2\(\varepsilon\) package or class, and gives a short description of itself.
**Preliminary declarations**: Here the file declares some commands and can also load other files. Usually these commands will be just those needed for the code used in the declared options.
**Options**: The file declares and processes its options.
**More declarations**: This is where the file does most of its work: declaring new variables, commands and fonts; and loading other files.

### Identification

The first thing a class or package file does is identify itself. Package files do this as follows:

\NeedsTeXFormat{LaTeX2e} \ProvidesPackage{<package>}[<date> <other information>]For example:

\WeedsTeXFormat{LaTeX2e}

\ProvidesPackage{latexsym}[1998-08-17 Standard LaTeX package]

Class files do this as follows:

\WeedsTeXFormat{LaTeX2e}

\ProvidesClass{<class-name>}[<date> <other information>]

For example:

\WeedsTeXFormat{LaTeX2e}

\ProvidesClass{article}[2022-06-01 Standard LaTeX class]

The \(date\) should be given in the form 'yyyy-mm-dd' and must be present if the optional argument is used (this is also true for the \WeedsTeXFormat command). Any derivation from this syntax will result in low-level TeX errors--the commands expect a valid syntax to speed up the daily usage of the package or class and make no provision for the case that the developer made a mistake!

This date is checked whenever a user specifies a date in their \documentclass or \usepackage command. For example, if you wrote:

\documentclass{article}[2022-06-01]

then users at a different location would get a warning that their copy of article was out of date.

The description of a class is displayed when the class is used. The description of a package is put into the log file. These descriptions are also displayed by the \listfiles command. The phrase Standard LaTeX **must not** be used in the identification banner of any file other than those in the standard LaTeX distribution.

### Using classes and packages

A LaTeX package or class can load a package as follows:

\RequirePackage[<options>]{package>}[<date>]

For example:

\RequirePackage{ifthen}[2022-06-01]

This command has the same syntax as the author command \usepackage. It allows packages or classes to use features provided by other packages. For example, by loading the ifthen package, a package writer can use the 'if...then...else...' commands provided by that package.

A LaTeX class can load one other class as follows:\LoadClass[<options>]{<class-name>}[<date>] For example:

\LoadClass[twocolumn]{article} This command has the same syntax as the author command \documentclass. It allows classes to be based on the syntax and appearance of another class. For example, by loading the article class, a class writer only has to change the bits of article they don't like, rather than writing a new class from scratch.

The following commands can be used in the common case that you want to simply load a class or package file with exactly those options that are being used by the current class.

\LoadClassWithOptions{<class-name>}[<date>] \RequirePackageWithOptions{<package>}[<date>] For example:

\LoadClassWithOptions{article} \RequirePackageWithOptions{graphics}[1995/12/01]

### Declaring options

Packages and classes can declare options and these can be specified by authors; for example, the twocolumn option is declared by the article class. Note that the name of an option should contain only those characters allowed in a 'LaTeX name'; in particular it must not contain any control sequences.

LaTeX supports two methods for creating options: a key-value system and a'simple text' approach. The key-value system is recommended for new classes and packages, and is more flexible in handling of option classes than the simple text approach. Both option methods use the same basic structure within the LaTeX source: declaration of options first then processing options in a second step. Both also allow options to be passed on to other packages or an underlying class. As the 'classical' simple text approach is conceptually more straightforward to illustrate, it is used here to show the general structure: see Section 4.4 for full details of the key-value approach.

An option is declared as follows:

\DeclareOption{<option>}{<code>} For example, the dvips option (slightly simplified) to the graphics package is implemented as:

\DeclareOption{dvips}{\input{dvips.def}}

This means that when an author writes \usepackage[dvips]{graphics}, the file dvips.def is loaded. As another example, the a4paper option is declared in the article class to set the \paperheight and \paperwidth lengths:

 \DeclareOption{a4paper}{  \setlength{paperheight}{297mm}%  \setlength{paperwidth}{210mm}%  }

Sometimes a user will request an option which the class or package has not explicitly declared. By default this will produce a warning (for classes) or error (for packages); this behaviour can be altered as follows:

 \DeclareOption*{<code>}

For example, to make the package fred produce a warning rather than an error for unknown options, you could specify:

 \DeclareOption*{%  \PackageWarning{fred}{Unknown option '\CurrentOption'}%  }

Then, if an author writes \usepackage[foo]{fred}, they will get a warning Package fred Warning: Unknown option 'foo'. As another example, the fontenc package tries to load a file <ENC>enc.def whenever the \(\mathit{ENC}\) option is used. This can be done by writing:

 \DeclareOption*{%  \input{\CurrentOption enc.def}%  }

It is possible to pass options on to another package or class, using the command \PassOptionsToPackage or \PassOptionsToClass (note that this is a specialised operation that works only for option names): see Section 4.5. For example, to pass every unknown option on to the article class, you can use:

 \DeclareOption*{%  \PassOptionsToClass{\CurrentOption}{article}%  }

If you do this then you should make sure you load the class at some later point, otherwise the options will never be processed!

So far, we have explained only how to declare options, not how to execute them. To process the options with which the file was called, you should use:

 \ProcessOptions\relax


\DeclareOption*{VassOptionsToClass{\CurrentOption}{letter}} \ProcessOptions\relax \LoadClass[a4paper]{letter} In order to use the company letter head, it redefines the firstpage page style: this is the page style that is used on the first page of letters.

 \renewcommand{\ps@firstpage}{%  \renewcommand{\@oddhead}{<letterhead goes here>}%  \renewcommand{\@oddfoot}{<letterfoot goes here>}%  } And that's it!

### Example: a newsletter class

A simple newsletter can be typeset with LaTeX, using a variant of the article class. The class begins by announcing itself as smplnews.cls.

 \WeedsTeXFormat{LaTeX2e}  \ProvidesClass{smplnews}[2022-06-01 The Simple News newsletter class]

 \newcommand{\headlinecolor}{\normalcolor} It passes most specified options on to the article class: apart from the onecolumn option, which is switched off, and the green option, which sets the headline in green.

 \DeclareOption{onecolumn}{\OptionNotUsed}  \DeclareOption{green}{\renewcommand{\headlinecolor}{\color{green}}}  \DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}}  \ProcessOptions\relax It then loads the class article with the option twocolumn.

 \LoadClass[twocolumn]{article} Since the newsletter is to be printed in colour, it now loads the color package. The class does not specify a device driver option since this should be specified by the user of the smplnews class.

 \RequirePackage{color} The class then redefines \maketitle to produce the title in 72 pt Helvetica bold oblique, in the appropriate colour.

\renewcommand{\maketitle}{%  \twocolumn[%  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}

It redefines \section and switches off section numbering.

 \renewcommand{\section}{\fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}

 \section{\fontsize{}  \fontsize{}  \fontsize{}

It also sets the three essential things.

 \renewcommand{\normalsize}{\fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}  \fontsize{}

In practice, a class would need more than this: it would provide commands for issue numbers, authors of articles, page styles and so on; but this skeleton gives a start. The ltnews class file is not much more complex than this one.

## 4 Commands for class and package writers

This section describes briefly each of the commands for class and package writers. To find out about other aspects of the system, you should also read LaTeX: _A Document Preparation System_, _The LaTeX Companion_ and LaTeX 2_\(\varepsilon\) for Authors_.

### Identification

The first group of commands discussed here are those used to identify your class or package file.

\NeedsTeXFormat{\format-name}}[{\release-date}]

This command tells TeX that this file should be processed using a format with name \format-name. You can use the optional argument \release-date to further specify the earliest release date of the format that is needed. When the release date of the format is older than the one specified a warning will be generated. The standard \format-name is LaTeX2e. The date, if present, must be in the form yyyy-mm-dd.

Example:WeedsTeXFormat{LaTeX2e}[2022-06-01] People often don't know what date to put here. For the kernel, you can find out the right one by consulting changes.txt and select the release date of a new feature you are interested in. This is slightly different for packages as they are released throughout the year: you will need to consult their change history.

```
\ProvidesClass{\(\_\)class-name\}I{release-info\} \ProvidesPackage{\(\_\)package-name\}I{release-info\}
```

This declares that the current file contains the definitions for the document class \(\_\)class-name\()\) or package \(\_\)package-name\()\).

The optional \(\_\)release-info\()\), if used, must contain:

* the release date of this version of the file, in the form yyyy-mm-dd;
* optionally followed by a space and a short description, possibly including a version number.

The above syntax must be followed exactly so that this information can be used by \LoadClass or \documentclass (for classes) or \RequirePackage or \usepackage (for packages) to test that the release is not too old.

The whole of this \(\_\)release-info\()\) information is displayed by \listfiles and should therefore not be too long.

Example:

```
\ProvidesClass{article}[2022-06-01 v1.0 Standard LaTeX class] \ProvidesPackage{ifthen}[2022-06-01 v1.0 Standard LaTeX package]
```

This is similar to the two previous commands except that here the full filename, including the extension, must be given. It is used for declaring any files other than main class and package files.

Example:

```
\ProvidesFile{Tlenc.def}[2022-06-01 v1.0 Standard LaTeX file]
```

Note that the phrase Standard LaTeX **must not** be used in the identification banner of any file other than those in the standard LaTeX distribution.

### Loading files

This group of commands can be used to create your own document class or package by building on existing classes or packages.

\RequirePackage[\(options-list)]{\(\package-name)}[\(release-info)] \RequirePackageWithOptions{(package-name)}[\(release-info)] ```
Packages and classes should use these commands to load other packages.

The use of \RequirePackage is the same as the author command \usepackage. Examples:

\RequirePackage{ifthen}[2022-06-01] \RequirePackageWithOptions{graphics}[2022-06-01]

\LoadClass[(options-list)]{(class-name)}[\(release-info)] \LoadClassWithOptions{(class-name)}[\(release-info)]
```

These commands are for use _only_ in class files, they cannot be used in packages files; they can be used at most once within a class file.

The use of \LoadClass is the same as the use of \documentclass to load a class file.

Examples:

\LoadClass{article}[2022-06-01] \LoadClassWithOptions{article}[2022-06-01]

The two WithOptions versions simply load the class (or package) file with exactly those options that are being used by the current file (class or package). See below, in 4.5, for further discussion of their use.

### Delaying code

As noted earlier, a sophisticated hook system is available and described in lithooks. Here, we document a small set of convenient short names for common hooks.

These first two commands are also intended primarily for use within the \(code\) argument of \DeclareOption or \DeclareOption*.

\AtEndOfClass{(code)} \AtEndOfPackage{(code)} These commands declare \(code\) that is saved away internally and then executed after processing the whole of the current class or package file.

Repeated use of these commands is permitted: the code in the arguments is stored (and later executed) in the order of their declarations.

\AtBeginDocument{(code)} \AtEndDocument{(code)} These commands declare \(code\) to be saved internally and executed while LaTeX is executing \begin{document} or \end{document}.

The \(\langle\)_code_\(\rangle\) specified in the argument to \AtBeginDocument is executed near the end of the \begin{document} code, _after_ the font selection tables have been set up. It is therefore a useful place to put code which needs to be executed after everything has been prepared for typesetting and when the normal font for the document is the current font.

The \AtBeginDocument hook should not be used for code that does any typesetting since the typeset result would be unpredictable.

The \(\langle\)_code_\(\rangle\) specified in the argument to \AtEndDocument is executed at the beginning of the \end{document} code, _before_ the final page is finished and before any leftover floating environments are processed. If some of the \(\langle\)_code_\(\rangle\) is to be executed after these two processes, you should include a \clearpage at the appropriate point in \(\langle\)_code_\(\rangle\).

Repeated use of these commands is permitted: the code in the arguments is stored (and later executed) in the order of their declarations.

### Creating and using keyval options

As with any key-value input, using key-value pairs as package or class options has two parts: creating the key options and setting (using) them. Options created in this way _may_ be used after package loading as general key-value settings: this will depend on the nature of the underlying code.

\DeclareKeys[(_family_)] \{\(\langle\)_declarations_\(\rangle\}\)

This command creates a series of options from a comma-separated \(\langle\)_declarations_\(\rangle\) list. Each entry in this list is a key-value pair, with the \(\langle\)_key_\(\rangle\) having one or more \(\langle\)_properties_\(\rangle\). A small number of 'basic' \(\langle\)_properties_\(\rangle\) are described below. The full range of properties, provided by 13keys, can also be used for more powerful processing. See interface3 for the full details.

The basic properties provided here are

*.code -- execute arbitrary code
*.if -- sets a TeX \if... switch
*.ifnot -- sets an inverted TeX \if... switch
*.store -- stores a value in a macro
* defines whether the option can be given only when loading (load), in the preamble (preamble) or has no limitation on scope (general)

The part of the \(\langle\)_key_\(\rangle\) before the \(\langle\)_property_\(\rangle\) is the \(\langle\)_name_\(\rangle\), with the \(\langle\)_value_\(\rangle\) working with the \(\langle\)_property_\(\rangle\) to define the behaviour of the option.

For example, with }DeclareKeys[mpkg] {  draft.if = @mypkg@draft,  draft.usage = preamble,  name.store = \@mypkg@name,  name.usage = load,  second-name.store = \@mypkg@other@name } three options would be created. The option draft can be given anywhere in the preamble, and will set a switch called \if@mypkg@draft. The option name can only be given during package loading, and will save whatever value it is given in \@mypkg@name. Finally, the option second-name can be given anywhere, and will save its value in \@mypkg@other@name.

Keys created _before_ the use of \ProcessKeyOptions act as package options.

\DeclareUnknownKeyHandler[\(\langle\)_family_\(\rangle\)] The command \DeclareUnknownKeyHandler may be used to define the behavior when an undefined key is encountered. The \(\langle\)_code_\(\rangle\) will receive the unknown key name as #1 and the value as #2. These can then be processed as appropriate, e.g. by forwarding to another package.

\ProcessKeyOptions[\(\langle\)_family_\(\rangle\)] The \ProcessKeyOptions function is used to check the current option list against the keys defined for \(\langle\)_family_\(\rangle\). Global (class) options and local (package) options are checked when this function is called in a package.

\SetKeys[\(\langle\)_family_\(\rangle\)] {\(\langle\)_keyvals_\(\rangle\)} Sets (applies) the explicit list of \(\langle\)_keyvals_\(\rangle\) for the \(\langle\)_family_\(\rangle\): if the latter is not given, the value of \@currname is used. This command may be used within a package to set options before or after using \ProcessKeyOptions.

### Passing options around

These two commands are also very useful within the \(\langle\)_code_\(\rangle\) argument of options.

\PassOptionsToPackage {\(\langle\)_options-list_\(\rangle\)} {\(\langle\)_package-name_\(\rangle\)} \PassOptionsToClass {\(\langle\)_options-list_\(\rangle\)} {\(\langle\)_class-name_\(\rangle\)} The command \PassOptionsToPackage passes the option names in \(\langle\)_options-list_\(\rangle\) to package \(\langle\)_package-name_\(\rangle\). This means that it adds the \(\langle\)_option-list_\(\rangle\) to the list of options used by any future \RequirePackage or \usepackage command for package \(\langle\)_package-name_\(\rangle\).

Example:\PassOptionsToPackage{foo,bar}{fred}  \RequirePackage[baz]{fred} is the same as:

\RequirePackage[foo,bar,baz]{fred} Similarly, \PassOptionsToClass may be used in a class file to pass options to another class to be loaded with \LoadClass.

The effects and use of these two commands should be contrasted with those of the following two (documented above, in 4.2):

\LoadClassWithOptions  \RequirePackageWithOptions

The command \RequirePackageWithOptions is similar to \RequirePackage, but it always loads the required package with exactly the same option list as that being used by the current class or package, rather than with any option explicitly supplied or passed on by \PassOptionsToPackage.

The main purpose of \LoadClassWithOptions is to allow one class to simply build on another, for example:

 \LoadClassWithOptions{article} This should be compared with the slightly different construction

 \DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}  \ProcessOptions} relax  \LoadClass{article} As used above, the effects are more or less the same, but the first is a lot less to type; also the \LoadClassWithOptions method runs slightly quicker.

If, however, the class declares options of its own then the two constructions are different. Compare, for example:

 \DeclareOption{landscape}{\@landscapetrue}  \ProcessOptions}relax  \LoadClassWithOptions{article}

with:

 \DeclareOption{landscape}{\@landscapetrue}  \DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}  \ProcessOptions}relax  \LoadClass{article} In the first example, the article class will be loaded with option landscape precisely when the current class is called with this option. By contrast, in the second example it will never be called with option landscape as in that case article is passed options only by the default option handler, but this handler is not used for landscape because that option is explicitly declared.

### Safe file commands

These commands deal with file input; they ensure that the non-existence of a requested file can be handled in a user-friendly way.

```
\IfFileExists{\(\mathit{file\_name}\)}{\(\langle\mathit{true}\rangle\)}{\(\langle\mathit{false}\rangle\)}
```

If the file exists then the code specified in \(\langle\mathit{true}\rangle\) is executed.

If the file does not exist then the code specified in \(\langle\mathit{false}\rangle\) is executed.

This command does _not_ input the file.

```
\InputIfFileExists{\(\langle\mathit{file\_name}\rangle\)}{\(\langle\mathit{true}\rangle\)}{\(\langle\mathit{false}\rangle\)}
```

This inputs the file \(\langle\mathit{file\_name}\rangle\) if it exists and, immediately before the input, the code specified in \(\langle\mathit{true}\rangle\) is executed.

If the file does not exist then the code specified in \(\langle\mathit{false}\rangle\) is executed.

It is implemented using \IfFileExists.

### Reporting errors, etc

These commands should be used by third party classes and packages to report errors, or to provide information to authors.

```
\ClassError{(\langle\mathit{class\_name}\rangle\)}{\(\langle\mathit{error\_text}\rangle\)}{\(\langle\mathit{help\_text}\rangle\)}{\(\langle\)PackageError\(\langle\mathit{package\_name}\rangle\)}{\(\langle\mathit{error\_text}\rangle\)}{\(\langle\mathit{help\_text}\rangle\)}
```

These produce an error message. The \(\langle\mathit{error\_text}\rangle\) is displayed and the \(\mathcal{T}\) error prompt is shown. If the user types h, they will be shown the \(\langle\mathit{help\_text}\rangle\).

Within the \(\langle\mathit{error\_text}\rangle\) and \(\langle\mathit{help\_text}\rangle\): \(\backslash\)protect can be used to stop a command from expanding; \(\backslash\)MessageBreak causes a line-break; and \(\backslash\)space prints a space.

Note that the \(\langle\mathit{error\_text}\rangle\) will have a full stop added to it, so do not put one into the argument.

For example:

```
\newcommand{\foo}{F00} \PackageError{ethel}{\%  Your hovercraft is full of eels,\MessageBreak  and \protect\foo\space is \foo }{\%  Oh dear! Something's gone wrong.\MessageBreak \space\space Try typing \space \space \space tryturns \space to proceed, ignoring \protect\foo. }
```

produces this display::

! Package ethel Error: Your hovercraft is full of eels,  (ethel) and \foo is F0O.

 See the ethel package documentation for explanation.

 If the user types h, this will be shown:

 Oh dear! Something's gone wrong.  Try typing <return> to proceed, ignoring \foo.

\ClassWarning {_class-name_} {_warning-text_} \PackageWarning {_package-name_} {_warning-text_} \ClassWarningNoLine {_class-name_} {_warning-text_} \PackageWarningNoLine {_package-name_} {_warning-text_} \ClassInfo {_class-name_} {_info-text_} \PackageInfo {_package-name_} {_info-text_} \PackageInfo {_package-name_} {_info-text_} \The four Warning commands are similar to the error commands, except that they produce only a warning on the screen, with no error prompt.

 The first two, Warning versions, also show the line number where the warning occurred, whilst the second two, WarningNoLine versions, do not.

 The two Info commands are similar except that they log the information only in the transcript file, including the line number. There are no NoLine versions of these two.

 Within the \(\langle\)_warning-text_\(\rangle\) and \(\langle\)_info-text_\(\rangle\): \(\backslash\)protect can be used to stop a command from expanding; \(\backslash\)MessageBreak causes a line-break; and \(\backslash\)space prints a space. Also, these should not end with a full stop as one is automatically added.

## 5 Miscellaneous commands, etc.

### Layout parameters

\paperheight \paperwidth

These two parameters are usually set by the class to be the size of the paper being used. This should be actual paper size, unlike \textwidth and \textheight which are the size of the main text body within the margins.

### Case changing

\MakeUppercase {_text_} MakeLowercase {_text_} MakeTitlecase {_text_}

 As described in usrguide, case changing for text should be carried out usingthe commands MakeUppercase, MakeLowercase and MakeTitlecase. If you need to change the case of programmatic material, the team strongly suggest using the L3 programming layer commands in the str module. If you do not wish to do this, you should use the TeX \uppercase and \lowercase primitives _in this situation only_.

### Better user-defined math display environments

```
\ignorespacesaaferend
```

Suppose that you want to define an environment for displaying text that is numbered as an equation. A straightforward way to do this is as follows:

```
\newenvironment{texteqn} {begin{equation} \begin{minipage}{0.9\linewidth} \{end{minipage} \end{equation}
```

However, if you have tried this then you will probably have noticed that it does not work perfectly when used in the middle of a paragraph because an inter-word space appears at the beginning of the first line after the environment.

You can avoid this problem using \ignorespacesafterend; it should be inserted as shown here:

```
\newenvironment{texteqn} {begin{equation} \begin{minipage}{0.9\linewidth} \{end{minipage} \end{equation} \ignorespacesafterend}
```

This command may also have other uses.

### Normalising spacing

```
\normalsfcodes
```

This command should be used to restore the normal settings of the parameters that affect spacing between words, sentences, etc.

An important use of this feature is to correct a problem, reported by Donald Arseneau, that punctuation in page headers has always (in all known TeX formats) been potentially wrong whenever a page break happens while a local setting of the space codes is in effect. These space codes are changed by, for example, the command \frenchspacing) and the verbatim environment.

It is normally given the correct definition automatically in \begin{document} and so need not be explicitly set; however, if it is explicitly made non-empty in a class file then automatic default setting will be over-ridden.

### Querying localisation

Localisation information is needed to customise a range of outputs. The LaTeX kernel does not itself manage localisation, which is well-served by the bundles babel and polyglossia. To allow the kernel and other packages to access the current localisation information provided by babel or polyglossia, the command \BCPdata is defined by the kernel. The initial kernel definition expands to tag parts for en-US, as the kernel does not track localisation but does start out with a broadly US English setup. However, if babel or polyglossia are loaded, it is redefined expand to the BCP-47 information from the appropriate package. The supported arguments are the BCP-47 tag breakdowns:

* tag The full BCP-47 tag (e.g. en-US)
* language (e.g., de)
* region (e.g., AT)
* script (e.g., Latn)
* variant (e.g., 1901)
* extension.t (transformation, e.g., en-t-ja)
* extension.u (additional locale information, e.g., ar-u-nu-latn)
* extension.x (private use area, e.g., la-x-classic)

The information for the _main_ language for a document is be provided if these are prefixed by main., e.g. main.language will expand to the main language even if another language is currently active.

In addition to the tag breakdown, the following semantic arguments are supported

* casing The tag for case changing, e.g. el-x-iota could be selected rather than el to select a capital adscript iota on uppercasing an _ypogegrammeni_

For example, the case changing command \MakeUppercase is (conceptually) defined as

\ExpandArgs{e}\MakeUppercaseAux{\BCPdata{casing}}{#1}

where #1 is the user input and the first argument to \MakeUppercaseAux takes two arguments, the locale and input text.

## 6 Commands superseded for new material

A small number of commands were introduced as part of LaTeX 2\(\varepsilon\) in the mid-1990s, are widely used but have been superseded by more modern methods. These are covered here as they are likely to be encountered routinely in existing classes and packages.

### Defining commands

The *-forms of these commands should be used to define commands that are not, in TeX terms, long. This can be useful for error-trapping with commands whose arguments are not intended to contain whole paragraphs of text.

```
\DeclareRobustCommand{{cmd}}[{num}][{default}]{{definition}} DeclareRobustCommand*{{cmd}}[{num}][{default}]{{definition}}
```

This command takes the same arguments as \newcommand but it declares a robust command, even if some code within the \(\langle\)_definition_\(\rangle\) is fragile. You can use this command to define new robust commands, or to redefine existing commands and make them robust. A log is put into the transcript file if a command is redefined.

For example, if \seq is defined as follows:

```
\DeclareRobustCommand{\seq}[2][n]{% \ifmmode #1_{1}\ldots#1_{#2}% \else \PackageWarning{fred}{You can't use \protect\seq\space in text}% \fi }
```

Then the command \seq can be used in moving arguments, even though \ifmmode cannot, for example:

```
\section{Stuffaboutsequences$\seq{x}$}
```

Note also that there is no need to put a \relax before the \ifmmode at the beginning of the definition; this is because the protection given by this \relax against expansion at the wrong time will be provided internally.

```
\CheckCommand{{cmd}}[{num}][{default}]{{definition}} CheckCommand*{{cmd}}[{num}][{default}]{{definition}}
```

This takes the same arguments as \newcommand but, rather than define \(cmd\), it just checks that the current definition of \(cmd\) is exactly as given by \(\langle\)_definition_\(\rangle\). An error is raised if these definitions differ.

This command is useful for checking the state of the system before your package starts altering the definitions of commands. It allows you to check, in particular, that no other package has redefined the same command.

### Option declaration

The following commands deal with the declaration and handling of options to document classes and packages using a classical'simple text' approach. Every option name must be a 'LaTeX name'.

There are some commands designed especially for use within the \(\langle code\rangle\) argument of these commands (see below).

\DeclareOption\(\{\langle\)option-name\(\rangle\}\)\(\{\langle code\rangle\}\) This makes \(\langle\)option-name\(\rangle\) a 'declared option' of the class or package in which it is put. The \(\langle code\rangle\) argument contains the code to be executed if that option is specified for the class or package; it can contain any valid LaTeX\(2_{\varepsilon}\) construct. Example: \DeclareOption\(\{\)twoside\(\}\{\)\(\emptyset\)twosidetrue\(\}\) This declares the \(\langle code\rangle\) to be executed for every option which is specified for, but otherwise not explicitly declared by, the class or package; this code is called the 'default option code' and it can contain any valid LaTeX\(2_{\varepsilon}\) construct. If a class file contains no \DeclareOption* then, by default, all specified but undeclared options for that class will be silently passed to all packages (as will the specified and declared options for that class). If a package file contains no \DeclareOption* then, by default, each specified but undeclared option for that package will produce an error.

### Commands within option code

These two commands can be used only within the \(\langle code\rangle\) argument of either \DeclareOption or \DeclareOption*. Other commands commonly used within these arguments can be found in the next few subsections.

\CurrentOption

This expands to the name of the current option.

\OptionNotUsed

This causes the current option to be added to the list of 'unused options'.

### Option processing

\ProcessOptions

This command executes the \(\langle code\rangle\) for each selected option.

We shall first describe how \ProcessOptions works in a package file, and then how this differs in a class file.

To understand in detail what \ProcessOptions does in a package file, you have to know the difference between _local_ and _global_ options.

* **Local options** are those which have been explicitly specified for this particular package in the \(_options_) argument of any of these: \PassOptionsToPackage{<options>} \usepackage[<options>] \RequirePackage[<options>]
* **Global options** are any other options that are specified by the author in the \(_options_) argument of \documentclass[<options>].

For example, suppose that a document begins:

\documentclass[german,twocolum]{article} \usepackage{gerhardt}

whilst package gerhardt calls package fred with:

\PassOptionsToPackage{german,dvips,a4paper}{fred} \RequirePackage[errorshow]{fred}

then:

* fred's local options are german, dvips, a4paper and errorshow;
* fred's only global option is twocolumn.

When \ProcessOptions is called, the following happen.

* _First_, for each option so far declared in fred.sty by \DeclareOption, it looks to see if that option is either a global or a local option for fred: if it is then the corresponding code is executed. This is done in the order in which these options were declared in fred.sty.
* _Then_, for each remaining _local_ option, the command \ds@<option> is executed if it has been defined somewhere (other than by a \DeclareOption); otherwise, the 'default option code' is executed. If no default option code has been declared then an error message is produced. This is done in the order in which these options were specified.

Throughout this process, the system ensures that the code declared for an option is executed at most once.

Returning to the example, if fred.sty contains:

 \DeclareOption{dvips}{\typeout{DVIPS}} \DeclareOption{german}{\typeout{GERMAN}} \DeclareOption{french}{typeout{FRENCH}} \DeclareOption*{\PackageWarning{fred}{Unknown '\CurrentOption'}} \ProcessOptions\relaxthen the result of processing this document will be:

```
DVIPS GERMAN PackagefredWarning:Unknown'a4paper'. PackagefredWarning:Unknown'erorshow'.
```

Note the following:

* the code for the dvips option is executed before that for the german option, because that is the order in which they are declared in fred.sty;
* the code for the german option is executed only once, when the declared options are being processed;
* the a4paper and errorshow options produce the warning from the code declared by DeclareOption* (in the order in which they were specified), whilst the twocolumn option does not: this is because twocolumn is a global option.

In a class file, ProcessOptions works in the same way, except that: _all_ options are local; and the default value for DeclareOption* is \OptionNotUsed rather than an error.

Note that, because \ProcessOptions has a *-form, it is wise to follow the non-star form with \relax, as in the previous examples, since this prevents unnecessary look ahead and possibly misleading error messages being issued.

```
\ProcessOptions*
```

This is like \ProcessOptions but it executes the options in the order specified in the calling commands, rather than in the order of declaration in the class or package. For a package this means that the global options are processed first.

```
\ExecuteOptions{(options-list)}
```

It can be used to provide a 'default option list' just before \ProcessOptions. For example, suppose that in a class file you want to set up the default design to be: two-sided printing; 11pt fonts; in two columns. Then it could specify:

```
\ExecuteOptions{11pt,twoside,twocolumn}
```