text:
VDOC.PUB

### Computers & Typesetting: The Texbook [PDF]

This document was uploaded by our user. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

#### E-Book Overview

This guide to computer typesetting using TeX is written by Donald Knuth, the system's creator. TeX offers both writers and publishers the ability to produce plain or technical text, especially text containing a great deal of mathematics, comparable to the work of the finest printers. Novice and expert alike will find The TeXbook useful; it is accessible to the beginner, and also contains the details required by experienced users.

#### E-Book Content

(page mcmlxxxiii)

(page i)

DONALD E. KNUTH

Stanford University

Illustrations by DUANE BIBBY

6 77

ADDISON –WESLEY PUBLISHING COMPANY Reading, Massachusetts Menlo Park, California New York Don Mills, Ontario Wokingham, England Amsterdam · Bonn Sydney · Singapore · Tokyo Madrid · San Juan

(page ii)

This manual describes TEX Version 3.0. Some of the advanced features mentioned here are absent from earlier versions. c 1970 by Sesame Street, Inc., and used by permission The quotation on page 61 is copyright ° of the Children’s Television Workshop. TEX is a trademark of the American Mathematical Society.

opqrstuq is a trademark of Addison –Wesley Publishing Company. Library of Congress cataloging in publication data Knuth, Donald Ervin, 1938The TeXbook. (Computers & Typesetting ; A) Includes index. 1. TeX (Computer system). 2. Computerized typesetting. 3. Mathematics printing. I. Title. II. Series: Knuth, Donald Ervin, 1938. Computers & typesetting ; A. Z253.4.T47K58 1986 686.2'2544 85-30845 ISBN 0-201-13447-0 ISBN 0-201-13448-9 (soft)

Twentieth printing, revised, May 1991 c 1984, 1986 by the American Mathematical Society Copyright °

This book is published jointly by the American Mathematical Society and Addison –Wesley Publishing Company. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publishers. Printed in the United States of America. ISBN 0-201-13448-9 TUVWXYZ–DO–97654321

(page iii)

To Jill: For your books and brochures

(page iv)

(page v)

Preface READER: This is a handbook about TEX, a new typesetting system intended for the creation of beautiful books—and especially for books that contain a lot of mathematics. By preparing a manuscript in TEX format, you will be telling a computer exactly how the manuscript is to be transformed into pages whose typographic quality is comparable to that of the world’s finest printers; yet you won’t need to do much more work than would be involved if you were simply typing the manuscript on an ordinary typewriter. In fact, your total work will probably be significantly less, if you consider the time it ordinarily takes to revise a typewritten manuscript, since computer text files are so easy to change and to reprocess. (If such claims sound too good to be true, keep in mind that they were made by TEX’s designer, on a day when TEX happened to be working, so the statements may be biased; but read on anyway.) This manual is intended for people who have never used TEX before, as well as for experienced TEX hackers. In other words, it’s supposed to be a panacea that satisfies everybody, at the risk of satisfying nobody. Everything you need to know about TEX is explained here somewhere, and so are a lot of things that most users don’t care about. If you are preparing a simple manuscript, you won’t need to learn much about TEX at all; on the other hand, some things that go into the printing of technical books are inherently difficult, and if you wish to achieve more complex effects you will want to penetrate some of TEX’s darker corners. In order to make it possible for many types of users to read this manual effectively, a special sign is used to designate material that is for wizards only: When the symbol Ä ENTLE

appears at the beginning of a paragraph, it warns of a “dangerous bend” in the train of thought; don’t read the paragraph unless you need to. Brave and experienced drivers at the controls of TEX will gradually enter more and more of these hazardous areas, but for most applications the details won’t matter. All that you really ought to know, before reading on, is how to get a file of text into your computer using a standard editing program. This manual explains what that file ought to look like so that TEX will understand it, but basic computer usage is not explained here. Some previous experience with technical typing will be quite helpful if you plan to do heavily mathematical work with TEX, although it is not absolutely necessary. TEX will do most of the necessary

vi

Preface

formatting of equations automatically; but users with more experience will be able to obtain better results, since there are so many ways to deal with formulas. Some of the paragraphs in this manual are so esoteric that they are rated ÄÄ ; everything that was said about single dangerous-bend signs goes double for these. You should probably have at least a month’s experience with TEX before you attempt to fathom such doubly dangerous depths of the system; in fact, most people will never need to know TEX in this much detail, even if they use it every day. After all, it’s possible to drive a car without knowing how the engine works. Yet the whole story is here in case you’re curious. (About TEX, not cars.) The reason for such different levels of complexity is that people change as they grow accustomed to any powerful tool. When you first try to use TEX, you’ll find that some parts of it are very easy, while other things will take some getting used to. A day or so later, after you have successfully typeset a few pages, you’ll be a different person; the concepts that used to bother you will now seem natural, and you’ll be able to picture the final result in your mind before it comes out of the machine. But you’ll probably run into challenges of a different kind. After another week your perspective will change again, and you’ll grow in yet another way; and so on. As years go by, you might become involved with many different kinds of typesetting; and you’ll find that your usage of TEX will keep changing as your experience builds. That’s the way it is with any powerful tool: There’s always more to learn, and there are always better ways to do what you’ve done before. At every stage in the development you’ll want a slightly different sort of manual. You may even want to write one yourself. By paying attention to the dangerous bend signs in this book you’ll be better able to focus on the level that interests you at a particular time. Computer system manuals usually make dull reading, but take heart: This one contains JOKES every once in a while, so you might actually enjoy reading it. (However, most of the jokes can only be appreciated properly if you understand a technical point that is being made—so read carefully.) Another noteworthy characteristic of this manual is that it doesn’t always tell the truth. When certain concepts of TEX are introduced informally, general rules will be stated; afterwards you will find that the rules aren’t strictly true. In general, the later chapters contain more reliable information than the

Preface

earlier ones do. The author feels that this technique of deliberate lying will actually make it easier for you to learn the ideas. Once you understand a simple but false rule, it will not be hard to supplement that rule with its exceptions. In order to help you internalize what you’re reading, EXERCISES are sprinkled through this manual. It is generally intended that every reader should try every exercise, except for questions that appear in the “dangerous bend” areas. If you can’t solve a problem, you can always look up the answer. But please, try first to solve it by yourself; then you’ll learn more and you’ll learn faster. Furthermore, if you think you do know the solution, you should turn to Appendix A and check it out, just to make sure. The TEX language described in this book is similar to the author’s first attempt at a document formatting language, but the new system differs from the old one in literally thousands of details. Both languages have been called TEX; but henceforth the old language should be called TEX78, and its use should rapidly fade away. Let’s keep the name TEX for the language described here, since it is so much better, and since it is not going to change any more. I wish to thank the hundreds of people who have helped me to formulate this “definitive edition” of the TEX language, based on their experiences with preliminary versions of the system. My work at Stanford has been generously supported by the National Science Foundation, the Office of Naval Research, the IBM Corporation, and the System Development Foundation. I also wish to thank the American Mathematical Society for its encouragement, for establishing the TEX Users Group, and for publishing the TUGboat newsletter (see Appendix J). Stanford, California June 1983

— D. E. K.

‘Tis pleasant, sure, to see one’s name in print; A book’s a book, although there’s nothing in ’t. — BYRON, English Bards and Scotch Reviewers (1809) A question arose as to whether we were covering the field that it was intended we should fill with this manual. — RICHARD R. DONNELLEY, Proceedings, United Typothetæ of America (1897)

vii

(page viii)

Contents 1

The Name of the Game

2

Book Printing versus Ordinary Typing

3

Controlling TEX .

4

Fonts of Type .

5

Grouping

6

Running TEX .

7

How TEX Reads What You Type

8

The Characters You Type

9

TEX’s Roman Fonts .

.

. .

.

.

.

.

.

.

10

Dimensions

11

Boxes

12

Glue .

13

Modes .

14

How TEX Breaks Paragraphs into Lines

15

How TEX Makes Lines into Pages .

16

Typing Math Formulas .

17

18

Fine Points of Mathematics Typing

19

Displayed Equations .

20

Definitions (also called Macros) .

21

Making Boxes

22

Alignment

23

Output Routines

.

. .

. .

.

. .

.

. .

.

. .

.

.

. .

.

. .

.

.

.

.

.

.

.

185 199

. .

.

139 161

.

. .

.

.

109 127

.

.

.

.

.

85 91

.

.

.

. .

.

.

.

.

63 69

.

.

.

.

. .

.

.

.

.

51 57

.

.

.

.

.

.

.

.

.

.

37 43

.

.

.

.

.

.

.

.

.

.

19 23

.

.

.

.

.

. .

.

.

.

.

.

.

.

7 13

.

.

.

.

.

.

.

.

.

.

.

.

.

.

1 3

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

. .

.

.

.

.

. .

.

.

. .

.

.

.

. .

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

. .

.

.

.

. .

.

.

.

.

. .

.

.

.

. .

.

.

.

. .

.

.

.

221 231

.

251

Contents

24

Summary of Vertical Mode .

.

25

Summary of Horizontal Mode .

26

Summary of Math Mode

27

Recovery from Errors

. .

. .

. .

. .

. .

. .

. .

. .

. .

. .

. .

. .

. .

267 .

. .

285 289

.

295

Appendices A

B

Basic Control Sequences

C

Character Codes

D

Dirty Tricks .

E

Example Formats .

F

Font Tables .

G

Generating Boxes from Formulas

H

Hyphenation .

. .

.

.

.

.

.

I

Index

.

J

Joining the TEX Community

.

.

.

.

.

.

.

.

.

.

.

.

427 441

. .

.

373 403

.

. .

.

.

339 367

.

.

.

.

.

.

305

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

. .

.

.

.

. .

.

.

. .

. .

.

.

.

. .

.

.

. .

.

.

.

. .

.

.

.

.

449 457

.

483

ix

(page x)

1 The Name of the Game

Chapter 1: The Name of the Game

English words like ‘technology’ stem from a Greek root beginning with the letters τ ²χ . . . ; and this same Greek word means art as well as technology. Hence the name TEX, which is an uppercase form of τ ²χ. Insiders pronounce the χ of TEX as a Greek chi, not as an ‘x’, so that TEX rhymes with the word blecchhh. It’s the ‘ch’ sound in Scottish words like loch or German words like ach; it’s a Spanish ‘j’ and a Russian ‘kh’. When you say it correctly to your computer, the terminal may become slightly moist. The purpose of this pronunciation exercise is to remind you that TEX is primarily concerned with high-quality technical manuscripts: Its emphasis is on art and technology, as in the underlying Greek word. If you merely want to produce a passably good document—something acceptable and basically readable but not really beautiful—a simpler system will usually suffice. With TEX the goal is to produce the finest quality; this requires more attention to detail, but you will not find it much harder to go the extra distance, and you’ll be able to take special pride in the finished product. On the other hand, it’s important to notice another thing about TEX’s name: The ‘E’ is out of kilter. This displaced ‘E’ is a reminder that TEX is about typesetting, and it distinguishes TEX from other system names. In fact, TEX (pronounced tecks) is the admirable Text EXecutive processor developed by Honeywell Information Systems. Since these two system names are pronounced quite differently, they should also be spelled differently. The correct way to refer to TEX in a computer file, or when using some other medium that doesn’t allow lowering of the ‘E’, is to type ‘TeX’. Then there will be no confusion with similar names, and people will be primed to pronounce everything properly. x EXERCISE 1.1 After you have mastered the material in this book, what will you be: A TEXpert, or a TEXnician?

They do certainly give very strange and new-fangled names to diseases. — PLATO, The Republic, Book 3 (c. 375 B.C.) Technique! The very word is like the shriek Of outraged Art. It is the idiot name Given to effort by those who are too weak, Too weary, or too dull to play the game. — LEONARD BACON, Sophia Trenton (1920)

1

(page 2)

2 Book Printing versus Ordinary Typing

Chapter 2: Book Printing versus Ordinary Typing

When you first started using a computer terminal, you probably had to adjust to the difference between the digit ‘1’ and the lowercase letter ‘l’. When you take the next step to the level of typography that is common in book publishing, a few more adjustments of the same kind need to be made; your eyes and your fingers need to learn to make a few more distinctions. In the first place, there are two kinds of quotation marks in books, but only one kind on the typewriter. Even your computer terminal, which has more characters than an ordinary typewriter, probably has only a non-oriented double-quote mark ("), because the standard ASCII code for computers was not invented with book publishing in mind. However, your terminal probably does have two flavors of single-quote marks, namely ‘ and ’; the second of these is useful also as an apostrophe. American keyboards usually contain a left-quote character that shows up as something like , and an apostrophe or right-quote that looks like ' or ´. To produce double-quote marks with TEX, you simply type two singlequote marks of the appropriate kind. For example, to get the phrase “I understand.” (including the quotation marks) you should type ‘‘I understand.’’ to your computer. A typewriter-like style of type will be used throughout this manual to indicate TEX constructions that you might type on your terminal, so that the symbols actually typed are readily distinguishable from the output TEX would produce and from the comments in the manual itself. Here are the symbols to be used in the examples: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789"#$%[email protected]*+-=,.:;?! ()[]{}‘’\|/_^~ If your computer terminal doesn’t happen to have all of these, don’t despair; TEX can make do with the ones you have. An additional symbol Ã is used to stand for a blank space, in case it is important to emphasize that a blank space is being typed; thus, what you really type in the example above is ‘‘IÃunderstand.’’ Without such a symbol you would have difficulty seeing the invisible parts of certain constructions. But we won’t be using ‘Ã’ very often, because spaces are usually visible enough. 3 4 Chapter 2: Book Printing versus Ordinary Typing Book printing differs significantly from ordinary typing with respect to dashes, hyphens, and minus signs. In good math books, these symbols are all different; in fact there usually are at least four different symbols: a hyphen (-); an en-dash (–); an em-dash (—); a minus sign (−). Hyphens are used for compound words like ‘daughter-in-law’ and ‘X-rated’. Endashes are used for number ranges like ‘pages 13–34’, and also in contexts like ‘exercise 1.2.6–52’. Em-dashes are used for punctuation in sentences—they are what we often call simply dashes. And minus signs are used in formulas. A conscientious user of TEX will be careful to distinguish these four usages, and here is how to do it: for for for for a hyphen, type a hyphen (-); an en-dash, type two hyphens (--); an em-dash, type three hyphens (---); a minus sign, type a hyphen in mathematics mode ($-$). (Mathematics mode occurs between dollar signs; it is discussed later, so you needn’t worry about it now.) x EXERCISE 2.1 Explain how to type the following sentence to TEX: Alice said, “I always use an en-dash instead of a hyphen when specifying page numbers like ‘480–491’ in a bibliography.” x EXERCISE 2.2 What do you think happens when you type four hyphens in a row? If you look closely at most well-printed books, you will find that certain combinations of letters are treated as a unit. For example, this is true of the ‘f’ and the ‘i’ of ‘find’. Such combinations are called ligatures, and professional typesetters have traditionally been trained to watch for letter combinations such as ff, fi, fl, ffi, and ffl. (The reason is that words like ‘find’ don’t look very good in most styles of type unless a ligature is substituted for the letters that clash. It’s somewhat surprising how often the traditional ligatures appear in English; other combinations are important in other languages.) x EXERCISE 2.3 Think of an English word that contains two ligatures. The good news is that you do not have to concern yourself with ligatures: TEX is perfectly capable of handling such things by itself, using the same mechanism that converts ‘--’ into ‘–’. In fact, TEX will also look for combinations of adjacent letters (like ‘A’ next to ‘V’ ) that ought to be moved closer together for better appearance; this is called kerning. Chapter 2: Book Printing versus Ordinary Typing To summarize this chapter: When using TEX for straight copy, you type the copy as on an ordinary typewriter, except that you need to be careful about quotation marks, the number 1, and various kinds of hyphens/dashes. TEX will automatically take care of other niceties like ligatures and kerning. Ä (Are you sure you should be reading this paragraph? The “dangerous bend” sign here is meant to warn you about material that ought to be skipped on first reading. And maybe also on second reading. The reader-beware paragraphs sometimes refer to concepts that aren’t explained until later chapters.) Ä If your keyboard does not contain a left-quote symbol, you can type \lq, followed by a space if the next character is a letter, or followed by a \ if the next character is a space. Similarly, \rq yields a right-quote character. Is that clear? \lq\lqÃIÃunderstand.\rq\rq\Ã Ä In case you need to type quotes within quotes, for example a single quote followed by a double quote, you can’t simply type ’’’ because TEX will interpret this as ”’ (namely, double quote followed by single quote). If you have already read Chapter 5, you might expect that the solution will be to use grouping—namely, to type something like {’}’’. But it turns out that this doesn’t produce the desired result, because there is usually less space following a single right quote than there is following a double right quote: What you get is ’”, which is indeed a single quote followed by a double quote (if you look at it closely enough), but it looks almost like three equally spaced single quotes. On the other hand, you certainly won’t want to type ’Ã’’, because that space is much too large—it’s just as large as the space between words—and TEX might even start a new line at such a space when making up a paragraph! The solution is to type ’\thinspace’’, which produces ’ ” as desired. Ä x EXERCISE 2.4 Ä x EXERCISE 2.5 OK, now you know how to produce ”’ and ’ ”; how do you get “ ‘ and ‘“ ? Why do you think the author introduced the control sequence \thinspace to solve the adjacent-quotes problem, instead of recommending the trickier construction ’$\,$’’ (which also works)? In modern Wit all printed Trash, is Set off with num’rous Breaks and Dashes — JONATHAN SWIFT, On Poetry: A Rapsody (1733) Some compositors still object to work in offices where type-composing machines are introduced. — WILLIAM STANLEY JEVONS, Political Economy (1878) 5 (page 6) 3 Controlling TEX Chapter 3: Controlling TEX Your keyboard has very few keys compared to the large number of symbols that you may want to specify. In order to make a limited keyboard sufficiently versatile, one of the characters that you can type is reserved for special use, and it is called the escape character. Whenever you want to type something that controls the format of your manuscript, or something that doesn’t use the keyboard in the ordinary way, you should type the escape character followed by an indication of what you want to do. Note: Some computer terminals have a key marked ‘ESC’, but that is not your escape character! It is a key that sends a special message to the operating system, so don’t confuse it with what this manual calls “escape.” TEX allows any character to be used for escapes, but the “backslash” character ‘\’ is usually adopted for this purpose, since backslashes are reasonably convenient to type and they are rarely needed in ordinary text. Things work out best when different TEX users do things consistently, so we shall escape via backslashes in all the examples of this manual. Immediately after typing ‘\’ (i.e., immediately after an escape character) you type a coded command telling TEX what you have in mind. Such commands are called control sequences. For example, you might type \input MS which (as we will see later) causes TEX to begin reading a file called ‘MS.tex’; the string of characters ‘\input’ is a control sequence. Here’s another example: George P\’olya and Gabor Szeg\"o. TEX converts this to ‘George P´olya and Gabor Szeg¨o.’ There are two control sequences, \’ and \", here; these control sequences have been used to place accents over some of the letters. Control sequences come in two flavors. The first kind, like \input, is called a control word; it consists of an escape character followed by one or more letters, followed by a space or by something besides a letter. (TEX has to know where the control sequence ends, so you must put a space after a control word if the next character is a letter. For example, if you type ‘\inputMS’, TEX will naturally interpret this as a control word with seven letters.) In case you’re wondering what a “letter” is, the answer is that TEX normally regards the 52 symbols A...Z and a...z as letters. The digits 0...9 are not considered to be letters, so they don’t appear in control sequences of the first kind. A control sequence of the other kind, like \’, is called a control symbol; it consists of the escape character followed by a single nonletter. In this case you don’t need a space to separate the control sequence from a letter that follows, since control sequences of the second kind always have exactly one symbol after the escape character. x EXERCISE 3.1 What are the control sequences in ‘\I’m \exercise3.1\\!’ ? 7 8 Chapter 3: Controlling TEX x EXERCISE 3.2 We’ve seen that the input P\’olya yields ‘P´olya’. Can you guess how the French words ‘math´ematique’ and ‘centimetre’ should be specified? When a space comes after a control word (an all-letter control sequence), it is ignored by TEX; i.e., it is not considered to be a “real” space belonging to the manuscript that is being typeset. But when a space comes after a control symbol, it’s truly a space. Now the question arises, what do you do if you actually want a space to appear after a control word? We will see later that TEX treats two or more consecutive spaces as a single space, so the answer is not going to be “type two spaces.” The correct answer is to type “control space,” namely \Ã (the escape character followed by a blank space); TEX will treat this as a space that is not to be ignored. Notice that control-space is a control sequence of the second kind, i.e., a control symbol, since there is a single nonletter (Ã) following the escape character. Two consecutive spaces are considered to be equivalent to a single space, so further spaces immediately following \Ã will be ignored. But if you want to enter, say, three consecutive spaces into a manuscript you can type ‘\Ã\Ã\Ã’. Incidentally, typists are often taught to put two spaces at the ends of sentences; but we will see later that TEX has its own way to produce extra space in such cases. Thus you needn’t be consistent in the number of spaces you type. Ä Nonprinting control characters like hreturni might follow an escape character, and these lead to distinct control sequences according to the rules. TEX is initially set up to treat \hreturni and \htabi the same as \Ã (control space); these special control sequences should probably not be redefined, because you can’t see the difference between them when you look at them in a file. It is usually unnecessary for you to use “control space,” since control sequences aren’t often needed at the ends of words. But here’s an example that might shed some light on the matter: This manual itself has been typeset by TEX, and one of the things that occurs fairly often is the tricky logo ‘TEX’, which requires backspacing and lowering the E. There’s a special control word \TeX that produces the half-dozen or so instructions necessary to typeset ‘TEX’. When a phrase like ‘TEX ignores spaces after control words.’ is desired, the manuscript renders it as follows: \TeX\ ignores spaces after control words. Notice the extra \ following \TeX; this produces the control space that is necessary because TEX ignores spaces after control words. Without this extra \, the result would have been TEXignores spaces after control words. Chapter 3: Controlling TEX On the other hand, you can’t simply put \ after \TeX in all contexts. For example, consider the phrase the logo ‘\TeX’. In this case an extra backslash doesn’t work at all; in fact, you get a curious result if you type the logo ‘\TeX\’. Can you guess what happens? Answer: The \’ is a control sequence denoting an acute accent, as in our P\’olya example above; the effect is therefore to put an accent over the next nonblank character, which happens to be a period. In other words, you get an accented period, and the result is the logo ‘TEX´. Computers are good at following instructions, but not at reading your mind. TEX understands about 900 control sequences as part of its built-in vocabulary, and all of them are explained in this manual somewhere. But you needn’t worry about learning so many different things, because you won’t really be needing very many of them unless you are faced with unusually complicated copy. Furthermore, the ones you do need to learn actually fall into relatively few categories, so they can be assimilated without great difficulty. For example, many of the control sequences are simply the names of special characters used in math formulas; you type ‘\pi’ to get ‘π’, ‘\Pi’ to get ‘Π’, ‘\aleph’ to get ‘ℵ’, ‘\infty’ to get ‘∞’, ‘\le’ to get ‘≤’, ‘\ge’ to get ‘≥’, ‘\ne’ to get ‘6=’, ‘\oplus’ to get ‘⊕’, ‘\otimes’ to get ‘⊗’. Appendix F contains several tables of such symbols. Ä There’s no built-in relationship between uppercase and lowercase letters in control sequence names. For example, ‘\pi’ and ‘\Pi’ and ‘\PI’ and ‘\pI’ are four different control words. The 900 or so control sequences that were just mentioned actually aren’t the whole story, because it’s easy to define more. For example, if you want to substitute your own favorite names for math symbols, so that you can remember them better, you’re free to go right ahead and do it; Chapter 20 explains how. About 300 of TEX’s control sequences are called primitive; these are the low-level atomic operations that are not decomposable into simpler functions. All other control sequences are defined, ultimately, in terms of the primitive ones. For example, \input is a primitive operation, but \’ and \" are not; the latter are defined in terms of an \accent primitive. People hardly ever use TEX’s primitive control sequences in their manuscripts, because the primitives are . . . well . . . so primitive. You have to type a lot of instructions when you are trying to make TEX do low-level things; this takes time and invites mistakes. It is generally better to make use of higher-level control sequences that state what functions are desired, instead of typing out the way to achieve each function each time. The higher-level control sequences 9 10 Chapter 3: Controlling TEX need to be defined only once in terms of primitives. For example, \TeX is a control sequence that means “typeset the TEX logo”; \’ is a control sequence that means “put an acute accent over the next character”; and both of these control sequences might require different combinations of primitives when the style of type changes. If TEX’s logo were to change, the author would simply have to change one definition, and the changes would appear automatically wherever they were needed. By contrast, an enormous amount of work would be necessary to change the logo if it were specified as a sequence of primitives each time. At a still higher level, there are control sequences that govern the overall format of a document. For example, in the present book the author typed ‘\exercise’ just before stating each exercise; this \exercise command was programmed to make TEX do all of the following things: compute the exercise number (e.g., ‘3.2’ for the second exercise in Chapter 3); typeset ‘ x EXERCISE 3.2’ with the appropriate typefaces, on a line by itself, and with the triangle sticking out in the left margin; leave a little extra space just before that line, or begin a new page at that line if appropriate; prohibit beginning a new page just after that line; suppress indentation on the following line. It is obviously advantageous to avoid typing all of these individual instructions each time. And since the manual is entirely described in terms of high-level control sequences, it could be printed in a radically different format simply by changing a dozen or so definitions. Ä How can a person distinguish a TEX primitive from a control sequence that has been defined at a higher level? There are two ways: (1) The index to this manual lists all of the control sequences that are discussed, and each primitive is marked with an asterisk. (2) You can display the meaning of a control sequence while running TEX. If you type ‘\show\cs’ where \cs is any control sequence, TEX will respond with its current meaning. For example, ‘\show\input’ results in ‘> \input=\input.’, because \input is primitive. On the other hand, ‘\show\thinspace’ yields > \thinspace=macro: ->\kern .16667em . This means that \thinspace has been defined as an abbreviation for ‘\kern .16667em ’. By typing ‘\show\kern’ you can verify that \kern is primitive. The results of \show appear on your terminal and in the log file that you get after running TEX. Ä x EXERCISE 3.3 Which of the control sequences \Ã and \hreturni is primitive? In the following chapters we shall frequently discuss “plain TEX” format, which is a set of about 600 basic control sequences that are defined in Appendix B. These control sequences, together with the 300 or so primitives, Chapter 3: Controlling TEX are usually present when TEX begins to process a manuscript; that is why TEX claims to know roughly 900 control sequences when it starts. We shall see how plain TEX can be used to create documents in a flexible format that meets many people’s needs, using some typefaces that come with the TEX system. However, you should keep in mind that plain TEX is only one of countless formats that can be designed on top of TEX’s primitives; if you want some other format, it will usually be possible to adapt TEX so that it will handle whatever you have in mind. The best way to learn is probably to start with plain TEX and to change its definitions, little by little, as you gain more experience. Ä Appendix E contains examples of formats that can be added to Appendix B for special applications; for example, there is a set of definitions suitable for business correspondence. A complete specification of the format used to typeset this manual also appears in Appendix E. Thus, if your goal is to learn how to design TEX formats, you will probably want to study Appendix E while mastering Appendix B. After you have become skilled in the lore of control-sequence definition, you will probably have developed some formats that other people will want to use; you should then write a supplement to this manual, explaining your style rules. The main point of these remarks, as far as novice TEX users are concerned, is that it is indeed possible to define nonstandard TEX control sequences. When this manual says that something is part of “plain TEX,” it means that TEX doesn’t insist on doing things exactly that way; a person could change the rules by changing one or more of the definitions in Appendix B. But you can safely rely on the control sequences of plain TEX until you become an experienced TEXnical typist. Ä Äx EXERCISE 3.4 How many different control sequences of length 2 (including the escape character) are possible? How many of length 3? Syllables govern the world. — JOHN SELDEN, Table Talk (1689) I claim not to have controlled events, but confess plainly that events have controlled me. — ABRAHAM LINCOLN (1864) 11 (page 12) 4 Fonts of Type Chapter 4: Fonts of Type Occasionally you will want to change from one typeface to another, for example if you wish to be bold or to emphasize something. TEX deals with sets of up to 256 characters called “fonts” of type, and control sequences are used to select a particular font. For example, you could specify the last few words of the first sentence above in the following way, using the plain TEX format of Appendix B: to be \bf bold \rm or to \sl emphasize \rm something. Plain TEX provides the following control sequences for changing fonts: \rm \sl \it \tt \bf switches switches switches switches switches to to to to to the normal “roman” typeface: a slanted roman typeface: italic style: a typewriter-like face: an extended boldface style: Roman Slanted Italic Typewriter Bold At the beginning of a run you get roman type (\rm) unless you specify otherwise. Notice that two of these faces have an “oblique” slope for emphasis: Slanted type is essentially the same as roman, but the letters are slightly skewed, while the letters in italic type are drawn in a different style. (You can perhaps best appreciate the difference between the roman and italic styles by contemplating letters that are in an unslanted italic face.) Typographic conventions are presently in a state of transition, because new technology has made it possible to do things that used to be prohibitively expensive; people are wrestling with the question of how much to use their new-found typographic freedom. Slanted roman type was introduced in the 1930s, but it first became widely used as an alternative to the conventional italic during the late 1970s. It can be beneficial in mathematical texts, since slanted letters are distinguishable from the italic letters in math formulas. The double use of italic type for two different purposes—for example, when statements of theorems are italicized as well as the names of variables in those theorems—has led to some confusion, which can now be avoided with slanted type. People are not generally agreed about the relative merits of slanted versus italic, but slanted type is rapidly becoming a favorite for the titles of books and journals in bibliographies. Special fonts are effective for emphasis, but not for sustained reading; your eyes would tire if long portions of this manual were entirely set in a bold or slanted or italic face. Therefore roman type accounts for the bulk of most typeset material. But it’s a nuisance to say ‘\rm’ every time you want to go back to the roman style, so TEX provides an easier way to do it, using “curly brace” symbols: You can switch fonts inside the special symbols { and }, without affecting the fonts outside. For example, the displayed phrase at the beginning of this chapter is usually rendered to be {\bf bold} or to {\sl emphasize} something. This is a special case of the general idea of “grouping” that we shall discuss in the next chapter. It’s best to forget about the first way of changing fonts, and 13 14 Chapter 4: Fonts of Type to use grouping instead; then your TEX manuscripts will look more natural, and you’ll probably never* have to type ‘\rm’. x EXERCISE 4.1 Explain how to type the bibliographic reference ‘Ulrich Dieter, Journal f¨ ur die reine und angewandte Mathematik 201 (1959), 37–70.’ [Use grouping.] We have glossed over an important aspect of quality in the preceding discussion. Look, for example, at the italicized and slanted words in this sentence. Since italic and slanted styles slope to the right, the d’s stick into the spaces that separate these words from the roman type that follows; as a result, the spaces appear to be too skimpy, although they are correct at the base of the letters. To equalize the effective white space, TEX allows you to put the special control sequence ‘\/’ just before switching back to unslanted letters. When you type {\it italicized\/} and {\sl slanted\/} words you get italicized and slanted words that look better. The ‘\/’ tells TEX to add an “italic correction” to the previous letter, depending on that letter; this correction is about four times as much for an ‘f ’ as for a ‘c’, in a typical italic font. Sometimes the italic correction is not desirable, because other factors take up the visual slack. The standard rule of thumb is to use \/ just before switching from slanted or italic to roman or bold, unless the next character is a period or comma. For example, type {\it italics\/} for {\it emphasis}. Old manuals of style say that the punctuation after a word should be in the same font as that word; but an italic semicolon often looks wrong, so this convention is changing. When an italicized word occurs just before a semicolon, the author recommends typing ‘{\it word\/};’. x EXERCISE 4.2 Explain how to typeset a roman word in the midst of an italicized sentence. Ä Every letter of every font has an italic correction, which you can bring to life by typing \/. The correction is usually zero in unslanted styles, but there are exceptions: To typeset a bold ‘f ’ in quotes, you should say a bold ‘{\bf f\/}’, lest you get a bold ‘f’. Ä Äx EXERCISE 4.3 Define a control sequence \ic such that ‘\ic c’ puts the italic correction of character c into TEX’s register \dimen0. Ä Ä The primitive control sequence \nullfont stands for a font that has no characters. This font is always present, in case you haven’t specified any others. * Well . . . , hardly ever. Chapter 4: Fonts of Type Fonts vary in size as well as in shape. For example, the font you are now reading is called a “10-point” font, because certain features of its design are 10 points apart, when measured in printers’ units. (We will study the point system later; for now, it should suffice to point out that the parentheses around this sentence are exactly 10 points tall—and the em-dash is just 10 points wide.) The “dangerous bend” sections of this manual are set in 9-point type, the footnotes in 8-point, subscripts in 7-point or 6-point, sub-subscripts in 5-point. Each font used in a TEX manuscript is associated with a control sequence; for example, the 10-point font in this paragraph is called \tenrm, and the corresponding 9-point font is called \ninerm. The slanted fonts that match \tenrm and \ninerm are called \tensl and \ninesl. These control sequences are not built into TEX, nor are they the actual names of the fonts; TEX users are just supposed to make up convenient names, whenever new fonts are introduced into a manuscript. Such control sequences are used to change typefaces. When fonts of different sizes are used simultaneously, TEX will line the letters up according to their “baselines.” For example, if you type \tenrm smaller \ninerm and smaller \eightrm and smaller \sevenrm and smaller \sixrm and smaller \fiverm and smaller \tenrm the result is smaller and smaller and smaller and smaller and smaller and smaller. Of course this is something that authors and readers aren’t accustomed to, because printers couldn’t do such things with traditional lead types. Perhaps poets who wish to speak in a still small voice will cause future books to make use of frequent font variations, but nowadays it’s only an occasional font freak (like the author of this manual) who likes such experiments. One should not get too carried away by the prospect of font switching unless there is good reason. An alert reader might well be confused at this point because we started out this chapter by saying that ‘\rm’ is the command that switches to roman type, but later on we said that ‘\tenrm’ is the way to do it. The truth is that both ways work. But it has become customary to set things up so that \rm means “switch to roman type in the current size” while \tenrm means “switch to roman type in the 10-point size.” In plain TEX format, nothing but 10-point fonts are provided, so \rm will always get you \tenrm; but in more complicated formats the meaning of \rm will change in different parts of the manuscript. For example, in the format used by the author to typeset this manual, there’s a control sequence ‘\tenpoint’ that causes \rm to mean \tenrm, \sl to mean \tensl, and so on, while ‘\ninepoint’ changes the definitions so that \rm means \ninerm, etc. There’s another control sequence used to introduce the quotations at the end of each chapter; when the quotations are typed, \rm and \sl temporarily stand for 8-point unslanted sans-serif type and 8-point slanted sans-serif type, respectively. This device of constantly redefining the abbreviations \rm and \sl, behind the scenes, frees the typist from the need to remember what size or style of type is currently being used. 15 16 Chapter 4: Fonts of Type x EXERCISE 4.4 Why do you think the author chose the names ‘\tenpoint’ and ‘\tenrm’, etc., instead of ‘\10point’ and ‘\10rm’ ? Ä x EXERCISE 4.5 Suppose that you have typed a manuscript using slanted type for emphasis, but your editor suddenly tells you to change all the slanted to italic. What’s an easy way to do this? Ä Each font has an external name that identifies it with respect to all other fonts in a particular library. For example, the font in this sentence is called ‘cmr9’, which is an abbreviation for “Computer Modern Roman 9 point.” In order to prepare TEX for using this font, the command \font\ninerm=cmr9 appears in Appendix E. In general you say ‘\font\cs=hexternal font namei’ to load the information about a particular font into TEX’s memory; afterwards the control sequence \cs will select that font for typesetting. Plain TEX makes only sixteen fonts available initially (see Appendix B and Appendix F), but you can use \font to access anything that exists in your system’s font library. Ä It is often possible to use a font at several different sizes, by magnifying or shrinking the character images. Each font has a so-called design size, which reflects the size it normally has by default; for example, the design size of cmr9 is 9 points. But on many systems there is also a range of sizes at which you can use a particular font, by scaling its dimensions up or down. To load a scaled font into TEX’s memory, you simply say ‘\font\cs=hexternal font namei at hdesired sizei’. For example, the command \font\magnifiedfiverm=cmr5 at 10pt brings in 5-point Computer Modern Roman at twice its normal size. (Caution: Before using this ‘at’ feature, you should check to make sure that your typesetter supports the font at the size in question; TEX will accept any hdesired sizei that is positive and less than 2048 points, but the final output will not be right unless the scaled font really is available on your printing device.) Ä What’s the difference between cmr5 at 10pt and the normal 10-point font, cmr10? Plenty; a well-designed font will be drawn differently at different point sizes, and the letters will often have different relative heights and widths, in order to enhance readability. Ten point type is different from magnified five-point type. It is usually best to scale fonts only slightly with respect to their design size, unless the final product is going to be photographically reduced after TEX has finished with it, or unless you are trying for an unusual effect. Ä Another way to magnify a font is to specify a scale factor that is relative to the design size. For example, the command \font\magnifiedfiverm=cmr5 scaled 2000 Chapter 4: Fonts of Type is another way to bring in the font cmr5 at double size. The scale factor is specified as an integer that represents a magnification ratio times 1000. Thus, a scale factor of 1200 specifies magnification by 1.2, etc. Ä x EXERCISE 4.6 State two ways to load font cmr10 into TEX’s memory at half its normal size. Ä At many computer centers it has proved convenient to supply fonts at magnifications that grow in geometric ratios—something like well-tempered tuning on a piano. The idea is to have all fonts available at their true size as well as at magnifications 1.2 and 1.44 (which is 1.2 × 1.2); perhaps also at magnification 1.728 (= 1.2 × 1.2 × 1.2) and even higher. Then you can magnify an entire document by 1.2 or 1.44 and still stay within the set of available fonts. Plain TEX provides the abbreviations \magstep0 for a scale factor of 1000, \magstep1 for a scaled factor of 1200, \magstep2 for 1440, and so on up to \magstep5. You say, for example, \font\bigtenrm=cmr10 scaled\magstep2 to load font cmr10 at 1.2 × 1.2 times its normal size. “This is cmr10 at normal size (\magstep0).” “This is cmr10 scaled once by 1.2 (\magstep1).” “This is cmr10 scaled twice by 1.2 (\magstep2).” (Notice that a√little magnification goes a long way.) There’s also \magstephalf, which magnifies by 1.2, i.e., halfway between steps 0 and 1. Ä Chapter 10 explains how to apply magnification to an entire document, over and above any magnification that has been specified when fonts are loaded. For example, if you have loaded a font that is scaled by \magstep1 and if you also specify \magnification=\magstep2, the actual font used for printing will be scaled by \magstep3. Similarly, if you load a font scaled by \magstephalf and if you also say \magnification=\magstephalf, the printed results will be scaled by \magstep1. Type faces—like people’s faces—have distinctive features indicating aspects of character. — MARSHALL LEE, Bookmaking (1965) This was the Noblest Roman of them all. — WILLIAM SHAKESPEARE, The Tragedie of Julius Cæsar (1599) 17 (page 18) 5 Grouping Chapter 5: Grouping Every once in a while it is necessary to treat part of a manuscript as a unit, so you need to indicate somehow where that part begins and where it ends. For this purpose TEX gives special interpretation to two “grouping characters,” which (like the escape character) are treated differently from the normal symbols that you type. We assume in this manual that { and } are the grouping characters, since they are the ones used in plain TEX. We saw examples of grouping in the previous chapter, where it was mentioned that font changes inside a group do not affect the fonts in force outside. The same principle applies to almost anything else that is defined inside a group, as we will see later; for example, if you define a control sequence within some group, that definition will disappear when the group ends. In this way you can conveniently instruct TEX to do something unusual, by changing its normal conventions temporarily inside of a group; since the changes are invisible from outside the group, there is no need to worry about messing up the rest of a manuscript by forgetting to restore the normal conventions when the unusual construction has been finished. Computer scientists have a name for this aspect of grouping, because it’s an important aspect of programming languages in general; they call it “block structure,” and definitions that are in force only within a group are said to be “local” to that group. You might want to use grouping even when you don’t care about block structure, just to have better control over spacing. For example, let’s consider once more the control sequence \TeX that produces the logo ‘TEX’ in this manual: We observed in Chapter 3 that a blank space after this control sequence will be gobbled up unless one types ‘\TeX\ ’, yet it is a mistake to say ‘\TeX\’ when the following character is not a blank space. Well, in all cases it would be correct to specify the simple group {\TeX} whether or not the following character is a space, because the } stops TEX from absorbing an optional space into \TeX. This might come in handy when you’re using a text editor (e.g., when replacing all occurrences of a particular word by a control sequence). Another thing you could do is type \TeX{} using an empty group for the same purpose: The ‘{}’ here is a group of no characters, so it produces no output, but it does have the effect of stopping TEX from skipping blanks. x EXERCISE 5.1 Sometimes you run into a rare word like ‘shelfful’ that looks better as ‘shelfful’ without the ‘ff’ ligature. How can you fool TEX into thinking that there aren’t two consecutive f’s in such a word? Ä x EXERCISE 5.2 Explain how to get three blank spaces in a row without using ‘\Ã’. 19 20 Chapter 5: Grouping But TEX also uses grouping for another, quite different, purpose, namely to determine how much of your text is to be governed by certain control sequences. For example, if you want to center something on a line you can type \centerline{This information should be centered.} using the control sequence \centerline defined in plain TEX format. Grouping is used in quite a few of TEX’s more intricate instructions; and it’s possible to have groups within groups within groups, as you can see by glancing at Appendix B. Complex grouping is generally unnecessary, however, in ordinary manuscripts, so you needn’t worry about it. Just don’t forget to finish each group that you’ve started, because a lost ‘}’ might cause trouble. Here’s an example of two groups, one nested inside the other: \centerline{This information should be {\it centered}.} As you might expect, TEX will produce a centered line that also contains italics: This information should be centered. But let’s look at the example more closely: ‘\centerline’ appears outside the curly braces, while ‘\it’ appears inside. Why are the two cases different? And how can a beginner learn to remember which is which? Answer: \centerline is a control sequence that applies only to the very next thing that follows, so you want to put braces around the text that is to be centered (unless that text consists of a single symbol or control sequence). For example, to center the TEX logo on a line, it would suffice to type ‘\centerline\TeX’, but to center the phrase ‘TEX has groups’ you need braces: ‘\centerline{\TeX\ has groups}’. On the other hand, \it is a control sequence that simply means “change the current font”; it acts without looking ahead, so it affects everything that follows, at least potentially. The braces surround \it in order to confine the font change to a local region. In other words, the two sets of braces in this example actually have different functions: One serves to treat several words of the text as if they were a single object, while the other provides local block structure. x EXERCISE 5.3 What do you think happens if you type the following: \centerline{This information should be {centered}.} \centerline So should this. x EXERCISE 5.4 And how about this one? \centerline{This information should be \it centered.} Ä x EXERCISE 5.5 Define a control sequence \ital so that a user could type ‘\ital{text}’ instead of ‘{\it text\/}’. Discuss the pros and cons of \ital versus \it. Chapter 5: Grouping Ä Ä Subsequent chapters describe many primitive operations of TEX for which the locality of grouping is important. For example, if one of TEX’s internal parameters is changed within a group, the previous contents of that parameter will be restored when the group ends. Sometimes, however, it’s desirable to make a definition that transcends its current group. This effect can be obtained by prefixing ‘\global’ to the definition. For example, TEX keeps the current page number in a register called \count0, and the routine that outputs a page wants to increase the page number. Output routines are always protected by enclosing them in groups, so that they do not inadvertently mess up the rest of TEX; but the change to \count0 would disappear if it were kept local to the output group. The command \global\advance\count0 by 1 solves the problem; it increases \count0 and makes this value stick around at the end of the output routine. In general, \global makes the immediately following definition pertain to all existing groups, not just to the innermost one. Ä Äx EXERCISE 5.6 If you think you understand local and global definitions, here’s a little test to make sure: Suppose \c stands for ‘\count1=’, \g stands for ‘\global\count1=’, and \s stands for ‘\showthe\count1’. What values will be shown? {\c1\s\g2{\s\c3\s\g4\s\c5\s}\s\c6\s}\s Ä Ä Another way to obtain block structure with TEX is to use the primitives \begingroup and \endgroup. These control sequences make it easy to begin a group within one control sequence and end it within another. The text that TEX actually executes, after control sequences have been expanded, must have properly nested groups, i.e., groups that don’t overlap. For example, { \begingroup } \endgroup is not legitimate. Ä Äx EXERCISE 5.7 Define control sequences \beginthehblock namei and \endthehblock namei that provide a “named” block structure. In other words, \beginthe{beguine}\beginthe{waltz}\endthe{waltz}\endthe{beguine} should be permissible, but not \beginthe{beguine}\beginthe{waltz}\endthe{beguine}\endthe{waltz}. I have had recourse to varieties of type, and to braces. — JAMES MUIRHEAD, The Institutes of Gaius (1880) An encounter group is a gathering, for a few hours or a few days, of twelve or eighteen personable, responsible, certifiably normal and temporarily smelly people. — JANE HOWARD, Please Touch (1970) 21 (page 22) 6 Running TEX Chapter 6: Running TEX The best way to learn how to use TEX is to use it. Thus, it’s high time for you to sit down at a computer terminal and interact with the TEX system, trying things out to see what happens. Here are some small but complete examples suggested for your first encounter. Caution: This chapter is rather a long one. Why don’t you stop reading now, and come back fresh tomorrow? OK, let’s suppose that you’re rested and excited about having a trial run of TEX. Step-by-step instructions for using it appear in this chapter. First do this: Go to the lab where the graphic output device is, since you will be wanting to see the output that you get—it won’t really be satisfactory to run TEX from a remote location, where you can’t hold the generated documents in your own hands. Then log in; and start TEX. (You may have to ask somebody how to do this on your local computer. Usually the operating system prompts you for a command and you type ‘TeX’ or ‘run tex’ or something like that.) When you’re successful, TEX will welcome you with a message such as This is TeX, Version 3.14 (preloaded format=plain 89.7.15) ** The ‘**’ is TEX’s way of asking you for an input file name. Now type ‘\relax’ (including the backslash), and hreturni (or whatever is used to mean “end-of-line” on your terminal). TEX is all geared up for action, ready to read a long manuscript; but you’re saying that it’s all right to take things easy, since this is going to be a real simple run. In fact, \relax is a control sequence that means “do nothing.” The machine will type another asterisk at you. This time type something like ‘Hello?’ and wait for another asterisk. Finally type ‘\end’, and stand back to see what happens. TEX should respond with ‘[1]’ (meaning that it has finished page 1 of your output); then the program will halt, probably with some indication that it has created a file called ‘texput.dvi’. (TEX uses the name texput for its output when you haven’t specified any better name in your first line of input; and dvi stands for “device independent,” since texput.dvi is capable of being printed on almost any kind of typographic output device.) Now you’re going to need some help again from your friendly local computer hackers. They will tell you how to produce hardcopy from texput.dvi. And when you see the hardcopy—Oh, glorious day!—you will see a magnificent ‘Hello?’ and the page number ‘1’ at the bottom. Congratulations on your first masterpiece of fine printing. The point is, you understand now how to get something through the whole cycle. It only remains to do the same thing with a somewhat longer document. So our next experiment will be to work from a file instead of typing the input online. 23 24 Chapter 6: Running TEX Use your favorite text editor to create a file called story.tex that contains the following 18 lines of text (no more, no less): 1 2 3 4 5 6 7 8 9 10 \hrule \vskip 1in \centerline{\bf A SHORT STORY} \vskip 6pt \centerline{\sl by A. U. Thor} \vskip .5cm Once upon a time, in a distant galaxy called \"O\"o\c c, there lived a computer named R.~J. Drofnats. 11 12 13 14 15 16 17 18 Mr.~Drofnats---or ‘‘R. J.,’’ as he preferred to be called--was happiest when he was at work typesetting beautiful documents. \vskip 1in \hrule \vfill\eject (Don’t type the numbers at the left of these lines, of course; they are present only for reference.) This example is a bit long, and more than a bit silly; but it’s no trick for a good typist like you and it will give you some worthwhile experience, so do it. For your own good. And think about what you’re typing, as you go; the example introduces a few important features of TEX that you can learn as you’re making the file. Here is a brief explanation of what you have just typed: Lines 1 and 17 put a horizontal rule (a thin line) across the page. Lines 2 and 16 skip past one inch of space; ‘\vskip’ means “vertical skip,” and this extra space will separate the horizontal rules from the rest of the copy. Lines 3 and 5 produce the title and the author name, centered, in boldface and in slanted type. Lines 4 and 6 put extra white space between those lines and their successors. (We shall discuss units of measure like ‘6pt’ and ‘.5cm’ in Chapter 10.) The main bulk of the story appears on lines 7–15, and it consists of two paragraphs. The fact that line 11 is blank informs TEX that line 10 is the end of the first paragraph; and the ‘\vskip’ on line 16 implies that the second paragraph ends on line 15, because vertical skips don’t appear in paragraphs. Incidentally, this example seems to be quite full of TEX commands; but it is atypical in that respect, because it is so short and because it is supposed to be teaching things. Messy constructions like \vskip and \centerline can be expected at the very beginning of a manuscript, unless you’re using a canned format, but they don’t last long; most of the time you will find yourself typing straight text, with relatively few control sequences. Chapter 6: Running TEX And now comes the good news, if you haven’t used computer typesetting before: You don’t have to worry about where to break lines in a paragraph (i.e., where to stop at the right margin and to begin a new line), because TEX will do that for you. Your manuscript file can contain long lines or short lines, or both; it doesn’t matter. This is especially helpful when you make changes, since you don’t have to retype anything except the words that changed. Every time you begin a new line in your manuscript file it is essentially the same as typing a space. When TEX has read an entire paragraph—in this case lines 7 to 11—it will try to break up the text so that each line of output, except the last, contains about the same amount of copy; and it will hyphenate words if necessary to keep the spacing consistent, but only as a last resort. Line 8 contains the strange concoction \"O\"o\c c and you already know that \" stands for an umlaut accent. The \c stands for a ¨ oc¸’ as the name of that distant galaxy. “cedilla,” so you will get ‘O¨ The remaining text is simply a review of the conventions that we discussed long ago for dashes and quotation marks, except that the ‘~’ signs in lines 10 and 12 are a new wrinkle. These are called ties, because they tie words together; i.e., TEX is supposed to treat ‘~’ as a normal space but not to break between lines there. A good typist will use ties within names, as shown in our example; further discussion of ties appears in Chapter 14. Finally, line 18 tells TEX to ‘\vfill’, i.e., to fill the rest of the page with white space; and to ‘\eject’ the page, i.e., to send it to the output file. Now you’re ready for Experiment 2: Get TEX going again. This time when the machine says ‘**’ you should answer ‘story’, since that is the name of the file where your input resides. (The file could also be called by its full name ‘story.tex’, but TEX automatically supplies the suffix ‘.tex’ if no suffix has been specified.) You might wonder why the first prompt was ‘**’, while the subsequent ones are ‘*’; the reason is simply that the first thing you type to TEX is slightly different from the rest: If the first character of your response to ‘**’ is not a backslash, TEX automatically inserts ‘\input’. Thus you can usually run TEX by merely naming your input file. (Previous TEX systems required you to start by typing ‘\input story’ instead of ‘story’, and you can still do that; but most TEX users prefer to put all of their commands into a file instead of typing them online, so TEX now spares them the nuisance of starting out with \input each time.) Recall that in Experiment 1 you typed ‘\relax’; that started with a backslash, so \input was not implied. Ä There’s actually another difference between ‘**’ and ‘*’: If the first character after ** is an ampersand ( ‘&’ ), TEX will replace its memory with a precomputed format file before proceeding. Thus, for example, you can type ‘&plain \input story’ or even ‘&plain story’ in response to ‘**’, if you are running some version of TEX that might not have the plain format preloaded. 25 26 Chapter 6: Running TEX Ä Incidentally, many systems allow you to invoke TEX by typing a one-liner like ‘tex story’ instead of waiting for the ‘**’; similarly, ‘tex \relax’ works for Experiment 1, and ‘tex &plain story’ loads the plain format before inputting the story file. You might want to try this, to see if it works on your computer, or you might ask somebody if there’s a similar shortcut. As TEX begins to read your story file, it types ‘(story.tex’, possibly with a version number for more precise identification, depending on your local operating system. Then it types ‘[1]’, meaning that page 1 is done; and ‘)’, meaning that the file has been entirely input. TEX will now prompt you with ‘*’, because the file did not contain ‘\end’. Enter \end into the computer now, and you should get a file story.dvi containing a typeset version of Thor’s story. As in Experiment 1, you can proceed to convert story.dvi into hardcopy; go ahead and do that now. The typeset output won’t be shown here, but you can see the results by doing the experiment personally. Please do so before reading on. x EXERCISE 6.1 Statistics show that only 7.43 of 10 people who read this manual actually type the story.tex file as recommended, but that those people learn TEX best. So why don’t you join them? x EXERCISE 6.2 Look closely at the output of Experiment 2, and compare it to story.tex : If you followed the instructions carefully, you will notice a typographical error. What is it, and why did it sneak in? With Experiment 2 under your belt, you know how to make a document from a file. The remaining experiments in this chapter are intended to help you cope with the inevitable anomalies that you will run into later; we will intentionally do things that will cause TEX to “squeak.” But before going on, it’s best to fix the error revealed by the previous output (see exercise 6.2): Line 13 of the story.tex file should be changed to he preferred to be called---% error has been fixed! The ‘%’ sign here is a feature of plain TEX that we haven’t discussed before: It effectively terminates a line of your input file, without introducing the blank space that TEX ordinarily inserts when moving to the next line of input. Furthermore, TEX ignores everything that you type following a %, up to the end of that line in the file; you can therefore put comments into your manuscript, knowing that the comments are for your eyes only. Experiment 3 will be to make TEX work harder, by asking it to set the story in narrower and narrower columns. Here’s how: After starting the program, type \hsize=4in \input story Chapter 6: Running TEX 27 in response to the ‘**’. This means, “Set the story in a 4-inch column.” More precisely, \hsize is a primitive of TEX that specifies the horizontal size, i.e., the width of each normal line in the output when a paragraph is being typeset; and \input is a primitive that causes TEX to read the specified file. Thus, you are instructing the machine to change the normal setting of \hsize that was defined by plain TEX, and then to process story.tex under this modification. TEX should respond by typing something like ‘(story.tex [1])’ as before, followed by ‘*’. Now you should type \hsize=3in \input story and, after TEX says ‘(story.tex [2])’ asking for more, type three more lines \hsize=2.5in \input story \hsize=2in \input story \end to complete this four-page experiment. Don’t be alarmed when TEX screams ‘Overfull \hbox’ several times as it works at the 2-inch size; that’s what was supposed to go wrong during Experiment 3. There simply is no good way to break the given paragraphs into lines that are exactly two inches wide, without making the spaces between words come out too large or too small. Plain TEX has been set up to ensure rather strict tolerances on all of the lines it produces: you don’t get spaces between words narrower than this, and you don’t get spaces between words wider than this. If there’s no way to meet these restrictions, you get an overfull box. And with the overfull box you also get (1) a warning message, printed on your terminal, and (2) a big black bar inserted at the right of the offending box, in your output. (Look at page 4 of the output from Experiment 3; the overfull boxes should stick out like sore thumbs. On the other hand, pages 1–3 should be perfect.) Of course you don’t want overfull boxes in your output, so TEX provides several ways to remove them; that will be the subject of our Experiment 4. But first let’s look more closely at the results of Experiment 3, since TEX reported some potentially valuable information when it was forced to make those boxes too full; you should learn how to read this data: Overfull \hbox (0.98807pt too wide) in paragraph at lines 7--11 \tenrm tant galaxy called []O^^?o^^Xc, there lived| Overfull \hbox (0.4325pt too wide) in paragraph at lines 7--11 \tenrm a com-puter named R. J. Drof-nats. | Overfull \hbox (5.32132pt too wide) in paragraph at lines 12--16 \tenrm he pre-ferred to be called---was hap-| Each overfull box is correlated with its location in your input file (e.g., the first two were generated when processing the paragraph on lines 7–11 of story.tex), and you also learn by how much the copy sticks out (e.g., 0.98807 points). 28 Chapter 6: Running TEX Notice that TEX also shows the contents of the overfull boxes in abbreviated form. For example, the last one has the words ‘he preferred to be called—was hap-’, set in font \tenrm (10-point roman type); the first one has ¨ oc¸’, because the accents appear in strange a somewhat curious rendering of ‘O¨ places within that font. In general, when you see ‘[]’ in one of these messages, it stands either for the paragraph indentation or for some sort of complex construction; in this particular case it stands for an umlaut that has been raised up to cover an ‘O’. Ä x EXERCISE 6.3 Can you explain the ‘|’ that appears after ‘lived’ in that message? Ä Äx EXERCISE 6.4 Why is there a space before the ‘|’ in ‘Drof-nats. |’ ? You don’t have to take out pencil and paper in order to write down the overfull box messages that you get before they disappear from view, since TEX always writes a “transcript” or “log file” that records what happened during each session. For example, you should now have a file called story.log containing the transcript of Experiment 3, as well as a file called texput.log containing the transcript of Experiment 1. (The transcript of Experiment 2 was probably overwritten when you did number 3.) Take a look at story.log now; you will see that the overfull box messages are accompanied not only by the abbreviated box contents, but also by some strange-looking data about hboxes and glue and kerns and such things. This data gives a precise description of what’s in that overfull box; TEX wizards will find such listings important, if they are called upon to diagnose some mysterious error, and you too may want to understand TEX’s internal code some day. The abbreviated forms of overfull boxes show the hyphenations that TEX tried before it resorted to overfilling. The hyphenation algorithm, which is described in Appendix H, is excellent but not perfect; for example, you can see from the messages in story.log that TEX finds the hyphen in ‘pre-ferred’, and it can even hyphenate ‘Drof-nats’. Yet it discovers no hyphen in ‘galaxy’, and every once in a while an overfull box problem can be cured simply by giving TEX a hint about how to hyphenate some word more completely. (We will see later that there are two ways to do this, either by inserting discretionary hyphens each time as in ‘gal\-axy’, or by saying ‘\hyphenation{gal-axy}’ once at the beginning of your manuscript.) In the present example, hyphenation is not a problem, since TEX found and tried all the hyphens that could possibly have helped. The only way to get rid of the overfull boxes is to change the tolerance, i.e., to allow wider spaces between words. Indeed, the tolerance that plain TEX uses for wide lines is completely inappropriate for 2-inch columns; such narrow columns simply can’t be achieved without loosening the constraints, unless you rewrite the copy to fit. TEX assigns a numerical value called “badness” to each line that it sets, in order to assess the quality of the spacing. The exact rules for badness are Chapter 6: Running TEX different for different fonts, and they will be discussed in Chapter 14; but here is the way badness works for the roman font of plain TEX: The badness of this line is 100. The badness of this line is 12. The badness of this line is 0. The badness of this line is 12. The badness of this line is 200. The badness of this line is 1000. The badness of this line is 5000. (very tight) (somewhat tight) (perfect) (somewhat loose) (loose) (bad) (awful) Plain TEX normally stipulates that no line’s badness should exceed 200; but in our case, the task would be impossible since ¨ oc¸, there’ ‘tant galaxy called O¨ has badness 1521; ‘he preferred to be called—was’ has badness 568. So we turn now to Experiment 4, in which spacing variations that are more appropriate to narrow columns will be used. Run TEX again, and begin this time by saying \hsize=2in \tolerance=1600 \input story so that lines with badness up to 1600 will be tolerated. Hurray! There are no overfull boxes this time. (But you do get a message about an underfull box, since TEX reports all boxes whose badness exceeds a certain threshold called \hbadness; plain TEX sets \hbadness=1000.) Now make TEX work still harder by trying \hsize=1.5in \input story (thus leaving the tolerance at 1600 but making the column width still skimpier). Alas, overfull boxes return; so try typing \tolerance=10000 \input story in order to see what happens. TEX treats 10000 as if it were “infinite” tolerance, allowing arbitrarily wide space; thus, a tolerance of 10000 will never produce an overfull box, unless something strange occurs like an unhyphenatable word that is wider than the column itself. The underfull box that TEX produces in the 1.5-inch case is really bad; with such narrow limits, an occasional wide space is unavoidable. But try \raggedright \input story for a change. (This tells TEX not to worry about keeping the right margin straight, and to keep the spacing uniform within each line.) Finally, type \hsize=.75in \input story followed by ‘\end’, to complete Experiment 4. This makes the columns almost impossibly narrow. 29 30 Chapter 6: Running TEX Ä The output from this experiment will give you some feeling for the problem of breaking a paragraph into approximately equal lines. When the lines are relatively wide, TEX will almost always find a good solution. But otherwise you will have to figure out some compromise, and several options are possible. Suppose you want to ensure that no lines have badness exceeding 500. Then you could set \tolerance to some high number, and \hbadness=500; TEX would not produce overfull boxes, but it would warn you about the underfull ones. Or you could set \tolerance=500; then TEX might produce overfull boxes. If you really want to take corrective action, the second alternative is better, because you can look at an overfull box to see how much sticks out; it becomes graphically clear what remedies are possible. On the other hand, if you don’t have time to fix bad spacing—if you just want to know how bad it is—then the first alternative is better, although it may require more computer time. Ä x EXERCISE 6.5 When \raggedright has been specified, badness reflects the amount of space at the right margin, instead of the spacing between words. Devise an experiment by which you can easily determine what badness TEX assigns to each line, when the story is set ragged-right in 1.5-inch columns. Ä A parameter called \hfuzz allows you to ignore boxes that are only slightly overfull. For example, if you say \hfuzz=1pt, a box must stick out more than one point before it is considered erroneous. Plain TEX sets \hfuzz=0.1pt. Ä Äx EXERCISE 6.6 Inspection of the output from Experiment 4, especially page 3, shows that with narrow columns it would be better to allow white space to appear before and after a dash, whenever other spaces in the same line are being stretched. Define a \dash macro that does this. You were warned that this is a long chapter. But take heart: There’s only one more experiment to do, and then you will know enough about TEX to run it fearlessly by yourself forever after. The only thing you are still missing is some information about how to cope with error messages—i.e., not just with warnings about things like overfull boxes, but with cases where TEX actually stops and asks you what to do next. Error messages can be terrifying when you aren’t prepared for them; but they can be fun when you have the right attitude. Just remember that you really haven’t hurt the computer’s feelings, and that nobody will hold the errors against you. Then you’ll find that running TEX might actually be a creative experience instead of something to dread. The first step in Experiment 5 is to plant two intentional mistakes in the story.tex file. Change line 3 to \centerline{\bf A SHORT \ERROR STORY} and change ‘\vskip’ to ‘\vship’ on line 2. Now run TEX again; but instead of ‘story’ type ‘sorry’. The computer should respond by saying that it can’t find file sorry.tex, and it will ask you to try again. Just hit hreturni this time; you’ll see that you had better give the Chapter 6: Running TEX name of a real file. So type ‘story’ and wait for TEX to find one of the faux pas in that file. Ah yes, the machine will soon stop,* after typing something like this: ! Undefined control sequence. l.2 \vship 1in ? TEX begins its error messages with ‘!’, and it shows what it was reading at the time of the error by displaying two lines of context. The top line of the pair (in this case ‘\vship’ ) shows what TEX has looked at so far, and where it came from (‘l.2’, i.e., line number 2); the bottom line (in this case ‘1in’ ) shows what TEX has yet to read. The ‘?’ that appears after the context display means that TEX wants advice about what to do next. If you’ve never seen an error message before, or if you’ve forgotten what sort of response is expected, you can type ‘?’ now (go ahead and try it!); TEX will respond as follows: Type to proceed, S to scroll future error messages, R to run without stopping, Q to run quietly, I to insert something, E to edit your file, 1 or ... or 9 to ignore the next 1 to 9 tokens of input, H for help, X to quit. This is your menu of options. You may choose to continue in various ways: 1. Simply type hreturni. TEX will resume its processing, after attempting to recover from the error as best it can. 2. Type ‘S’. TEX will proceed without pausing for instructions if further errors arise. Subsequent error messages will flash by on your terminal, possibly faster than you can read them, and they will appear in your log file where you can scrutinize them at your leisure. Thus, ‘S’ is sort of like typing hreturni to every message. 3. Type ‘R’. This is like ‘S’ but even stronger, since it tells TEX not to stop for any reason, not even if a file name can’t be found. 4. Type ‘Q’. This is like ‘R’ but even more so, since it tells TEX not only to proceed without stopping but also to suppress all further output to your terminal. It is a fast, but somewhat reckless, way to proceed (intended for running TEX with no operator in attendance). 5. Type ‘I’, followed by some text that you want to insert. TEX will read this line of text before encountering what it would ordinarily see next. Lines inserted in this way are not assumed to end with a blank space. * Some installations of TEX do not allow interaction. In such cases all you can do is look at the error messages in your log file, where they will appear together with the “help” information. 31 32 Chapter 6: Running TEX 6. Type a small number (less than 100). TEX will delete this many characters and control sequences from whatever it is about to read next, and it will pause again to give you another chance to look things over. 7. Type ‘H’. This is what you should do now and whenever you are faced with an error message that you haven’t seen for a while. TEX has two messages built in for each perceived error: a formal one and an informal one. The formal message is printed first (e.g., ‘! Undefined control sequence.’ ); the informal one is printed if you request more help by typing ‘H’, and it also appears in your log file if you are scrolling error messages. The informal message tries to complement the formal one by explaining what TEX thinks the trouble is, and often by suggesting a strategy for recouping your losses. 8. Type ‘X’. This stands for “exit.” It causes TEX to stop working on your job, after putting the finishing touches on your log file and on any pages that have already been output to your dvi file. The current (incomplete) page will not be output. 9. Type ‘E’. This is like ‘X’, but it also prepares the computer to edit the file that TEX is currently reading, at the current position, so that you can conveniently make a change before trying again. After you type ‘H’ (or ‘h’, which also works), you’ll get a message that tries to explain that the control sequence just read by TEX (i.e., \vship) has never been assigned a meaning, and that you should either insert the correct control sequence or you should go on as if the offending one had not appeared. In this case, therefore, your best bet is to type I\vskip (and hreturni), with no space after the ‘I’; this effectively replaces \vship by \vskip. (Do it.) If you had simply typed hreturni instead of inserting anything, TEX would have gone ahead and read ‘1in’, which it would have regarded as part of a paragraph to be typeset. Alternatively, you could have typed ‘3’ ; that would have deleted ‘1in’ from TEX’s input. Or you could have typed ‘X’ or ‘E’ in order to correct the spelling error in your file. But it’s usually best to try to detect as many errors as you can, each time you run TEX, since that increases your productivity while decreasing your computer bills. Chapter 27 explains more about the art of steering TEX through troubled text. Ä x EXERCISE 6.7 What would have happened if you had typed ‘5’ after the \vship error? Ä You can control the level of interaction by giving commands in your file as well as online: The TEX primitives \scrollmode, \nonstopmode, and \batchmode correspond respectively to typing ‘S’, ‘R’, or ‘Q’ in response to an error message, and \errorstopmode puts you back into the normal level of interaction. (Such changes are global, whether or not they appear inside a group.) Furthermore, many installations Chapter 6: Running TEX have implemented a way to interrupt TEX while it is running; such an interruption causes the program to revert to \errorstopmode, after which it pauses and waits for further instructions. What happens next in Experiment 5? TEX will hiccup on the other bug that we planted in the file. This time, however, the error message is more elaborate, since the context appears on six lines instead of two: ! Undefined control sequence. \bf A SHORT \ERROR STORY \centerline #1->\line {\hss #1 \hss } l.3 \centerline{\bf A SHORT \ERROR STORY} ? You get multiline error messages like this when the error is detected while TEX is processing some higher-level commands—in this case, while it is trying to carry out \centerline, which is not a primitive operation (it is defined in plain TEX). At first, such error messages will appear to be complete nonsense to you, because much of what you see is low-level TEX code that you never wrote. But you can overcome this hangup by getting a feeling for the way TEX operates. First notice that the context information always appears in pairs of lines. As before, the top line shows what TEX has just read ( ‘\bf A SHORT \ERROR’ ), then comes what it is about to read ( ‘STORY’ ). The next pair of lines shows the context of the first two; it indicates what TEX was doing just before it began to read the others. In this case, we see that TEX has just read ‘#1’, which is a special code that tells the machine to “read the first argument that is governed by the current control sequence”; i.e., “now read the stuff that \centerline is supposed to center on a line.” The definition in Appendix B says that \centerline, when applied to some text, is supposed to be carried out by sticking that text in place of the ‘#1’ in ‘\line{\hss#1\hss}’. So TEX is in the midst of this expansion of \centerline, as well as being in the midst of the text that is to be centered. The bottom line shows how far TEX has gotten until now in the story file. (Actually the bottom line is blank in this example; what appears to be the bottom line is really the first of two lines of context, and it indicates that TEX has read everything including the ‘}’ in line 3 of the file.) Thus, the context in this error message gives us a glimpse of how TEX went about its business. First, it saw \centerline at the beginning of line 3. Then it looked at the definition of \centerline and noticed that \centerline takes an “argument,” i.e., that \centerline applies to the next character or control sequence or group that follows. So TEX read on, and filed ‘\bf A SHORT \ERROR STORY’ away as the argument to \centerline. Then it began to read the expansion, as defined in Appendix B. When it reached the #1, it began to read the argument it had saved. And when it reached \ERROR, it complained about an undefined control sequence. 33 34 Chapter 6: Running TEX Ä x EXERCISE 6.8 Why didn’t TEX complain about \ERROR being undefined when \ERROR was first encountered, i.e., before reading ‘STORY}’ on line 3? When you get a multiline error message like this, the best clues about the source of the trouble are usually on the bottom line (since that is what you typed) and on the top line (since that is what triggered the error message). Somewhere in there you can usually spot the problem. Where should you go from here? If you type ‘H’ now, you’ll just get the same help message about undefined control sequences that you saw before. If you respond by typing hreturni, TEX will go on and finish the run, producing output virtually identical to that in Experiment 2. In other words, the conventional responses won’t teach you anything new. So type ‘E’ now; this terminates the run and prepares the way for you to fix the erroneous file. (On some systems, TEX will actually start up the standard text editor, and you’ll be positioned at the right place to delete ‘\ERROR’. On other systems, TEX will simply tell you to edit line 3 of file story.tex.) When you edit story.tex again, you’ll notice that line 2 still contains \vship; the fact that you told TEX to insert \vskip doesn’t mean that your file has changed in any way. In general, you should correct all errors in the input file that were spotted by TEX during a run; the log file provides a handy way to remember what those errors were. Well, this has indeed been a long chapter, so let’s summarize what has been accomplished. By doing the five experiments you have learned at first hand (1) how to get a job printed via TEX; (2) how to make a file that contains a complete TEX manuscript; (3) how to change the plain TEX format to achieve columns with different widths; and (4) how to avoid panic when TEX issues stern warnings. So you could now stop reading this book and go on to print a bunch of documents. It is better, however, to continue bearing with the author (after perhaps taking another rest), since you’re just at the threshold of being able to do a lot more. And you ought to read Chapter 7 at least, because it warns you about certain symbols that you must not type unless you want TEX to do something special. While reading the remaining chapters it will, of course, be best for you to continue making trial runs, using experiments of your own design. Ä Ä If you use TEX format packages designed by others, your error messages may involve many inscrutable two-line levels of macro context. By setting \errorcontextlines=0 at the beginning of your file, you can reduce the amount of information that is reported; TEX will show only the top and bottom pairs of context lines together with up to \errorcontextlines additional two-line items. (If anything has thereby been omitted, you’ll also see ‘...’.) Chances are good that you can spot the source of an error even when most of a large context has been suppressed; if not, you can say ‘I\errorcontextlines=100\oops’ and try again. (That will usually give you an undefined control sequence error and plenty of context.) Plain TEX sets \errorcontextlines=5. Chapter 6: Running TEX What we have to learn to do we learn by doing. — ARISTOTLE, Ethica Nicomachea II (c. 325 B.C.) He may run who reads. — HABAKKUK 2 : 2 (c. 600 B.C.) He that runs may read. — WILLIAM COWPER, Tirocinium (1785) 35 (page 36) 7 How TEX Reads What You Type Chapter 7: How TEX Reads What You Type We observed in the previous chapter that an input manuscript is expressed in terms of “lines,” but that these lines of input are essentially independent of the lines of output that will appear on the finished pages. Thus you can stop typing a line of input at any place that’s convenient for you, as you prepare or edit a file. A few other related rules have also been mentioned: A hreturni is like a space. Two spaces in a row count as one space. A blank line denotes the end of a paragraph. Strictly speaking, these rules are contradictory: A blank line is obtained by typing hreturni twice in a row, and this is different from typing two spaces in a row. Some day you might want to know the real rules. In this chapter and the next, we shall study the very first stage in the transition from input to output. In the first place, it’s wise to have a precise idea of what your keyboard sends to the machine. There are 256 characters that TEX might encounter at each step, in a file or in a line of text typed directly on your terminal. These 256 characters are classified into 16 categories numbered 0 to 15: Category 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Meaning Escape character Beginning of group End of group Math shift Alignment tab End of line Parameter Superscript Subscript Ignored character Space Letter Other character Active character Comment character Invalid character (\ in this manual) ({ in this manual) (} in this manual) ($ in this manual) (& in this manual) (hreturni in this manual) (# in this manual) (^ in this manual) (_ in this manual) (hnulli in this manual) (Ã in this manual) (A, . . . , Z and a, . . . , z) (none of the above or below) (~ in this manual) (% in this manual) (hdeletei in this manual)

It’s not necessary for you to learn these code numbers; the point is only that TEX responds to 16 different types of characters. At first this manual led you to believe that there were just two types—the escape character and the others— and then you were told about two more types, the grouping symbols { and }. In Chapter 6 you learned two more: ~ and %. Now you know that there are really 16. This is the whole truth of the matter; no more types remain to be revealed. The category code for any character can be changed at any time, but it is usually wise to stick to a particular scheme.

37

38

Chapter 7: How TEX Reads What You Type The main thing to bear in mind is that each TEX format reserves certain characters for its own special purposes. For example, when you are using plain TEX format (Appendix B), you need to know that the ten characters \ { } $& # ^ _ % ~ cannot be used in the ordinary way when you are typing; each of them will cause TEX to do something special, as explained elsewhere in this book. If you really need these symbols as part of your manuscript, plain TEX makes it possible for you to type \$ for $, \% for %, \& for &, \# for #, \_ for ; the \_ symbol is useful for compound identifiers in computer programs. In mathematics formulas you can use \{ and \} for { and }, while \backslash produces a reverse slash; for example, ‘$\{a \backslash b\}$’ yields ‘{a\b}’. Furthermore \^ produces a circumflex accent (e.g., ‘\^e’ yields ‘ˆe’ ); and \~ yields a tilde accent (e.g., ‘\~n’ yields ‘˜ n’ ). x EXERCISE 7.1 What horrible errors appear in the following sentence? Procter & Gamble’s stock climbed to$2, a 10% gain. x EXERCISE 7.2 Can you imagine why the designer of plain TEX decided not to make ‘\\’ the control sequence for reverse slashes? Ä

When TEX reads a line of text from a file, or a line of text that you entered directly on your terminal, it converts that text into a list of “tokens.” A token is either (a) a single character with an attached category code, or (b) a control sequence. For example, if the normal conventions of plain TEX are in force, the text ‘{\hskip 36 pt}’ is converted into a list of eight tokens: {1

hskip

312

612

Ã10

p11

t11

}2

The subscripts here are the category codes, as listed earlier: 1 for “beginning of group,” 12 for “other character,” and so on. The hskip doesn’t get a subscript, because it represents a control sequence token instead of a character token. Notice that the space after \hskip does not get into the token list, because it follows a control word.

Ä

It is important to understand the idea of token lists, if you want to gain a thorough understanding of TEX, and it is convenient to learn the concept by thinking of TEX as if it were a living organism. The individual lines of input in your files are seen only by TEX’s “eyes” and “mouth”; but after that text has been gobbled up, it is sent to TEX’s “stomach” in the form of a token list, and the digestive processes that do the actual typesetting are based entirely on tokens. As far as the stomach is concerned, the input flows in as a stream of tokens, somewhat as if your TEX manuscript had been typed all on one extremely long line.

Chapter 7: How TEX Reads What You Type Ä

You should remember two chief things about TEX’s tokens: (1) A control sequence is considered to be a single object that is no longer composed of a sequence of symbols. Therefore long control sequence names are no harder for TEX to deal with than short ones, after they have been replaced by tokens. Furthermore, spaces are not ignored after control sequences inside a token list; the ignore-space rule applies only in an input file, during the time that strings of characters are being tokenized. (2) Once a category code has been attached to a character token, the attachment is permanent. For example, if character ‘{’ were suddenly declared to be of category 12 instead of category 1, the characters ‘{1 ’ already inside token lists of TEX would still remain of category 1; only newly made lists would contain ‘{12 ’ tokens. In other words, individual characters receive a fixed interpretation as soon as they have been read from a file, based on the category they have at the time of reading. Control sequences are different, since they can change their interpretation at any time. TEX’s digestive processes always know exactly what a character token signifies, because the category code appears in the token itself; but when the digestive processes encounter a control sequence token, they must look up the current definition of that control sequence in order to figure out what it means.

Ä Äx EXERCISE 7.3

Some of the category codes 0 to 15 will never appear as subscripts in character tokens, because they disappear in TEX’s mouth. For example, characters of category 0 (escapes) never get to be tokens. Which categories can actually reach TEX’s stomach?

Ä Ä There’s a program called INITEX that is used to install TEX, starting from

scratch; INITEX is like TEX except that it can do even more things. It can compress hyphenation patterns into special tables that facilitate rapid hyphenation, and it can produce format files like ‘plain.fmt’ from ‘plain.tex’. But INITEX needs extra space to carry out such tasks, so it generally has less memory available for typesetting than you would expect to find in a production version of TEX.

Ä Ä When INITEX begins, it knows nothing but TEX’s primitives. All 256 charac-

ters are initially of category 12, except that hreturni has category 5, hspacei has category 10, hnulli has category 9, hdeletei has category 15, the 52 letters A . . . Z and a . . . z have category 11, % and \ have the respective categories 14 and 0. It follows that INITEX is initially incapable of carrying out some of TEX’s primitives that depend on grouping; you can’t use \def or \hbox until there are characters of categories 1 and 2. The format in Appendix B begins with \catcode commands to provide characters of the necessary categories; e.g., \catcode‘\{=1 assigns category 1 to the { symbol. The \catcode operation is like many other primitives of TEX that we shall study later; by modifying internal quantities like the category codes, you can adapt TEX to a wide variety of applications.

Ä Äx EXERCISE 7.4

Suppose that the commands \catcode‘\=2

appear near the beginning of a group that begins with ‘{’; these specifications instruct TEX to treat < and > as group delimiters. According to TEX’s rules of locality, the

39

40

Chapter 7: How TEX Reads What You Type characters < and > will revert to their previous categories when the group ends. But should the group end with } or with > ?

Ä Ä Although control sequences are treated as single objects, TEX does provide

a way to break them into lists of character tokens: If you write \string\cs, where \cs is any control sequence, you get the list of characters for that control sequence’s name. For example, \string\TeX produces four tokens: \12 , T12 , e12 , X12 . Each character in this token list automatically gets category code 12 (“other”), including the backslash that \string inserts to represent an escape character. However, category 10 will be assigned to the character ‘Ã’ (blank space) if a space character somehow sneaks into the name of a control sequence.

Ä Ä Conversely, you can go from a list of character tokens to a control sequence by

saying ‘\csnamehtokensi\endcsname’. The tokens that appear in this construction between \csname and \endcsname may include other control sequences, as long as those control sequences ultimately expand into characters instead of TEX primitives; the final characters can be of any category, not necessarily letters. For example, ‘\csname TeX\endcsname’ is essentially the same as ‘\TeX’; but ‘\csname\TeX\endcsname’ is illegal, because \TeX expands into tokens containing the \kern primitive. Furthermore, ‘\csname\string\TeX\endcsname’ will produce the unusual control sequence ‘\\TeX’, i.e., the token \TeX , which you can’t ordinarily write.

Ä Äx EXERCISE 7.5

Experiment with TEX to see what \string does when it is followed by an active character like ~. (Active characters behave like control sequences, but they are not prefixed by an escape.) What is an easy way to conduct such experiments online? What control sequence could you put after \string to obtain the single character token \12 ?

Ä Äx EXERCISE 7.6

What tokens does ‘\expandafter\string\csname a\string\ b\endcsname’ produce? (There are three spaces before the b. Chapter 20 explains \expandafter.)

Ä Äx EXERCISE 7.7

When \csname is used to define a control sequence for the first time, that control sequence is made equivalent to \relax until it is redefined. Use this fact to design a macro \ifundefined#1 such that, for example, \ifundefined{TeX}htrue texti\elsehfalse texti\fi expands to the htrue texti if \TeX hasn’t previously been defined, or if \TeX has been \let equal to \relax; it should expand to the hfalse texti otherwise.

Ä Ä In the examples so far, \string has converted control sequences into lists of

tokens that begin with \12 . But this backslash token isn’t really hardwired into TEX; there’s a parameter called \escapechar that specifies what character should be used when control sequences are output as text. The value of \escapechar is normally TEX’s internal code for backslash, but it can be changed if another convention is desired.

Ä Ä TEX has two other token-producing operations similar to the \string com-

mand. If you write \numberhnumberi, you get the decimal equivalent of the hnumberi; and if you write \romannumeralhnumberi, you get the number expressed in

Chapter 7: How TEX Reads What You Type lowercase roman numerals. For example, ‘\romannumeral24’ produces ‘xxiv’, a list of four tokens each having category 12. The \number operation is redundant when it is applied to an explicit constant (e.g., ‘\number24’ produces ‘24’); but it does suppress leading zeros, and it can also be used with numbers that are in TEX’s internal registers or parameters. For example, ‘\number-0015’ produces ‘-15’; and if register \count5 holds the value 316, then ‘\number\count5’ produces ‘316’.

Ä Ä The twin operations \uppercase{htoken listi} and \lowercase{htoken listi}

go through a given token list and convert all of the character tokens to their “uppercase” or “lowercase” equivalents. Here’s how: Each of the 256 possible characters has two associated values called the \uccode and the \lccode; these values are changeable just as a \catcode is. Conversion to uppercase means that a character is replaced by its \uccode value, unless the \uccode value is zero (when no change is made). Conversion to lowercase is similar, using the \lccode. The category codes aren’t changed. When INITEX begins, all \uccode and \lccode values are zero except that the letters a to z and A to Z have \uccode values A to Z and \lccode values a to z.

Ä Ä TEX performs the \uppercase and \lowercase transformations in its stomach,

but the \string and \number and \romannumeral and \csname operations are carried out en route to the stomach (like macro expansion), as explained in Chapter 20.

Ä Äx EXERCISE 7.8

What token list results from ‘\uppercase{a\lowercase{bC}}’ ?

Ä Äx EXERCISE 7.9

TEX has an internal integer parameter called \year that is set equal to the current year number at the beginning of every job. Explain how to use \year, together with c MCMLXXXVI’ \romannumeral and \uppercase, to print a copyright notice like ‘ ° for all jobs run in 1986.

Ä Äx EXERCISE 7.10

Define a control sequence \appendroman with three parameters such that \appendroman#1#2#3 defines control sequence #1 to expand to a control sequence whose name is the name of control sequence #2 followed by the value of the positive integer #3 expressed in roman numerals. For example, suppose \count20 equals 30; then ‘\appendroman\a\TeX{\count20}’ should have the same effect as ‘\def\a{\TeXxxx}’.

Some bookes are to bee tasted, others to bee swallowed, and some few to bee chewed and disgested. — FRANCIS BACON, Essayes (1597) ‘Tis the good reader that makes the good book. — RALPH WALDO EMERSON, Society & Solitude (1870)

41

(page 42)

8 The Characters You Type

Chapter 8: The Characters You Type

A lot of different keyboards are used with TEX, but few keyboards can produce 256 different symbols. Furthermore, as we have seen, some of the characters that you can type on your keyboard are reserved for special purposes like escaping and grouping. Yet when we studied fonts it was pointed out that there are 256 characters per font. So how can you refer to the characters that aren’t on your keyboard, or that have been pre-empted for formatting? One answer is to use control sequences. For example, the plain format of Appendix B, which defines % to be a special kind of symbol so that you can use it for comments, defines the control sequence \% to mean a percent sign. To get access to any character whatsoever, you can type \charhnumberi where hnumberi is any number from 0 to 255 (optionally followed by a space); you will get the corresponding character from the current font. That’s how Appendix B handles \%; it defines ‘\%’ to be an abbreviation for ‘\char37’, since 37 is the character code for a percent sign. The codes that TEX uses internally to represent characters are based on “ASCII,” the American Standard Code for Information Interchange. Appendix C gives full details of this code, which assigns numbers to certain control functions as well as to ordinary letters and punctuation marks. For example, hspacei = 32 and hreturni = 13. There are 94 standard visible symbols, and they have been assigned code numbers from 33 to 126, inclusive. It turns out that ‘b’ is character number 98 in ASCII. So you can typeset the word bubble in a strange way by putting \char98 u\char98\char98 le into your manuscript, if the b-key on your typewriter is broken. (An optional space is ignored after constants like ‘98’. Of course you need the \, c, h, a, and r keys to type ‘\char’, so let’s hope that they are always working.) Ä

TEX always uses the internal character code of Appendix C for the standard ASCII characters, regardless of what external coding scheme actually appears in the files being read. Thus, b is 98 inside of TEX even when your computer normally deals with EBCDIC or some other non-ASCII scheme; the TEX software has been set up to convert text files to internal code, and to convert back to the external code when writing text files. Device-independent (dvi) output files use TEX’s internal code. In this way, TEX is able to give identical results on all computers.

Ä

Character code tables like those in Appendix C often give the code numbers in octal notation, i.e., the radix-8 number system, in which the digits are 0, 1, 2, 3, 4, 5, 6, and 7.* Sometimes hexadecimal notation is also used, in which case the digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. For example, the octal code for ‘b’ is * The author of this manual likes to use italic digits for octal numbers, and typewriter type for hexadecimal numbers, in order to provide a typographic clue to the underlying radix whenever possible.

43

44

Chapter 8: The Characters You Type

142, and its hexadecimal code is 62. A hnumberi in TEX’s language can begin with a ’, in which case it is regarded as octal, or with a ", when it is regarded as hexadecimal. Thus, \char’142 and \char"62 are equivalent to \char98. The legitimate character codes in octal notation run from ´0 to ´377 ; in hexadecimal, they run from ˝0 to ˝FF.

Ä

But TEX actually provides another kind of hnumberi that makes it unnecessary for you to know ASCII at all! The token ‘12 (left quote), when followed by any character token or by any control sequence token whose name is a single character, stands for TEX’s internal code for the character in question. For example, \char‘b and \char‘\b are also equivalent to \char98. If you look in Appendix B to see how \% is defined, you’ll notice that the definition is \def\%{\char‘\%} instead of \char37 as claimed above.

Ä

x EXERCISE 8.1

What would be wrong with \def\%{\char‘%}?

Ä Ä The preface to this manual points out that the author tells little white lies from time to time. Well, if you actually check Appendix B you’ll find that \chardef\%=‘\% is the true definition of \%. Since format designers often want to associate a special character with a special control sequence name, TEX provides the construction ‘\chardefhcontrol sequencei=hnumberi’ for numbers between 0 and 255, as an efficient alternative to ‘\defhcontrol sequencei{\charhnumberi}’.

Although you can use \char to access any character in the current font, you can’t use it in the middle of a control sequence. For example, if you type \\char98 TEX reads this as the control sequence \\ followed by c, h, a, etc., not as the control sequence \b. You will hardly ever need to use \char when typing a manuscript, since the characters you want will probably be available as predefined control sequences; \char is primarily intended for the designers of book formats like those in the appendices. But some day you may require a special symbol, and you may have to hunt through a font catalog until you find it. Once you find it, you can use it by simply selecting the appropriate font and then specifying the character number with \char. For example, the “dangerous bend” sign used in this manual appears as character number 127 of font manfnt, and that font is selected by the control sequence \manual. The macros in Appendix E therefore display dangerous bends by saying ‘{\manual\char127}’. We have observed that the ASCII character set includes only 94 printable symbols; but TEX works internally with 256 different character codes, from 0 to 255, each of which is assigned to one of the sixteen categories described in Chapter 7. If your keyboard has additional symbols, or if it doesn’t have the standard 94, the people who installed your local TEX system can tell you the

Chapter 8: The Characters You Type

correspondence between what you type and the character number that TEX receives. Some people are fortunate enough to have keys marked ‘≠’ and ‘≤’ and ‘≥’; it is possible to install TEX so that it will recognize these handy symbols and make the typing of mathematics more pleasant. But if you do not have such keys, you can get by with the control sequences \ne, \le, and \ge. Ä

TEX has a standard way to refer to the invisible characters of ASCII: Code 0 can be typed as the sequence of three characters ^^@, code 1 can be typed ^^A, and so on up to code 31, which is ^^_ (see Appendix C). If the character following ^^ has an internal code between 64 and 127, TEX subtracts 64 from the code; if the code is between 0 and 63, TEX adds 64. Hence code 127 can be typed ^^?, and the dangerous bend sign can be obtained by saying {\manual^^?}. However, you must change the category code of character 127 before using it, since this character ordinarily has category 15 (invalid); say, e.g., \catcode‘\^^?=12. The ^^ notation is different from \char, because ^^ combinations are like single characters; for example, it would not be permissible to say \catcode‘\char127, but ^^ symbols can even be used as letters within control words.

Ä

One of the overfull box messages in Chapter 6 illustrates the fact that TEX sometimes uses the funny ^^ convention in its output: The umlaut character in that example appears as ^^?, and the cedilla appears as ^^X, because ‘ ¨ ’ and ‘¸’ occur in positions ´177 and ´30 of the \tenrm font.

Ä

There’s also a special convention in which ^^ is followed by two “lowercase hexadecimal digits,” 0–9 or a–f. With this convention, all 256 characters are obtainable in a uniform way, from ^^00 to ^^ff. Character 127 is ^^7f.

Ä

Most of the ^^ codes are unimportant except in unusual applications. But ^^M is particularly noteworthy because it is code 13, the ASCII hreturni that TEX normally places at the right end of every line of your input file. By changing the category of ^^M you can obtain useful special effects, as we shall see later.

Ä

The control code ^^I is also of potential interest, since it’s the ASCII htabi. Plain TEX makes htabi act like a blank space.

Ä Ä People who install TEX systems for use with non-American alphabets can

make TEX conform to any desired standard. For example, suppose you have a Norwegian keyboard containing the letter æ, which comes in as code 241 (say). Your local format package should define \catcode‘æ=11; then you could have control sequences like \særtrykk. Your TEX input files could be made readable by American installations of TEX that don’t have your keyboard, by substituting ^^f1 for character 241. (For example, the stated control sequence would appear as \s^^f1rtrykk in the file; your American friends should also be provided with the format that you used, with its \catcode‘^^f1=11.) Of course you should also arrange your fonts so that TEX’s character 241 will print as æ; and you should change TEX’s hyphenation algorithm so that it will do correct Norwegian hyphenation. The main point is that such changes are not extremely difficult; nothing in the design of TEX limits it to the American alphabet. Fine printing is obtained by fine tuning to the language or languages being used.

Ä Ä European languages can also be accommodated effectively with only a limited character set. For example, let’s consider Norwegian again, but suppose that

45

46

Chapter 8: The Characters You Type

you want to use a keyboard without an æ character. You can arrange the font metric file so that TEX will interpret ae, o/, aa, AE, O/, and AA as ligatures that produce æ, ø, ˚ a, Æ, Ø, and ˚ A, respectively; and you could put the characters ˚ a and ˚ A into positions 128 and 129 of the font. By setting \catcode‘/=11 you would be able to use the ligature o/ in control sequences like ‘\ho/yre’. TEX’s hyphenation method is not confused by ligatures; so you could use this scheme to operate essentially as suggested before, but with two keystrokes occasionally replacing one. (Your typists would have to watch out for the occasional times when the adjacent characters aa, oe, and o/ should not be treated as ligatures; also, ‘\/’ would be a control word, not a control symbol.)

Ä Ä The rest of this chapter is devoted to TEX’s reading rules, which define the

conversion from text to tokens. For example, the fact that TEX ignores spaces after control words is a consequence of the rules below, which imply among other things that spaces after control words never become space tokens. The rules are intended to work the way you would expect them to, so you may not wish to bother reading them; but when you are communicating with a computer, it is nice to understand what the machine thinks it is doing, and here’s your chance.

Ä Ä The input to TEX is a sequence of “lines.” Whenever TEX is reading a line of text from a file, or a line of text that you entered directly on your terminal, the computer’s reading apparatus is in one of three so-called states: State N State M State S

Beginning a new line; Middle of a line; Skipping blanks.

At the beginning of every line it’s in state N ; but most of the time it’s in state M , and after a control word or a space it’s in state S. Incidentally, “states” are different from the “modes” that we will be studying later; the current state refers to TEX’s eyes and mouth as they take in characters of new text, but the current mode refers to the condition of TEX’s gastro-intestinal tract. Most of the things that TEX does when it converts characters to tokens are independent of the current state, but there are differences when spaces or end-of-line characters are detected (categories 10 and 5).

Ä Ä TEX deletes any hspacei characters (number 32) that occur at the right end

of an input line. Then it inserts a hreturni character (number 13) at the right end of the line, except that it places nothing additional at the end of a line that you inserted with ‘I’ during error recovery. Note that hreturni is considered to be an actual character that is part of the line; you can obtain special effects by changing its catcode.

Ä Ä If TEX sees an escape character (category 0) in any state, it scans the entire

control sequence name as follows. (a) If there are no more characters in the line, the name is empty (like \csname\endcsname). Otherwise (b) if the next character is not of category 11 (letter), the name consists of that single symbol. Otherwise (c) the name consists of all letters beginning with the current one and ending just before the first nonletter, or at the end of the line. This name becomes a control sequence token. TEX goes into state S in case (c), or in case (b) with respect to a character of category 10 (space); otherwise TEX goes into state M .

Ä Ä If TEX sees a superscript character (category 7) in any state, and if that charac-

ter is followed by another identical character, and if those two equal characters

Chapter 8: The Characters You Type

are followed by a character of code c < 128, then they are deleted and 64 is added to or subtracted from the code c. (Thus, ^^A is replaced by a single character whose code is 1, etc., as explained earlier.) However, if the two superscript characters are immediately followed by two of the lowercase hexadecimal digits 0123456789abcdef, the four-character sequence is replaced by a single character having the specified hexadecimal code. The replacement is carried out also if such a trio or quartet of characters is encountered during steps (b) or (c) of the control-sequence-name scanning procedure described above. After the replacement is made, TEX begins again as if the new character had been present all the time. If a superscript character is not the first of such a trio or quartet, it is handled by the following rule.

Ä Ä If TEX sees a character of categories 1, 2, 3, 4, 6, 8, 11, 12, or 13, or a character

of category 7 that is not the first of a special sequence as just described, it converts the character to a token by attaching the category code, and goes into state M . This is the normal case; almost every nonblank character is handled by this rule.

Ä Ä If TEX sees an end-of-line character (category 5), it throws away any other

information that might remain on the current line. Then if TEX is in state N (new line), the end-of-line character is converted to the control sequence token ‘ par ’ (end of paragraph); if TEX is in state M (mid-line), the end-of-line character is converted to a token for character 32 (‘Ã’) of category 10 (space); and if TEX is in state S (skipping blanks), the end-of-line character is simply dropped.

Ä Ä If TEX sees a character to be ignored (category 9), it simply bypasses that character as if it weren’t there, and remains in the same state.

Ä Ä If TEX sees a character of category 10 (space), the action depends on the

current state. If TEX is in state N or S, the character is simply passed by, and TEX remains in the same state. Otherwise TEX is in state M ; the character is converted to a token of category 10 whose character code is 32, and TEX enters state S. The character code in a space token is always 32.

Ä Ä If TEX sees a comment character (category 14), it throws away that character and any other information that might remain on the current line.

Ä Ä Finally, if TEX sees an invalid character (category 15), it bypasses that character, prints an error message, and remains in the same state.

Ä Ä If TEX has nothing more to read on the current line, it goes to the next line

and enters state N . However, if \endinput has been specified for a file being \input, or if an \input file has ended, TEX returns to whatever it was reading when the \input command was originally given. (Further details of \input and \endinput are discussed in Chapter 20.)

Ä Äx EXERCISE 8.2

Test your understanding of TEX’s reading rules by answering the following quickie questions: (a) What is the difference between categories 5 and 14? (b) What is the difference between categories 3 and 4? (c) What is the difference between categories 11 and 12? (d) Are spaces ignored after active characters? (e) When a line ends with a comment character like %, are spaces ignored at the beginning of the next line? (f) Can an ignored character appear in the midst of a control sequence name?

47

48

Chapter 8: The Characters You Type

Ä Äx EXERCISE 8.3

Look again at the error message that appears on page 31. When TEX reported that \vship was an undefined control sequence, it printed two lines of context, showing that it was in the midst of reading line 2 of the story file. At the time of that error message, what state was TEX in? What character was it about to read next?

Ä Äx EXERCISE 8.4

Given the category codes of plain TEX format, what tokens are produced from the input line ‘ $x^2$~ \TeX ^^62^^6’ ?

Ä Äx EXERCISE 8.5

Consider an input file that contains exactly three lines; the first line says ‘Hi!’, while the other two lines are completely blank. What tokens are produced when TEX reads this file, using the category codes of plain TEX format?

Ä Äx EXERCISE 8.6

Assume that the category codes of plain TEX are in force, except that the characters ^^A, ^^B, ^^C, ^^M belong respectively to categories 0, 7, 10, and 11. What tokens are produced from the (rather ridiculous) input line ‘^^B^^BM^^A^^B^^C^^M^^@\MÃ’ ? (Remember that this line is followed by hreturni, which is ^^M; and recall that ^^@ denotes the hnulli character, which has category 9 when INITEX begins.)

Ä Ä The special character inserted at the end of each line needn’t be hreturni; TEX actually inserts the current value of an integer parameter called \endlinechar, which normally equals 13 but it can be changed like any other parameter. If the value of \endlinechar is negative or greater than 255, no character is appended, and the effect is as if every line ends with % (i.e., with a comment character).

Ä Ä Since it is possible to change the category codes, TEX might actually use

several different categories for the same character on a single line. For example, Appendices D and E contain several ways to coerce TEX to process text “verbatim,” so that the author could prepare this manual without great difficulty. (Try to imagine typesetting a TEX manual; backslashes and other special characters need to switch back and forth between their normal categories and category 12!) Some care is needed to get the timing right, but you can make TEX behave in a variety of different ways by judiciously changing the categories. On the other hand, it is best not to play with the category codes very often, because you must remember that characters never change their categories once they have become tokens. For example, when the arguments to a macro are first scanned, they are placed into a token list, so their categories are fixed once and for all at that time. The author has intentionally kept the category codes numeric instead of mnemonic, in order to discourage people from making extensive use of \catcode changes except in unusual circumstances.

Ä Äx EXERCISE 8.7

Appendix B defines \lq and \rq to be abbreviations for ‘ and ’ (single left and right quotes, respectively). Explain why the definitions \chardef\lq=96 would not be as good.

\chardef\rq=39

Chapter 8: The Characters You Type

for life’s not a paragraph And death i think is no parenthesis. — e. e. cummings, since feeling is first (1926) This coded character set is to facilitate the general interchange of information among information processing systems, communication systems, and associated equipment. . . . An 8-bit set was considered but the need for more than 128 codes in general applications was not yet evident. — ASA SUBCOMMITTEE X3.2, American Standard Code for Information Interchange (1963)

49

(page 50)

9 TEX’s Roman Fonts

Chapter 9: TEX’s Roman Fonts When you’re typing a manuscript for TEX, you need to know what symbols are available. The plain TEX format of Appendix B is based on the Computer Modern fonts, which provide the characters needed to typeset a wide variety of documents. It’s time now to discuss what a person can do with plain TEX when typing straight text. We’ve already touched on some of the slightly subtle things—for example, dashes and quotation marks were considered in Chapter 2, and certain kinds of accents appeared in the examples of Chapters 3 and 6. The purpose of this chapter is to give a more systematic summary of the possibilities, by putting all the facts together. Let’s begin with the rules for the normal roman font (\rm or \tenrm); plain TEX will use this font for everything unless you specify otherwise. Most of the ordinary symbols that you need are readily available and you can type them in the ordinary way: There’s nothing special about the letters A to Z and a to z the digits 0 to 9 common punctuation marks : ; ! ? ( ) [ ] ‘ ’ - * / . , @ except that TEX recognizes certain combinations as ligatures: ff yields ff; fi yields fi; fl yields fl;

ffi yields ffi; ffl yields ffl; -- yields – ;

‘‘ yields “ ; ’’ yields ” ; --- yields — ;

!‘ yields ¡ ; ?‘ yields ¿.

You can also type + and =, to get the corresponding symbols + and =; but it’s much better to use such characters only in math mode, i.e., enclosed between two $signs, since that tells TEX to insert the proper spacing for mathematics. Math mode is explained later; for now, it’s just a good idea to remember that formulas and text should be segregated. A non-mathematical hyphen and a non-mathematical slash should be specified by typing ‘-’ and ‘/’ outside of mathematics mode, but subtraction and division should be specified by typing ‘-’ and ‘/’ between$ signs. The previous paragraph covers 80 of the 94 visible characters of standard ASCII; so your keyboard probably contains at least 14 more symbols, and you should learn to watch out for the remaining ones, since they are special. Four of these are pre¨empted by plain TEX; if your manuscript requires the symbols $# % & you should remember to type them as \$

\#

\%

\&

respectively. Plain TEX also reserves the six symbols \

{

}

^

_

~

but you probably don’t mind losing these, since they don’t appear in normal copy. Braces and backslashes are available via control sequences in math mode.

51

52

Chapter 9: TEX’s Roman Fonts There are four remaining special characters in the standard ASCII set: "

|

<

>

Again, you don’t really want them when you’re typesetting text. (Double-quote marks should be replaced either by ‘‘ or by ’’; vertical lines and relation signs are needed only in math mode.) Scholarly publications in English often refer to other languages, so plain TEX makes it possible to typeset the most commonly used accents: Type \‘o \’o \^o \"o \~o \=o \.o \u o \v o \H o \t oo

to get o ´o oˆ ¨o o˜ ¯o o˙ ˘o ˇo o˝ oÄ o

(grave accent) (acute accent) (circumflex or “hat”) (umlaut or dieresis) (tilde or “squiggle”) (macron or “bar”) (dot accent) (breve accent) (h´aˇcek or “check”) (long Hungarian umlaut) (tie-after accent)

Within the font, such accents are designed to appear at the right height for the letter ‘o’; but you can use them over any letter, and TEX will raise an accent that is supposed to be taller. Notice that spaces are needed in the last four cases, to separate the control sequences from the letters that follow. You could, however, type ‘\H{o}’ in order to avoid putting a space in the midst of a word. Plain TEX also provides three accents that go underneath: Type \c o \d o \b o

to get o¸ (cedilla accent) o. (dot-under accent) o (bar-under accent) ¯ And there are a few special letters: Type \oe,\OE \ae,\AE \aa,\AA \o,\O \l,\L \ss

to get œ, Œ æ, Æ ˚ a, ˚ A ø, Ø lÃ, L Ã ß

(French ligature OE) (Latin and Scandinavian ligature AE) (Scandinavian A-with-circle) (Scandinavian O-with-slash) (Polish suppressed-L) (German “es-zet” or sharp S)

The \rm font contains also the dotless letters ‘ı’ and ‘’, which you can obtain by typing ‘\i’ and ‘\j’. These are needed because ‘i’ and ‘j’ should lose their dots

Chapter 9: TEX’s Roman Fonts when they gain an accent. For example, the right way to obtain ‘m¯ın˘ us’ is to type ‘m\=\i n\u us’ or ‘m\={\i}n\u{u}s’. This completes our summary of the \rm font. Exactly the same conventions apply to \bf, \sl, and \it, so you don’t have to do things differently when you’re using a different typeface. For example, \bf\"o yields ¨ o and \it\& yields &. Isn’t that nice? Ä

However, \tt is slightly different. You will be glad to know that ff, fi, and so on are not treated as ligatures when you’re using typewriter type; nor do you get ligatures from dashes and quote marks. That’s fine, because ordinary dashes and ordinary double-quotes are appropriate when you’re trying to imitate a typewriter. Most of the accents are available too. But \H, \., \l, and \L cannot be used—the typewriter font contains other symbols in their place. Indeed, you are suddenly allowed to type ", |, ; see Appendix F. All of the letters, spaces, and other symbols in \tt have the same width.

x EXERCISE 9.1 What’s the non-naive way to type ‘na¨ıve’ ? x EXERCISE 9.2 List some English words that contain accented letters. x EXERCISE 9.3 How would you type ‘Æsop’s Œuvres en fran¸cais’ ? x EXERCISE 9.4 Explain what to type in order to get this sentence: Commentarii Academiæ scientiarum imperialis petropolitanæ is now AkademiÄıa Nauk SSSR, Doklady. x EXERCISE 9.5 And how would you specify the names Ernesto Cesaro, P´al Erd˝os, Øystein Ore, ´ StanisÃlaw Swierczkowski, Serge˘ı ÄIur’ev, Muh.ammad ibn Mˆ usˆa al-Khwˆarizmˆı? Ä

x EXERCISE 9.6

Devise a way to typeset P´ al Erd˝ os in typewriter type.

The following symbols come out looking exactly the same whether you are using \rm, \sl, \bf, \it, or \tt: Type \dag \ddag \S \P

to get † ‡ § ¶

(dagger or obelisk) (double dagger or diesis) (section number sign) (paragraph sign or pilcrow)

(They appear in just one style because plain TEX gets them from the math symbols font. Lots of other symbols are needed for mathematics; we shall study them later. See Appendix B for a few more non-math symbols.)

53

54

Chapter 9: TEX’s Roman Fonts x EXERCISE 9.7 In plain TEX’s italic font, the ‘$’ sign comes out as ‘£ ’. This gives you a way to refer to pounds sterling, but you might want an italic dollar sign. Can you think of a way to typeset a reference to the book Europe on$15.00 a day ? Ä Ä Appendix B shows that plain TEX handles most of the accents by using TEX’s

\accent primitive. For example, \’#1 is equivalent to {\accent19 #1}, where #1 is the argument being accented. The general rule is that \accenthnumberi puts an accent over the next character; the hnumberi tells where that accent appears in the current font. The accent is assumed to be properly positioned for a character whose height equals the x-height of the current font; taller or shorter characters cause the accent to be raised or lowered, taking due account of the slantedness of the fonts of accenter and accentee. The width of the final construction is the width of the character being accented, regardless of the width of the accent. Mode-independent commands like font changes may appear between the accent number and the character to be accented, but grouping operations must not intervene. If it turns out that no suitable character is present, the accent will appear by itself as if you had said \charhnumberi instead of \accenthnumberi. For example, \’{} produces ´.

Ä Äx EXERCISE 9.8

Why do you think plain TEX defines \’#1 to be ‘{\accent19 #1}’ instead of simply letting \’ be an abbreviation for ‘\accent19 ’ ? (Why the extra braces, and why the argument #1?)

Ä Ä It’s important to remember that these conventions we have discussed for ac-

cents and special letters are not built into TEX itself; they belong only to the plain TEX format, which uses the Computer Modern fonts. Quite different conventions will be appropriate when other fonts are involved; format designers should provide rules for how to obtain accents and special characters in their particular systems. Plain TEX works well enough when accents are infrequent, but the conventions of this chapter are by no means recommended for large-scale applications of TEX to other languages. For example, a well-designed TEX font for French might well treat accents as ligatures, so that one could e’crire de cette manie‘re nai"ve en franc/ais without backslashes. (See the remarks about Norwegian in Chapter 8.)

Chapter 9: TEX’s Roman Fonts

Let’s doo’t after the high Roman fashion. — WILLIAM SHAKESPEARE, The Tragedie of Anthony and Cleopatra (1606) English is a straightforward, frank, honest, open-hearted, no-nonsense language, which has little truck with such devilish devious devices as accents; indeed U.S. editors and printers are often thrown into a dither when a foreign word insinuates itself into the language. However there is one word on which Americans seem to have closed ranks, printing it confidently, courageously, and almost invariably complete with accent—the cheese presented to us as M¨ unster. Unfortunately, Munster doesn’t take an accent. — WAVERLEY ROOT, in the International Herald Tribune (1982)

55

(page 56)

10 Dimensions

Chapter 10: Dimensions

Sometimes you want to tell TEX how big to make a space, or how wide to make a line. For example, the short story of Chapter 6 used the instruction ‘\vskip .5cm’ to skip vertically by half a centimeter, and we also said ‘\hsize=4in’ to specify a horizontal size of 4 inches. It’s time now to consider the various ways such dimensions can be communicated to TEX. “Points” and “picas” are the traditional units of measure for printers and compositors in English-speaking countries, so TEX understands points and picas. TEX also understands inches and metric units, as well as the continental European versions of points and picas. Each unit of measure is given a two-letter abbreviation, as follows: pt pc in bp cm mm dd cc sp

point (baselines in this manual are 12 pt apart) pica (1 pc = 12 pt) inch (1 in = 72.27 pt) big point (72 bp = 1 in) centimeter (2.54 cm = 1 in) millimeter (10 mm = 1 cm) didot point (1157 dd = 1238 pt) cicero (1 cc = 12 dd) scaled point (65536 sp = 1 pt)

The output of TEX is firmly grounded in the metric system, using the conversion factors shown here as exact ratios. x EXERCISE 10.1 How many points are there in 254 centimeters? When you want to express some physical dimension to TEX, type it as or

hoptional signihnumberihunit of measurei hoptional signihdigit stringi.hdigit stringihunit of measurei

where an hoptional signi is either a ‘+’ or a ‘-’ or nothing at all, and where a hdigit stringi consists of zero or more consecutive decimal digits. The ‘.’ can also be a ‘,’. For example, here are six typical dimensions: 3 in -.013837in 0.mm

29 pc + 42,1 dd 123456789sp

A plus sign is redundant, but some people occasionally like extra redundancy once in a while. Blank spaces are optional before the signs and the numbers and the units of measure, and you can also put an optional space after the dimension; but you should not put spaces within the digits of a number or between the letters of the unit of measure. x EXERCISE 10.2 Arrange those six “typical dimensions” into order, from smallest to largest.

57

58

Chapter 10: Dimensions

Ä

x EXERCISE 10.3

Two of the following three dimensions are legitimate according to TEX’s rules. Which two are they? What do they mean? Why is the other one incorrect? ’.77pt "Ccc -,sp

The following “rulers” have been typeset by TEX so that you can get some idea of how different units compare to each other. If no distortion has been introduced during the camera work and printing processes that have taken place after TEX did its work, these rulers are highly accurate. 4 in 300 pt 300 dd 10 cm Ä

x EXERCISE 10.4

(To be worked after you know about boxes and glue and have read Chapter 21.) Explain how to typeset such a 10 cm ruler, using TEX.

Ä

TEX represents all dimensions internally as an integer multiple of the tiny units called sp. Since the wavelength of visible light is approximately 100 sp, rounding errors of a few sp make no difference to the eye. However, TEX does all of its arithmetic very carefully so that identical results will be obtained on different computers. Different implementations of TEX will produce the same line breaks and the same page breaks when presented with the same document, because the integer arithmetic will be the same.

Ä

The units have been defined here so that precise conversion to sp is efficient on a wide variety of machines. In order to achieve this, TEX’s “pt” has been made slightly larger than the official printer’s point, which was defined to equal exactly .013837 in by the American Typefounders Association in 1886 [cf. National Bureau of Standards Circular 570 (1956)]. In fact, one classical point is exactly .99999999 pt, so the “error” is essentially one part in 108 . This is more than two orders of magnitude less than the amount by which the inch itself changed during 1959, when it shrank to 2.54 cm from its former value of (1/0.3937) cm; so there is no point in worrying about the difference. The new definition 72.27 pt = 1 in is not only better for calculation, it is also easier to remember. TEX will not deal with dimensions whose absolute value is 230 sp or more. In other words, the maximum legal dimension is slightly less than 16384 pt. This is a distance of about 18.892 feet (5.7583 meters), so it won’t cramp your style.

Ä

Chapter 10: Dimensions

In a language manual like this it is convenient to use “angle brackets” in abbreviations for various constructions like hnumberi and hoptional signi and hdigit stringi. Henceforth we shall use the term hdimeni to stand for a legitimate TEX dimension. For example, \hsize=hdimeni will be the general way to define the column width that TEX is supposed to use. The idea is that hdimeni can be replaced by any quantity like ‘4in’ that satisfies TEX’s grammatical rules for dimensions; abbreviations in angle brackets make it easy to state such laws of grammar. When a dimension is zero, you have to specify a unit of measure even though the unit is irrelevant. Don’t just say ‘0’ ; say ‘0pt’ or ‘0in’ or something. The 10-point size of type that you are now reading is normal in textbooks, but you probably will often find yourself wanting a larger font. Plain TEX makes it easy to do this by providing magnified output. If you say \magnification=1200 at the beginning of your manuscript, everything will be enlarged by 20%; i.e., it will come out at 1.2 times the normal size. Similarly, ‘\magnification=2000’ doubles everything; this actually quadruples the area of each letter, since heights and widths are both doubled. To magnify a document by the factor f , you say \magnification=hnumberi, where the hnumberi is 1000 times f . This instruction must be given before the first page of output has been completed. You cannot apply two different magnifications to the same document. Magnification has obvious advantages: You’ll have less eyestrain when you’re proofreading; you can easily make transparencies for lectures; and you can photo-reduce magnified output, in order to minimize the deficiencies of a low-resolution printer. Conversely, you might even want ‘\magnification=500’ in order to create a pocket-size version of some book. But there’s a slight catch: You can’t use magnification unless your printing device happens to have the fonts that you need at the magnification you desire. In other words, you need to find out what sizes are available before you can magnify. Most installations of TEX make it possible to print all the fonts of plain TEX if you magnify by \magstep0, 1, 2, 3, and perhaps 4 or even 5 (see Chapter 4); but the use of large fonts can be expensive because a lot of system memory space is often required to store the shapes. x EXERCISE 10.5 Try printing the short story of Chapter 6 at 1.2, 1.44, and 1.728 times the normal size. What should you type to get TEX to do this? Ä

When you say \magnification=2000, an operation like ‘\vskip.5cm’ will actually skip 1.0 cm of space in the final document. If you want to specify a dimension in terms of the final size, TEX allows you to say ‘true’ just before pt, pc, in,

59

60

Chapter 10: Dimensions

bp, cm, mm, dd, cc, and sp. This unmagnifies the units, so that the subsequent magnification will cancel out. For example, ‘\vskip.5truecm’ is equivalent to ‘\vskip.25cm’ if you have previously said ‘\magnification=2000’. Plain TEX uses this feature in the \magnification command itself: Appendix B includes the instruction \hsize = 6.5 true in just after a new magnification has taken effect. This adjusts the line width so that the material on each page will be 6 21 inches wide when it is finally printed, regardless of the magnification factor. There will be an inch of margin at both left and right, assuming that the paper is 8 12 inches wide.

Ä

If you use no ‘true’ dimensions, TEX’s internal computations are not affected by the presence or absence of magnification; line breaks and page breaks will be the same, and the dvi file will change in only two places. TEX simply tells the printing routine that you want a certain magnification, and the printing routine will do the actual enlargement when it reads the dvi file.

Ä

x EXERCISE 10.6

Chapter 4 mentions that fonts of different magnifications can be used in the same job, by loading them ‘at’ different sizes. Explain what fonts will be used when you give the commands \magnification=\magstep1 \font\first=cmr10 scaled\magstep1 \font\second=cmr10 at 12truept

Ä Ä Magnification is actually governed by TEX’s \mag primitive, which is an integer

parameter that should be positive and at most 32768. The value of \mag is examined in three cases: (1) just before the first page is shipped to the dvi file; (2) when computing a true dimension; (3) when the dvi file is being closed. Alternatively, some implementations of TEX produce non-dvi output; they examine \mag in case (2) and also when shipping out each page. Since each document has only one magnification, the value of \mag must not change after it has first been examined.

Ä

TEX also recognizes two units of measure that are relative rather than absolute; i.e., they depend on the current context: em is the width of a “quad” in the current font; ex is the “x-height” of the current font.

Each font defines its own em and ex values. In olden days, an “em” was the width of an ‘M’, but this is no longer true; ems are simply arbitrary units that come with a font, and so are exes. The Computer Modern fonts have the property that an em-dash is one em wide, each of the digits 0 to 9 is half an em wide, and lowercase ‘x’ is one ex high; but these are not hard-and-fast rules for all fonts. The \rm font (cmr10) of plain TEX has 1 em = 10 pt and 1 ex ≈ 4.3 pt; the \bf font (cmbx10) has 1 em = 11.5 pt and 1 ex ≈ 4.44 pt; and the \tt font (cmtt10) has 1 em = 10.5 pt and 1 ex ≈ 4.3 pt. All of these are “10-point” fonts, yet they have different em and ex values. It is generally best to use em for horizontal measurements and ex for vertical measurements that depend on the current font.

Chapter 10: Dimensions

Ä

A hdimeni can also refer to TEX’s internal registers or parameters. We shall discuss registers later, and a complete definition of everything that a hdimeni can be will be given in Chapter 24. For now it will suffice to give some hints about what is to come: ‘\hsize’ stands for the current horizontal line size, and ‘.5\hsize’ is half that amount; ‘2\wd3’ denotes twice the width of register \box3; ‘-\dimen100’ is the negative of register \dimen100.

Ä Ä Notice that the unit names in dimensions are not preceded by backslashes. The

same is true of other so-called keywords of the TEX language. Keywords can be given in uppercase letters or in a mixture of upper and lower case; e.g., ‘Pt’ is equivalent to ‘pt’. The category codes of these letters are irrelevant; you may, for example, be using a p of category 12 (other) that was generated by expanding ‘\the\hsize’ as explained in Chapter 20. TEX gives a special interpretation to keywords only when they appear in certain very restricted contexts. For example, ‘pt’ is a keyword only when it appears after a number in a hdimeni; ‘at’ is a keyword only when it appears after the external name of a font in a \font declaration. Here is a complete list of TEX’s keywords, in case you are wondering about the full set: at, bp, by, cc, cm, dd, depth, em, ex, fil, height, in, l, minus, mm, mu, pc, plus, pt, scaled, sp, spread, to, true, width. (See Appendix I for references to the contexts in which each of these is recognized as a keyword.)

The methods that have hitherto been taken to discover the measure of the Roman foot, will, upon examination, be found so unsatisfactory, that it is no wonder the learned are not yet agreed on that point. ... 9 London inches are equal to 8,447 Paris inches. — MATTHEW RAPER, in Philosophical Transactions (1760) Without the letter U, units would be nits. — SESAME STREET (1970)

61

(page 62)

11 Boxes

Chapter 11: Boxes

TEX makes complicated pages by starting with simple individual characters and putting them together in larger units, and putting these together in still larger units, and so on. Conceptually, it’s a big paste-up job. The TEXnical terms used to describe such page construction are boxes and glue. Boxes in TEX are two-dimensional things with a rectangular shape, having three associated measurements called height, width, and depth. Here is a picture of a typical box, showing its so-called reference point and baseline:

Reference point−→•

Baseline

←− width −→

↑ | | height | | ↓ ↑ depth ↓

From TEX’s viewpoint, a single character from a font is a box; it’s one of the simplest kinds of boxes. The font designer has decided what the height, width, and depth of the character are, and what the symbol will look like when it is in the box; TEX uses these dimensions to paste boxes together, and ultimately to determine the locations of the reference points for all characters on a page. In plain TEX’s \rm font (cmr10), for example, the letter ‘h’ has a height of 6.9444 points, a width of 5.5555 points, and a depth of zero; the letter ‘g’ has a height of 4.3055 points, a width of 5 points, and a depth of 1.9444 points. Only certain special characters like parentheses have height plus depth actually equal to 10 points, although cmr10 is said to be a “10-point” font. You needn’t bother to learn these measurements yourself, but it’s good to be aware of the fact that TEX deals with such information; then you can better understand what the computer does to your manuscript. The character shape need not fit inside the boundaries of its box. For example, some characters that are used to build up larger math symbols like matrix brackets intentionally protrude a little bit, so that they overlap properly with the rest of the symbol. Slanted letters frequently extend a little to the right of the box, as if the box were skewed right at the top and left at the bottom, keeping its baseline fixed. For example, compare the letter ‘g’ in the cmr10 and cmsl10 fonts (\rm and \sl):

In both cases TEX thinks that the box is 5 points wide, so both letters get exactly the same treatment. TEX doesn’t have any idea where the ink will go—only the output device knows this. But the slanted letters will be spaced properly in spite of TEX’s lack of knowledge, because the baselines will match up.

63

64

Chapter 11: Boxes

Actually the font designer also tells TEX one other thing, the so-called italic correction: A number is specified for each character, telling roughly how far that character extends to the right of its box boundary, plus a little to spare. For example, the italic correction for ‘g’ in cmr10 is 0.1389 pt, while in cmsl10 it is 0.8565 pt. Chapter 4 points out that this correction is added to the normal width if you type ‘\/’ just after the character. You should remember to use \/ when shifting from a slanted font to an unslanted one, especially in cases like the so-called {\sl italic correction\/}: since no space intervenes here to compensate for the loss of slant. TEX also deals with another simple kind of box, which might be called a “black box,” namely, a rectangle like ‘ ’ that is to be entirely filled with ink at printing time. You can specify any height, width, and depth you like for such boxes—but they had better not have too much area, or the printer might get upset. (Printers generally prefer white space to black space.) Usually these black boxes are made very skinny, so that they appear as horizontal lines or vertical lines. Printers traditionally call such lines “horizontal rules” and “vertical rules,” so the terms TEX uses to stand for black boxes are \hrule and \vrule. Even when the box is square, as in ‘ ’, you must call it either an \hrule or a \vrule. We shall discuss the use of rule boxes in greater detail later. (See Chapter 21.) Everything on a page that has been typeset by TEX is made up of simple character boxes or rule boxes, pasted together in combination. TEX pastes boxes together in two ways, either horizontally or vertically. When TEX builds a horizontal list of boxes, it lines them up so that their reference points appear in the same horizontal row; therefore the baselines of adjacent characters will match up as they should. Similarly, when TEX builds a vertical list of boxes, it lines them up so that their reference points appear in the same vertical column. Let’s take a look at what TEX does behind the scenes, by comparing the computer’s methods with what you would do if you were setting metal type by hand. In the time-tested traditional method, you choose the letters that you need out of a type case—the uppercase letters are in the upper case—and you put them into a “composing stick.” When a line is complete, you adjust the spacing and transfer the result to the “chase,” where it joins the other rows of type. Eventually you lock the type up tightly by adjusting external wedges called “quoins.” This isn’t much different from what TEX does, except that different words are used; when TEX locks up a line, it creates what is called an “hbox” (horizontal box), because the components of the line are pieced together horizontally. You can give an instruction like \hbox{A line of type.} in a TEX manuscript; this tells the computer to take boxes for the appropriate letters in the current font and to lock them up in an hbox. As far as TEX is

Chapter 11: Boxes

concerned, the letter ‘A’ is a box ‘ ’ and the letter ‘p’ is a box ‘ ’. So the given instruction causes TEX to form the hbox representing ‘A line of type.’ The hboxes for individual lines of type are eventually joined together by putting them into a “vbox” (vertical box). For example, you can say \vbox{\hbox{Two lines}\hbox{of type.}} and TEX will convert this into i.e.,

Two lines of type.

The principal difference between TEX’s method and the old way is that metal types are generally cast so that each character has the same height and depth; this makes it easy to line them up by hand. TEX’s types have variable height and depth, because the computer has no trouble lining characters up by their baselines, and because the extra information about height and depth helps in the positioning of accents and mathematical symbols. Another important difference between TEX setting and hand setting is, of course, that TEX will choose line divisions automatically; you don’t have to insert \hbox and \vbox instructions unless you want to retain complete control over where each letter goes. On the other hand, if you do use \hbox and \vbox, you can make TEX do almost everything that Ben Franklin could do in his printer’s shop. You’re only giving up the ability to make the letters come out charmingly crooked or badly inked; for such effects you need to make a new font. (And of course you lose the tactile and olfactory sensations, and the thrill of doing everything by yourself. TEX will never completely replace the good old ways.) A page of text like the one you’re reading is itself a box, in TEX’s view: It is a largish box made from a vertical list of smaller boxes representing the lines of text. Each line of text, in turn, is a box made from a horizontal list of boxes representing the individual characters. In more complicated situations, involving mathematical formulas and/or complex tables, you can have boxes within boxes within boxes . . . to any level. But even these complicated situations arise from horizontal or vertical lists of boxes pasted together in a simple way; all that you and TEX have to worry about is one list of boxes at a time. In fact, when you’re typing straight text, you don’t have to think about boxes at all, since TEX will automatically take responsibility for assembling the character boxes into words and the words into lines and the lines into pages. You need to be aware of the box concept only when you want to do something out of the ordinary, e.g., when you want to center a heading. Ä

From the standpoint of TEX’s digestive processes, a manuscript comes in as a sequence of tokens, and the tokens are to be transformed into a sequence of boxes. Each token of input is essentially an instruction or a piece of an instruction; for

65

66

Chapter 11: Boxes

example, the token ‘A11 ’ normally means, “put a character box for the letter A at the end of the current hbox, using the current font”; the token ‘ vskip ’ normally means, “skip vertically in the current vbox by the hdimeni specified in the following tokens.”

Ä

The height, width, or depth of a box might be negative, in which case it is a “shadow box” that is somewhat hard to draw. TEX doesn’t balk at negative dimensions; it just does arithmetic as usual. For example, the combined width of two adjacent boxes is the sum of their widths, whether or not the widths are positive. A font designer can declare a character’s width to be negative, in which case the character acts like a backspace. (Languages that read from right to left could be handled in this way, but only to a limited extent, since TEX’s line-breaking algorithm is based on the assumption that words don’t have negative widths.)

Ä

TEX can raise or lower the individual boxes in a horizontal list; such adjustments take care of mathematical subscripts and superscripts, as well as the heights of accents and a few other things. For example, here is a way to make a box that contains the TEX logo, putting it into TEX’s internal register \box0: \setbox0=\hbox{T\kern-.1667em\lower.5ex\hbox{E}\kern-.125em X} Here ‘\kern-.1667em’ means to insert blank space of −.1667 ems in the current font, i.e., to back up a bit; and ‘\lower.5ex’ means that the box \hbox{E} is to be lowered by half of the current x-height, thus offsetting that box with respect to the others. Instead of ‘\lower.5ex’ one could also say ‘\raise-.5ex’. Chapters 12 and 21 discuss the details of how to construct boxes for special effects; our goal in the present chapter is merely to get a taste of the possibilities.

Ä

TEX will exhibit the contents of any box register, if you ask it to. For example, if you type ‘\showbox0’ after setting \box0 to the TEX logo as above, your log file will contain the following mumbo jumbo: \hbox(6.83331+2.15277)x18.6108 .\tenrm T .\kern -1.66702 .\hbox(6.83331+0.0)x6.80557, shifted 2.15277 ..\tenrm E .\kern -1.25 .\tenrm X The first line means that \box0 is an hbox whose height, depth, and width are respectively 6.83331 pt, 2.15277 pt, and 18.6108 pt. Subsequent lines beginning with ‘.’ indicate that they are inside of a box. The first thing in this particular box is the letter T in font \tenrm; then comes a kern. The next item is an hbox that contains only the letter E; this box has the height, depth, and width of an E, and it has been shifted downward by 2.15277 pt (thereby accounting for the depth of the larger box).

Ä Ä

x EXERCISE 11.1

Why are there two dots in the ‘..\tenrm E’ line here?

Such displays of box contents will be discussed further in Chapters 12 and 17. They are used primarily for diagnostic purposes, when you are trying to figure out exactly what TEX thinks it’s doing. The main reason for bringing them up in the

Chapter 11: Boxes

present chapter is simply to provide a glimpse of how TEX represents boxes in its guts. A computer program doesn’t really move boxes around; it fiddles with lists of representations of boxes.

Ä

x EXERCISE 11.2

Ä

x EXERCISE 11.3

By running TEX, figure out how it actually handles italic corrections to characters: How are the corrections represented inside a box? The “opposite” of TEX’s logo—namely, T E X—is produced by \setbox1=\hbox{T\kern+.1667em\raise.5ex\hbox{E}\kern+.125em X} What would \showbox1 show now? (Try to guess, without running the machine.)

Ä

x EXERCISE 11.4

Why do you think the author of TEX didn’t make boxes more symmetrical between horizontal and vertical, by allowing reference points to be inside the boundary instead of insisting that the reference point must appear at the left edge of each box?

Ä Äx EXERCISE 11.5

Construct a \demobox macro for use in writing manuals like this, so that an author can write ‘\demobox{Tough exercise.}’ in order to typeset ‘ ’.

Ä Äx EXERCISE 11.6

Construct a \frac macro such that ‘\frac1/2’ yields ‘ 1/2’.

I have several boxes in my memory in which I will keep them all very safe, there shall not a one of them be lost. — IZAAK WALTON, The Compleat Angler (1653) How very little does the amateur, dwelling at home at ease, comprehend the labours and perils of the author. — R. L. STEVENSON and L. OSBOURNE, The Wrong Box (1889)

67

(page 68)

12 Glue

Chapter 12: Glue

But there’s more to the story than just boxes: There’s also some magic mortar called glue that TEX uses to paste boxes together. For example, there is a little space between the lines of text in this manual; it has been calculated so that the baselines of consecutive lines within a paragraph are exactly 12 points apart. And there is space between words too; such space is not an “empty” box, it is part of the glue between boxes. This glue can stretch or shrink so that the right-hand margin of each page comes out looking straight. When TEX makes a large box from a horizontal or vertical list of smaller boxes, there often is glue between the smaller boxes. Glue has three attributes, namely its natural space, its ability to stretch, and its ability to shrink. In order to understand how this works, consider the following example of four boxes in a horizontal list separated by three globs of glue: width 3

width 5

width 8

width 6

·················• space 9 stretch 3 shrink 1

·················• space 9 stretch 6 shrink 2

························• space 12 stretch 0 shrink 0

←−−−−−−−−−−−−−−−−−−−− width 52 −−−−−−−−−−−−−−−−−−−−→

The first glue element has 9 units of space, 3 of stretch, and 1 of shrink; the next one also has 9 units of space, but 6 units of stretch and 2 of shrink; the last one has 12 units of space, but it is unable to stretch or to shrink, so it will remain 12 units of space no matter what. The total width of boxes and glue in this example, considering only the space components of the glue, is 5 + 9 + 6 + 9 + 3 + 12 + 8 = 52 units. This is called the natural width of the horizontal list; it’s the preferred way to paste the boxes together. Suppose, however, that TEX is told to make the horizontal list into a box that is 58 units wide; then the glue has to stretch by 6 units. Well, there are 3 + 6 + 0 = 9 units of stretchability present, so TEX multiplies each unit of stretchability by 6/9 in order to obtain the extra 6 units needed. The first glob of glue becomes 9 + (6/9) × 3 = 11 units wide, the next becomes 9 + (6/9) × 6 = 13 units wide, the last remains 12 units wide, and we obtain the desired box looking like this:

······················• 9+2

··························• 9+4

························• 12 + 0

←−−−−−−−−−−−−−−−−−−−−−−− width 58 −−−−−−−−−−−−−−−−−−−−−−−→

On the other hand, if TEX is supposed to make a box 51 units wide from the given list, it is necessary for the glue to shrink by a total of one unit. There are three units of shrinkability present, so the first glob of glue would shrink by 1/3 and the second by 2/3.

69

70

Chapter 12: Glue

The process of determining glue thickness when a box is being made from a horizontal or vertical list is called setting the glue. Once glue has been set, it becomes rigid; it won’t stretch or shrink any more, and the resulting box is essentially indecomposable. Glue will never shrink more than its stated shrinkability. For example, the first glob of glue in our illustration will never be allowed to become narrower than 8 units wide, and TEX will never shrink the given horizontal list to make its total width less than 49 units. But glue is allowed to stretch arbitrarily far, whenever it has a positive stretch component. x EXERCISE 12.1 How wide would the glue globs be if the horizontal list in the illustration were to be made 100 units wide? Once you understand TEX’s concept of glue, you may well decide that it was misnamed; real glue doesn’t stretch or shrink in such ways, nor does it contribute much space between boxes that it welds together. Another word like “spring” would be much closer to the essential idea, since springs have a natural width, and since different springs compress and expand at different rates under tension. But whenever the author has suggested changing TEX’s terminology, numerous people have said that they like the word “glue” in spite of its inappropriateness; so the original name has stuck. Ä

TEX is somewhat reluctant to stretch glue more than the stated stretchability; therefore you can decide how big to make each aspect of the glue by using the following rules: (a) The natural glue space should be the amount of space that looks best. (b) The glue stretch should be the maximum amount of space that can be added to the natural spacing before the layout begins to look bad. (c) The glue shrink should be the maximum amount of space that can be subtracted from the natural spacing before the layout begins to look bad.

In most cases the designer of a book layout will have specified all the kinds of glue that are to be used, so a typist will not need to decide how big any glue attributes should be. For example, users of the plain TEX format of Appendix B can type ‘\smallskip’ when they want a little extra space between paragraphs; a \smallskip turns out to be 3 pt worth of vertical glue that can stretch or shrink by an additional 1 pt. Here is a \smallskip: Instead of sprinkling various amounts of glue throughout a manuscript, expressing each of them explicitly in terms of points, you will find it much better to explain your intentions more clearly by typing something like ‘\smallskip’ when you want abnormal spacing. The definition of \smallskip can readily be changed later, in case you want such spaces to be smaller or larger. Plain TEX also provides you with ‘\medskip’, which is worth two smallskips, and ‘\bigskip’, which is worth two medskips. Ä

A plain TEX \medskip appears before and after each “dangerous bend” section of this manual, so you have already seen numerous examples of such spacing

Chapter 12: Glue

before you knew what it was called. Vertical glue is created by writing ‘\vskiphgluei’, where hgluei is any glue specification. The usual way to specify hgluei to TEX is hdimeni plushdimeni minushdimeni where the ‘plushdimeni’ and ‘minushdimeni’ are optional and assumed to be zero if not present; ‘plus’ introduces the amount of stretchability, ‘minus’ introduces the amount of shrinkability. For example, Appendix B defines \medskip to be an abbreviation for ‘\vskip6pt plus2pt minus2pt’. The normal-space component of glue must always be given as an explicit hdimeni, even when it is zero.

Ä

Horizontal glue is created in the same way, but with \hskip instead of \vskip. For example, plain TEX defines \enskip as an abbreviation for the command ‘\hskip.5em\relax’; this skips horizontally by one “en,” i.e., by exactly half of an em in the current font. There is no stretching or shrinking in an \enskip. The control sequence \relax after ‘.5em’ prevents TEX from thinking that a keyword is present, in case the text following \enskip just happens to begin with ‘plus’ or ‘minus’.

One of the interesting things that happens when glue stretches and shrinks at different rates is that there might be glue with infinite stretchability. For example, consider again the four boxes we had at the beginning of this chapter, with the same glue as before except that the glue in the middle can stretch infinitely far. Now the total stretchability is infinite; and when the line has to grow, all of the additional space is put into the middle glue. If, for example, a box of width 58 is desired, the middle glue expands from 9 to 15 units, and the other spacing remains unchanged. If such infinitely stretchable glue is placed at the left of a row of boxes, the effect is to place them “flush right,” i.e., to move them over to the rightmost boundary of the constructed box. And if you take two globs of infinitely stretchable glue, putting one at the left and one at the right, the effect is to center the list of boxes within a larger box. This in fact is how the \centerline instruction works in plain TEX: It places infinite glue at both ends, then makes a box whose width is the current value of \hsize. The short story example of Chapter 6 used infinite glue not only for centering, but also in the \vfill instruction at the end; ‘\vfill’ essentially means “skip vertically by zero, but with infinite stretchability.” In other words, \vfill fills up the rest of the current page with blank space. Ä

TEX actually recognizes several kinds of infinity, some of which are “more infinite” than others. You can say both \vfil and \vfill; the second is stronger than the first. In other words, if no other infinite stretchability is present, \vfil will expand to fill the remaining space; but if both \vfil and \vfill are present simultaneously, the \vfill effectively prevents \vfil from stretching. You can think of it as if \vfil has one mile of stretchability, while \vfill has a trillion miles.

Ä

Besides \vfil and \vfill, TEX has \hfil and \hfill, for stretching indefinitely in the horizontal direction. You can also say \hss or \vss, in order to get glue that is infinitely shrinkable as well as infinitely stretchable. (The name ‘\hss’ stands for “horizontal stretch or shrink”; ‘\vss’ is its vertical counterpart.) Finally, the

71

72

Chapter 12: Glue

primitives \hfilneg and \vfilneg will cancel the stretchability of \hfil and \vfil; we shall discuss applications of these curious glues later.

Ä

Ä

Here are some examples of \hfil, using the \line macro of plain TEX, which creates an hbox whose width is the current \hsize: \line{This text will be flush left.\hfil} \line{\hfil This text will be flush right.} \line{\hfil This text will be centered.\hfil} \line{Some text flush left\hfil and some flush right.} \line{Alpha\hfil centered between Alpha and Omega\hfil Omega} \line{Five\hfil words\hfil equally\hfil spaced\hfil out.}

x EXERCISE 12.2

Describe the result of \line{\hfil\hfil What happens now?\hfil} \line{\hfill\hfil and now?\hfil}

Ä Äx EXERCISE 12.3

How do the following three macros behave differently?

\def\centerlinea#1{\line{\hfil#1\hfil}} \def\centerlineb#1{\line{\hfill#1\hfill}} \def\centerlinec#1{\line{\hss#1\hss}}

Ä

In order to specify such infinities, you are allowed to use the special units ‘fil’, ‘fill’, and ‘filll’ in the hdimeni parts of a stretchability or shrinkability component. For example, \vfil, \vfill, \vss, and \vfilneg are essentially equivalent to the glue specifications \vskip \vskip \vskip \vskip

0pt 0pt 0pt 0pt

plus plus plus plus

1fil 1fill 1fil minus 1fil -1fil

respectively. It’s usually best to stick to the first order infinity (fil) as much as you can, resorting to second order (fill) only when you really need something extremely infinite. Then the ultimate order (filll) is always available as a last resort in emergencies. (TEX does not provide a ‘\vfilll’ primitive, since the use of this highest infinity is not encouraged.) You can use fractional multiples of infinity like ‘3.25fil’, as long as you stick to fewer than 16384 fil units. TEX actually does its calculations with integer multiples of 2−16 fil (or fill or filll); so 0.000007filll turns out to be indistinguishable from 0pt, but 0.00001filll is infinitely greater than 16383.99999fill.

Now here’s something important for all TEXnical typists to know: Plain TEX puts extra space at the end of a sentence; furthermore, it automatically increases the stretchability (and decreases the shrinkability) after punctuation marks. The reason is that it’s usually better to put more space after punctuation than between two ordinary words, when spreading a line out to reach the desired margins. Consider, for example, the following sentences from a classic kindergarten pre-primer: ‘‘Oh, oh!’’ cried Baby Sally. Dick and Jane laughed.

Chapter 12: Glue

If TEX sets this at its natural width, all the spaces will be the same, except after the quote and after ‘Baby Sally.’: “Oh, oh!” cried Baby Sally. Dick and Jane laughed. But if the line needs to be expanded by 5 points, 10 points, 15 points, or more, TEX will set it as “Oh, “Oh, “Oh, “Oh,

oh!” oh!” oh!” oh!”

cried Baby Sally. Dick and Jane laughed. cried Baby Sally. Dick and Jane laughed. cried Baby Sally. Dick and Jane laughed. cried Baby Sally. Dick and Jane laughed.

The glue after the comma stretches at 1.25 times the rate of the glue between adjacent words; the glue after the period and after the !’’ stretches at 3 times the rate. There is no glue between adjacent letters, so individual words will always look the same. If TEX had to shrink this line to its minimum width, the result would be “Oh, oh!” cried Baby Sally. Dick and Jane laughed. The glue after a comma shrinks only 80 percent as much as ordinary inter-word glue, and after a period or exclamation point or question mark it shrinks by only one third as much. This all makes for nice-looking output, but it unfortunately adds a bit of a burden to your job as a typist, because TEX’s rule for determining the end of a sentence doesn’t always work. The problem is that a period sometimes comes in the middle of a sentence . . . like when it is used (as here) to make an “ellipsis” of three dots. Moreover, if you try to specify ‘. . .’ by typing three periods in a row, you get ‘...’—the dots are too close together. One way to handle this is to go into mathematics mode, using the \ldots control sequence defined in plain TEX format. For example, if you type Hmmm $\ldots$ I wonder why? the result is ‘Hmmm . . . I wonder why?’. This works because math formulas are exempt from the normal text spacing rules. Chapter 18 has more to say about \ldots and related topics. Abbreviations present problems too. For example, the short story in Chapter 6 referred to ‘Mr. Drofnats’; TEX must be told somehow that the period after ‘Mr.’ or ‘Mrs.’ or ‘Ms.’ or ‘Prof.’ or ‘Dr.’ or ‘Rt. Hon.’, etc., doesn’t count as a sentence-ending full stop. We avoided that embarrassment in Chapter 6 by typing ‘Mr.~Drofnats’; the “tie” mark ~ tells plain TEX to insert a normal space, and to refrain from breaking between lines at that space. Another way to get TEX to put out a normal space is to type ‘\Ã’ (control space); e.g., ‘Mr.\ Drofnats’ would be almost the same as ‘Mr.~Drofnats’, except that a line might end after the ‘Mr.’.

73

74

Chapter 12: Glue

The tie mark is best for abbreviations within a name, and after several other common abbreviations like ‘Fig.’ and ‘cf.’ and ‘vs.’ and ‘resp.’; you will find that it’s easy to train yourself to type ‘cf.~Fig.~5’. In fact, it’s usually wise to type ~ (instead of a space) just after a common abbreviation that occurs in the middle of a sentence. Manuals of style will tell you that the abbreviations ‘e.g.’ and ‘i.e.’ should always be followed by commas, never by spaces, so those particular cases shouldn’t need any special treatment. The only remaining abbreviations that arise with significant frequency occur in bibliographic references; control spaces are appropriate here. If, for example, you are typing a manuscript that refers to ‘Proc. Amer. Math. Soc.’, you should say Proc.\ Amer.\ Math.\ Soc. Granted that this input looks a bit ugly, it makes the output look right. It’s one of the things we occasionally must do when dealing with a computer that tries to be smart. x EXERCISE 12.4 Explain how to type the following sentence: “Mr. & Mrs. User were married by Rev. Drofnats, who preached on Matt. 19 : 3–9.” x EXERCISE 12.5 Put the following bibliographic reference into plain TEX language: Donald E. Knuth, “Mathematical typography,” Bull. Amer. Math. Soc. 1 (1979), 337–372. On the other hand, if you don’t care about such refinements of spacing you can tell plain TEX to make all spaces the same, regardless of punctuation marks, by simply typing ‘\frenchspacing’ at the beginning of your manuscript. French spacing looks like this: “Oh, oh!” cried Baby Sally. Dick and Jane laughed. You can also shift back and forth between the two styles, either by saying ‘\nonfrenchspacing’ to establish sophisticated spacing, or by making your use of \frenchspacing local to some group. For example, you might want to use French spacing only when typing the bibliography of some document. Ä

TEX doesn’t consider a period or question mark or exclamation point to be the end of a sentence if the preceding character is an uppercase letter, since TEX assumes that such uppercase letters are most likely somebody’s initials. Thus, for example, the ‘\’ is unnecessary after the ‘I.’ in ‘Dr.~Livingstone~I.\ Presume’; that particular period is not assumed to be a full stop.

Ä

x EXERCISE 12.6

What can you do to make TEX recognize the ends of sentences that do end with uppercase letters (e.g., ‘. . . launched by NASA.’ or ‘Did I?’ or ‘. . . see Appendix A.’)?

Chapter 12: Glue

Ä

You can see the glue that TEX puts between words by looking at the contents of hboxes in the internal diagnostic format that we discussed briefly in Chapter 11. For example, Baby Sally’s exclamation begins as follows, after TEX has digested it and put it into a box, assuming \nonfrenchspacing: .\tenrm \ (ligature .\tenrm O .\tenrm h .\tenrm , .\glue 3.33333 plus .\tenrm o .\tenrm h .\tenrm ! .\tenrm " (ligature .\glue 4.44444 plus .\tenrm c .\tenrm r .\tenrm i .\tenrm e .\tenrm d .\glue 3.33333 plus .\tenrm B .\tenrm a .\tenrm b .\kern-0.27779 .\tenrm y .\glue 3.33333 plus .\tenrm S .\tenrm a .\tenrm l .\tenrm l .\tenrm y .\kern-0.83334 .\tenrm . .\glue 4.44444 plus

‘‘)

2.08331 minus 0.88889

’’) 4.99997 minus 0.37036

1.66666 minus 1.11111

1.66666 minus 1.11111

4.99997 minus 0.37036

The normal interword glue in font \tenrm is 3.33333 pt, plus 1.66666 pt of stretchability, minus 1.11111 pt of shrinkability. Notice that the interword \glue in this list stretches more, and shrinks less, after the punctuation marks; and the natural space is in fact larger at the end of each sentence. This example also shows several other things that TEX does while it processes the sample line of text: It converts ‘‘ and ’’ into single characters, i.e., ligatures; and it inserts small kerns in two places to improve the spacing. A \kern is similar to glue, but it is not the same, because kerns cannot stretch or shrink; furthermore, TEX will never break a line at a kern, unless that kern is immediately followed by glue.

Ä Ä You may be wondering what TEX’s rules for interword glue really are, exactly.

For example, how did TEX remember the effect of Baby Sally’s exclamation point, when quotation marks intervened before the next space? The details are slightly

75

76

Chapter 12: Glue

tricky, but not incomprehensible. When TEX is processing a horizontal list of boxes and glue, it keeps track of a positive integer called the current “space factor.” The space factor is normally 1000, which means that the interword glue should not be modified. If the space factor f is different from 1000, the interword glue is computed as follows: Take the normal space glue for the current font, and add the extra space if f ≥ 2000. (Each font specifies a normal space, normal stretch, normal shrink, and extra space; for example, these quantities are 3.33333 pt, 1.66666 pt, 1.11111 pt, and 1.11111 pt, respectively, in cmr10. We’ll discuss such font parameters in greater detail later.) Then the stretch component is multiplied by f /1000, while the shrink component is multiplied by 1000/f .

Ä Ä However, TEX has two parameters \spaceskip and \xspaceskip that allow

you to override the normal spacing of the current font. If f ≥ 2000 and if \xspaceskip is nonzero, the \xspaceskip glue is used for an interword space. Otherwise if \spaceskip is nonzero, the \spaceskip glue is used, with stretch and shrink components multiplied by f /1000 and 1000/f . For example, the \raggedright macro of plain TEX uses \spaceskip and \xspaceskip to suppress all stretching and shrinking of interword spaces.

Ä Ä The space factor f is 1000 at the beginning of a horizontal list, and it is set to

1000 just after a non-character box or a math formula has been put onto the current horizontal list. You can say ‘\spacefactor=hnumberi’ to assign any particular value to the space factor; but ordinarily, f gets set to a number other than 1000 only when a simple character box goes on the list. Each character has a space factor code, and when a character whose space factor code is g enters the current list the normal procedure is simply to assign g as the new space factor. However, if g is zero, f is not changed; and if f < 1000 < g, the space factor is set to 1000. (In other words, f doesn’t jump from a value less than 1000 to a value greater than 1000 in a single step.) The maximum space factor is 32767 (which is much higher than anybody would ever want to use).

Ä Ä When INITEX creates a brand new TEX, all characters have a space factor code of 1000, except that the uppercase letters ‘A’ through ‘Z’ have code 999. (This slight difference is what makes punctuation act differently after an uppercase letter; do you see why?) Plain TEX redefines a few of these codes using the \sfcode primitive, which is similar to \catcode (see Appendix B); for example, the instructions \sfcode‘)=0

\sfcode‘.=3000

make right parentheses “transparent” to the space factor, while tripling the stretchability after periods. The \frenchspacing operation resets \sfcode‘. to 1000.

Ä Ä When ligatures are formed, or when a special character is specified via \char,

the space factor code is computed from the individual characters that generated the ligature. For example, plain TEX sets the space factor code for single-rightquote to zero, so that the effects of punctuation will be propagated. Two adjacent characters ’’ combine to form a ligature that is in character position ´042 ; but the space factor code of this double-right-quote ligature is never examined by TEX, so plain TEX does not assign any value to \sfcode’042.

Ä Äx EXERCISE 12.7

What are the space factors after each token of the Dick-and-Jane example?

Chapter 12: Glue

Ä

Here’s the way TEX goes about setting the glue when an hbox is being wrapped up: The natural width, x, of the box contents is determined by adding up the widths of the boxes and kerns inside, together with the natural widths of all the glue inside. Furthermore the total amount of glue stretchability and shrinkability in the box is computed; let’s say that there’s a total of y0 + y1 fil + y2 fill + y3 filll available for stretching and z0 + z1 fil + z2 fill + z3 filll available for shrinking. Now the natural width x is compared to the desired width w. If x = w, all glue gets its natural width. Otherwise the glue will be modified, by computing a “glue set ratio” r and a “glue set order” i in the following way: (a) If x < w, TEX attempts to stretch the contents of the box; the glue order is the highest subscript i such that yi is nonzero, and the glue ratio is r = (w − x)/yi . (If y0 = y1 = y2 = y3 = 0, there’s no stretchability; both i and r are set to zero.) (b) If x > w, TEX attempts to shrink the contents of the box in a similar way; the glue order is the highest subscript i such that zi 6= 0, and the glue ratio is normally r = (x − w)/zi . However, r is set to 1.0 in the case i = 0 and x − w > z0 , because the maximum shrinkability must not be exceeded. (c) Finally, every glob of glue in the horizontal list being boxed is modified. Suppose the glue has natural width u, stretchability y, and shrinkability z, where y is a jth order infinity and z is a kth order infinity. Then if x < w (stretching), this glue takes the new width u + ry if j = i; it keeps its natural width u if j 6= i. If x > w (shrinking), this glue takes the new width u − rz if k = i; it keeps its natural width u if k 6= i. Notice that stretching or shrinking occurs only when the glue has the highest order of infinity that doesn’t cancel out.

Ä

TEX will construct an hbox that has a given width w if you issue the command ‘\hbox to hdimeni{hcontents of boxi}’, where w is the value of the hdimeni. For example, the \line macro discussed earlier in this chapter is simply an abbreviation for ‘\hbox to\hsize’. TEX also allows you to specify the exact amount of stretching or shrinking; the command ‘\hbox spreadhdimeni{hcontents of boxi}’ creates a box whose width w is a given amount more than the natural width of the contents. For example, one of the boxes displayed earlier in this chapter was generated by \hbox spread 5pt{‘‘Oh, oh!’’ ... laughed.} In the simplest case, when you just want a box to have its natural width, you don’t have to write ‘\hbox spread 0pt’; you can simply say ‘\hbox{hcontents of boxi}’.

Ä

The baseline of a constructed hbox is the common baseline of the boxes inside. (More precisely, it’s the common baseline that they would share if they weren’t raised or lowered.) The height and depth of a constructed hbox are determined by the maximum distances by which the interior boxes reach above and below the baseline, respectively. The result of \hbox never has negative height or negative depth, but the width can be negative.

Ä

x EXERCISE 12.8

Assume that \box1 is 1 pt high, 1 pt deep, and 1 pt wide; \box2 is 2 pt high, 2 pt deep, and 2 pt wide. A third box is formed by saying \setbox3=\hbox to3pt{\hfil\lower3pt\box1\hskip-3pt plus3fil\box2} What are the height, depth, and width of \box3? Describe the position of the reference points of boxes 1 and 2 with respect to the reference point of box 3.

77

78

Chapter 12: Glue

Ä

The process of setting glue for vboxes is similar to that for hboxes; but before we study the \vbox operation, we need to discuss how TEX stacks boxes up vertically so that their baselines tend to be a fixed distance apart. The boxes in a horizontal list often touch each other, but it’s usually wrong to do this in a vertical list; imagine how awful a page would look if its lines of type were brought closer together whenever they didn’t contain tall letters, or whenever they didn’t contain any letters that descended below the baseline.

Ä

TEX’s solution to this problem involves three primitives called \baselineskip, \lineskip, and \lineskiplimit. A format designer chooses values of these three quantities by writing \baselineskip=hgluei \lineskip=hgluei \lineskiplimit=hdimeni

and the interpretation is essentially this: Whenever a box is added to a vertical list, TEX inserts “interline glue” intended to make the distance between the baseline of the new box and the baseline of the previous box exactly equal to the value of \baselineskip. But if the interline glue calculated by this rule would cause the top edge of the new box to be closer than \lineskiplimit to the bottom edge of the previous box, then \lineskip is used as the interline glue. In other words, the distance between adjacent baselines will be the \baselineskip setting, unless that would bring the boxes too close together; the \lineskip glue will separate adjacent boxes in the latter case.

Ä

The rules for interline glue in the previous paragraph are carried out without regard to other kinds of glue that might be present; all vertical spacing due to explicit appearances of \vskip and \kern acts independently of the interline glue. Thus, for example, a \smallskip between two lines always makes their baselines further apart than usual, by the amount of a \smallskip; it does not affect the decision about whether \lineskip glue is used between those lines.

Ä

For example, let’s suppose that \baselineskip=12pt plus 2pt, \lineskip= 3pt minus 1pt, and \lineskiplimit=2pt. (These values aren’t particularly useful; they have simply been chosen to illustrate the rules.) Suppose further that a box whose depth is 3 pt was most recently added to the current vertical list; we are about to add a new box whose height is h. If h = 5 pt, the interline glue will be 4 pt plus 2 pt, since this will make the baselines 12 pt plus 2 pt apart when we add h and the previous depth to the interline glue. But if h = 8 pt, the interline glue will be 3 pt minus 1 pt, since \lineskip will be chosen in order to keep from violating the given \lineskiplimit when stretching and shrinking are ignored.

Ä

When you are typesetting a document that spans several pages, it’s generally best to define the \baselineskip so that it cannot stretch or shrink, because this will give more uniformity to the pages. A small variation in the distance between baselines—say only half a point—can make a substantial difference in the appearance of the type, since it significantly affects the proportion of white to black. On the other hand, if you are preparing a one-page document, you might want to give the baselineskip some stretchability, so that TEX will help you fit the copy on the page.

Ä

x EXERCISE 12.9

What settings of \baselineskip, \lineskip, and \lineskiplimit will cause

Chapter 12: Glue

the interline glue to be a “continuous” function of the next box height (i.e., the interline glue will never change a lot when the box height changes only a little)?

Ä

A study of TEX’s internal box-and-glue representation should help to firm up some of these ideas. Here is an excerpt from the vertical list that TEX constructed when it was typesetting this very paragraph: \glue 6.0 plus 2.0 minus 2.0 \glue(\parskip) 0.0 plus 1.0 \glue(\baselineskip) 1.25 \hbox(7.5+1.93748)x312.0, glue set 0.80154, shifted 36.0 [] \penalty 10000 \glue(\baselineskip) 2.81252 \hbox(6.25+1.93748)x312.0, glue set 0.5816, shifted 36.0 [] \penalty 50 \glue(\baselineskip) 2.81252 \hbox(6.25+1.75)x348.0, glue set 116.70227fil [] \penalty 10000 \glue(\abovedisplayskip) 6.0 plus 3.0 minus 1.0 \glue(\lineskip) 1.0 \hbox(149.25+0.74998)x348.0 [] The first \glue in this example is the \medskip that precedes each dangerous-bend paragraph. Then comes the \parskip glue, which is automatically supplied before the first line of a new paragraph. Then comes some interline glue of 1.25 pt; it was calculated to make a total of 11 pt when the height of the next box (7.5 pt) and the depth of the previous box were added. (The previous box is not shown—it’s the bottom line of exercise 12.9—but we can deduce that its depth was 2.25 pt.) The \hbox that follows is the first line of this paragraph; it has been shifted right 36 pt because of hanging indentation. The glue set ratio for this hbox is 0.80154; i.e., the glue inside is stretched by 80.154% of its stretchability. (In the case of shrinking, the ratio following ‘glue set’ would have been preceded by ‘- ’; hence we know that stretching is involved here.) TEX has put ‘[]’ at the end of each hbox line to indicate that there’s something in the box that isn’t shown. (The box contents would have been displayed completely, if \showboxdepth had been set higher.) The \penalty indications are used to discourage bad breaks between pages, as we will see later. The third hbox has a glue ratio of 116.70227, which applies to first-order-infinite stretching (i.e., fil); this results from an \hfil that was implicitly inserted just before the displayed material, to fill up the third line of the paragraph. Finally the big hbox whose height is 149.25 pt causes \lineskip to be the interline glue. This large box contains the individual lines of typewriter type that are displayed; they have been packaged into a single box so that they cannot be split between pages. Careful study of this example will teach you a lot about TEX’s inner workings.

Ä

Exception: No interline glue is inserted before or after a rule box. You can also inhibit interline glue by saying \nointerlineskip between boxes.

Ä Ä TEX’s implementation of interline glue involves another primitive quantity called \prevdepth, which usually contains the depth of the most recent box on the current vertical list. However, \prevdepth is set to the sentinel value −1000 pt

79

80

Chapter 12: Glue

at the beginning of a vertical list, or just after a rule box; this serves to suppress the next interline glue. The user can change the value of \prevdepth at any time when building a vertical list; thus, for example, the \nointerlineskip macro of Appendix B simply expands to ‘\prevdepth=-1000pt’.

Ä Ä Here are the exact rules by which TEX calculates the interline glue between

boxes: Assume that a new box of height h (not a rule box) is about to be appended to the bottom of the current vertical list, and let \prevdepth = p, \lineskiplimit = l, \baselineskip = (b plus y minus z). If p ≤ −1000 pt, no interline glue is added. Otherwise if b − p − h ≥ l, the interline glue ‘(b − p − h) plus y minus z’ will be appended just above the new box. Otherwise the \lineskip glue will be appended. Finally, \prevdepth is set to the depth of the new box.

Ä Äx EXERCISE 12.10

Mr. B. L. User had an application in which he wanted to put a number of boxes together in a vertical list, with no space between them. He didn’t want to say \nointerlineskip after each box; so he decided to set \baselineskip, \lineskip, and \lineskiplimit all equal to 0pt. Did this work?

Ä

The vertical analog of \hbox is \vbox, and TEX will obey the commands ‘\vbox tohdimeni’ and ‘\vbox spreadhdimeni’ in about the way you would expect, by analogy with the horizontal case. However, there’s a slight complication because boxes have both height and depth in the vertical direction, while they have only width in the horizontal direction. The dimension in a \vbox command refers to the final height of the vbox, so that, for example, ‘\vbox to 50pt{...}’ produces a box that is 50 pt high; this is appropriate because everything that can stretch or shrink inside a vbox appears in the part that contributes to the height, while the depth is unaffected by glue setting.

Ä

The depth of a constructed \vbox is best thought of as the depth of the bottom box inside. Thus, a vbox is conceptually built by taking a bunch of boxes and arranging them so that their reference points are lined up vertically; then the reference point of the lowest box is taken as the reference point of the whole, and the glue is set so that the final height has some desired value.

Ä

However, this description of vboxes glosses over some technicalities that come up when you consider unusual cases. For example, TEX allows you to shift boxes in a vertical list to the right or to the left by saying ‘\moverighthdimenihboxi’ or ‘\movelefthdimenihboxi’; this is like the ability to \raise or \lower boxes in a horizontal list, and it implies that the reference points inside a vbox need not always lie in a vertical line. Furthermore, it is necessary to guard against boxes that have too much depth, lest they extend too far into the bottom margin of a page; and later chapters will point out that vertical lists can contain other things like penalties and marks, in addition to boxes and glue.

Ä Ä Therefore, the actual rules for the depth of a constructed vbox are somewhat

TEXnical. Here they are: Given a vertical list that is being wrapped up via \vbox, the problem is to determine its natural depth. (1) If the vertical list contains no boxes, the depth is zero. (2) If there’s at least one box, but if the final box is followed by kerning or glue, possibly with intervening penalties or other things, the depth is zero. (3) If there’s at least one box, and if the final box is not followed by kerning or glue,

Chapter 12: Glue

the depth is the depth of that box. (4) However, if the depth computed by rules (1), (2), or (3) exceeds \boxmaxdepth, the depth will be the current value of \boxmaxdepth. (Plain TEX sets \boxmaxdepth to the largest possible dimension; therefore rule (4) won’t apply unless you specify a smaller value. When rule (4) does decrease the depth, TEX adds the excess depth to the box’s natural height, essentially moving the reference point down until the depth has been reduced to the stated maximum.)

Ä

The glue is set in a vbox just as in an hbox, by determining a glue set ratio and a glue set order, based on the difference between the natural height x and the desired height w, and based on the amounts of stretchability and shrinkability that happen to be present.

Ä

The width of a computed \vbox is the maximum distance by which an enclosed box extends to the right of the reference point, taking possible shifting into account. This width is always nonnegative.

Ä

x EXERCISE 12.11

Assume that \box1 is 1 pt high, 1 pt deep, and 1 pt wide; \box2 is 2 pt high, 2 pt deep, and 2 pt wide; the baselineskip, lineskip, and lineskiplimit are all zero; and the \boxmaxdepth is very large. A third box is formed by saying \setbox3=\vbox to3pt{\moveright3pt\box1\vskip-3pt plus3fil\box2} What are the height, depth, and width of \box3? Describe the position of the reference points of boxes 1 and 2 with respect to the reference point of box 3.

Ä Äx EXERCISE 12.12

Under the assumptions of the previous exercise, but with \baselineskip=9pt minus3fil, describe \box4 after \setbox4=\vbox to4pt{\vss\box1\moveleft4pt\box2\vss}

Ä Äx EXERCISE 12.13

Solve the previous problem but with \boxmaxdepth=-4pt.

Ä

We have observed that \vbox combines a bunch of boxes into a larger box that has the same baseline as the bottom box inside. TEX has another operation called \vtop, which gives you a box like \vbox but with the same baseline as the top box inside. For example, \hbox{Here are \vtop{\hbox{two lines}\hbox{of text.}}} produces Here are two lines of text.

Ä Ä You can say ‘\vtop tohdimeni’ and ‘\vtop spreadhdimeni’ just as with \vbox,

but you should realize what such a construction means. TEX implements \vtop as follows: (1) First a vertical box is formed as if \vtop had been \vbox, using all of the rules for \vbox as given above. (2) The final height x is defined to be zero unless the very first item inside the new vbox is a box; in the latter case, x is the height of that box. (3) Let h and d be the height and depth of the vbox in step (1). TEX completes the \vtop by moving the reference point up or down, if necessary, so that the box has height x and depth h + d − x.

81

82

Chapter 12: Glue

Ä Äx EXERCISE 12.14

Describe the empty boxes that you get from ‘\vbox tohdimeni{}’ and ‘\vtop tohdimeni{}’. What are their heights, depths, and widths?

Ä Äx EXERCISE 12.15

Define a macro \nullbox#1#2#3 that produces a box whose height, depth, and width are given by the three parameters. The box should contain nothing that will show up in print.

Ä

The \vbox operation tends to produce boxes with large height and small depth, while \vtop tends to produce small height and large depth. If you’re trying to make a vertical list out of big vboxes, however, you may not be satisfied with either \vbox or \vtop; you might well wish that a box had two reference points simultaneously, one for the top and one for the bottom. If such a dual-reference-point scheme were in use, one could define interline glue based on the distance between the lower reference point of one box and the upper reference point of its successor in a vertical list. But alas, TEX gives you only one reference point per box.

Ä

There’s a way out of this dilemma, using an important idea called a “strut.” Plain TEX defines \strut to be an invisible box of width zero that extends just enough above and below the baseline so that you would need no interline glue at all if every line contained a strut. (Baselines are 12 pt apart in plain TEX; it turns out that \strut is a vertical rule, 8.5 pt high and 3.5 pt deep and 0 pt wide.) If you contrive to put a strut on the top line and another on the bottom line, inside your large vboxes, then it’s possible to obtain the correct spacing in a larger assembly by simply letting the boxes butt together. For example, the \footnote macro in Appendix B puts struts at the beginning and end of every footnote, so that the spacing will be right when several footnotes occur together at the bottom of some page.

Ä

If you understand boxes and glue, you’re ready to learn the \rlap and \llap macros of plain TEX; these names are abbreviations for “right overlap” and “left overlap.” Saying ‘\rlap{hsomethingi}’ is like typesetting hsomethingi and then backing up as if you hadn’t typeset anything. More precisely, ‘\rlap{hsomethingi}’ creates a box of width zero, with ‘hsomethingi’ appearing just at the right of that box (but not taking up any space). The \llap macro is similar, but it does the backspacing first; in other words, ‘\llap{hsomethingi}’ creates a box of width zero, with ‘hsomethingi’ extending just to the left of that box. Using typewriter type, for example, you can typeset ‘/ =’ by saying either ‘\rlap/=’ or ‘/\llap=’. It’s possible to put text into the left margin using \llap, or into the right margin using \rlap, because TEX does not insist that the contents of a box must be strictly confined within that box’s boundaries.

Ä

The interesting thing about \rlap and \llap is that they can be done so simply with infinite glue. One way to define \rlap would be \def\rlap#1{{\setbox0=\hbox{#1}\copy0\kern-\wd0}}

but there’s no need to do such a lengthy computation. The actual definition in Appendix B is much more elegant, namely, \def\rlap#1{\hbox to 0pt{#1\hss}}

Chapter 12: Glue

and it’s worth pondering why this works. Suppose, for example, that you’re doing \rlap{g} where the letter ‘g’ is 5 pt wide. Since \rlap makes an hbox of width 0 pt, the glue represented by \hss must shrink by 5 pt. Well, that glue has 0 pt as its natural width, but it has infinite shrinkability, so it can easily shrink to −5 pt; and ‘\hskip-5pt’ is exactly what \rlap wants in this case.

Ä

x EXERCISE 12.16

Ä

x EXERCISE 12.17

Guess the definition of \llap, without peeking at Appendices A or B. (This is a sequel to exercise 12.2, but it’s trickier.) Describe the result of

\line{\hfil A puzzle.\hfilneg}

There was things which he stretched, but mainly he told the truth. — MARK TWAIN, Huckleberry Finn (1884) Every shape exists only because of the space around it. . . . Hence there is a ‘right’ position for every shape in every situation. If we succeed in finding that position, we have done our job. — JAN TSCHICHOLD, Typographische Gestaltung (1935)

83

(page 84)

13 Modes

Chapter 13: Modes

Just as people get into different moods, TEX gets into different “modes.” (Except that TEX is more predictable than people.) There are six modes: Vertical mode. [Building the main vertical list, from which the pages of output are derived.] Internal vertical mode. [Building a vertical list for a vbox.] Horizontal mode. [Building a horizontal list for a paragraph.] Restricted horizontal mode. [Building a horizontal list for an hbox.] Math mode. [Building a mathematical formula to be placed in a horizontal list.] Display math mode. [Building a mathematical formula to be placed on a line by itself, temporarily interrupting the current paragraph.] In simple situations, you don’t need to be aware of what mode TEX is in, because the computer just does the right thing. But when you get an error message that says ‘ ! You can’t do such-and-such in restricted horizontal mode ’, a knowledge of modes helps to explain why TEX thinks you goofed. Basically TEX is in one of the vertical modes when it is preparing a list of boxes and glue that will be placed vertically above and below one another on the page; it’s in one of the horizontal modes when it is preparing a list of boxes and glue that will be strung out horizontally next to each other with baselines aligned; and it’s in one of the math modes when it is reading a formula. A play-by-play account of a typical TEX job should make the mode idea clear: At the beginning, TEX is in vertical mode, ready to construct pages. If you specify glue or a box when TEX is in vertical mode, the glue or the box gets placed on the current page below what has already been specified. For example, the \vskip instructions in the sample run we discussed in Chapter 6 contributed vertical glue to the page; and the \hrule instructions contributed horizontal rules at the top and bottom of the story. The \centerline commands also produced boxes that were included in the main vertical list; but those boxes required a bit more work than the rule boxes: TEX was in vertical mode when it encountered ‘\centerline{\bf A SHORT STORY}’, and it went temporarily into restricted horizontal mode while processing the words ‘A SHORT STORY’; then the digestive process returned to vertical mode, after setting the glue in the \centerline box. Continuing with the example of Chapter 6, TEX switched into horizontal mode as soon as it read the ‘O’ of ‘Once upon a time’. Horizontal mode is the mode for making paragraphs. The entire paragraph (lines 7 to 11 of the story file) was input in horizontal mode; then the text was divided into output lines of the appropriate width, those lines were put in boxes and appended to the page (with appropriate interline glue between them), and TEX was back in vertical mode. The ‘M’ on line 12 started up horizontal mode again. When TEX is in vertical mode or internal vertical mode, the first token of a new paragraph changes the mode to horizontal for the duration of a paragraph.

85

86

Chapter 13: Modes

In other words, things that do not have a vertical orientation cause the mode to switch automatically from vertical to horizontal. This occurs when you type any character, or \char or \accent or \hskip or \Ã or \vrule or math shift ($); TEX inserts the current paragraph indentation and rereads the horizontal token as if it had occurred in horizontal mode. Ä You can also tell TEX explicitly to go into horizontal mode, instead of relying on such implicit mode-switching, by saying ‘\indent’ or ‘\noindent’. For example, if line 7 of the story file in Chapter 6 had begun \indent Once upon a time, ... the same output would have been obtained, because ‘\indent’ would have instructed TEX to begin the paragraph. And if that line had begun with \noindent Once upon a time, ... the first paragraph of the story would not have been indented. The \noindent command simply tells TEX to enter horizontal mode if the current mode is vertical or internal vertical; \indent is similar, but it also creates an empty box whose width is the current value of \parindent, and it puts this empty box into the current horizontal list. Plain TEX sets \parindent=20pt. If you say \indent\indent, you get double indentation; if you say \noindent\noindent, the second \noindent does nothing. Ä x EXERCISE 13.1 If you say ‘\hbox{...}’ in horizontal mode, TEX will construct the specified box and it will contribute the result to the current paragraph. Similarly, if you say ‘\hbox{...}’ in vertical mode, TEX will construct a box and contribute it to the current page. What can you do if you want to begin a paragraph with an \hbox? When handling simple manuscripts, TEX spends almost all of its time in horizontal mode (making paragraphs), with brief excursions into vertical mode (between paragraphs). A paragraph is completed when you type \par or when your manuscript has a blank line, since a blank line is converted to \par by the reading rules of Chapter 8. A paragraph also ends when you type certain things that are incompatible with horizontal mode. For example, the command ‘\vskip 1in’ on line 16 of Chapter 6’s story file was enough to terminate the paragraph about ‘...beautiful documents.’; no \par was necessary, since \vskip introduced vertical glue that couldn’t belong to the paragraph. If a begin-math token ($) appears in horizontal mode, TEX plunges into math mode and processes the formula up until the closing ‘’, then appends the text of this formula to the current paragraph and returns to horizontal mode. Thus, in the “I wonder why?” example of Chapter 12, TEX went into math mode temporarily while processing \ldots, treating the dots as a formula. However, if two consecutive begin-math tokens appear in a paragraph ($$), TEX interrupts the paragraph where it is, contributes the paragraph-so-far to the enclosing vertical list, then processes a math formula in display math mode, then contributes this formula to the enclosing list, then returns to horizontal mode for more of the paragraph. (The formula to be displayed should Chapter 13: Modes end with ‘$$’.) For example, suppose you type the number $$\pi \approx 3.1415926536$$ is important. TEX goes into display math mode between the ’s, and the output you get states that the number π ≈ 3.1415926536 is important. TEX ignores blank spaces and blank lines (or \par commands) when it’s in vertical or internal vertical mode, so you need not worry that such things might change the mode or affect a printed document. A control space (\Ã) will, however, be regarded as the beginning of a paragraph; the paragraph will start with a blank space after the indentation. At the end of a TEX manuscript it’s usually best to finish everything off by typing ‘\bye’, which is plain TEX’s abbreviation for ‘\vfill\eject\end’. The ‘\vfill’ gets TEX into vertical mode and inserts enough space to fill up the last page; ‘\eject’ outputs that last page; and ‘\end’ sends the computer into its endgame routine. Ä TEX gets into internal vertical mode when you ask it to construct something from a vertical list of boxes (using \vbox or \vtop or \vcenter or \valign or \vadjust or \insert). It gets into restricted horizontal mode when you ask it to construct something from a horizontal list of boxes (using \hbox or \halign). Box construction is discussed in Chapters 12 and 21. We will see later that there is very little difference between internal vertical mode and ordinary vertical mode, and very little difference between restricted horizontal mode and ordinary horizontal mode; but they aren’t quite identical, because they have different goals. Ä Whenever TEX looks at a token of input to decide what should be done next, the current mode has a potential influence on what that token means. For example, \kern specifies vertical spacing in vertical mode, but it specifies horizontal spacing in horizontal mode; a math shift character like ‘’ causes entry to math mode from horizontal mode, but it causes exit from math mode when it occurs in math mode; two consecutive math shifts () appearing in horizontal mode will initiate display math mode, but in restricted horizontal mode they simply denote an empty math formula. TEX uses the fact that some operations are inappropriate in certain modes to help you recover from errors that might have crept into your manuscript. Chapters 24 to 26 explain exactly what happens to every possible token in every possible mode. Ä TEX often interrupts its work in one mode to do some task in another mode, after which the original mode is resumed again. For example, you can say ‘\hbox{’ in any mode; when TEX digests this, it suspends whatever else it was doing and enters restricted horizontal mode. The matching ‘}’ will eventually cause the hbox to be completed, whereupon the postponed task will be taken up anew. In this sense TEX can be in many modes simultaneously, but only the innermost mode influences the calculations at any time; the other modes have been pushed out of TEX’s consciousness. 87 88 Chapter 13: Modes Ä One way to become familiar with TEX’s modes is to consider the following curious test file called modes.tex, which exercises all the modes at once: 1 2 3 4 5 6 7 \tracingcommands=1 \hbox{ \vbox{ \noindent$$x\showlists$$}$}\bye The first line of modes.tex tells TEX to log every command it receives; TEX will produce diagnostic data whenever \tracingcommands is positive. Indeed, if you run TEX on modes.tex you will get a modes.log file that includes the following information: {vertical mode: \hbox} {restricted horizontal mode: blank space} {math shift character$} {math mode: blank space} {\vbox} {internal vertical mode: blank space} {\noindent} {horizontal mode: math shift character $} {display math mode: blank space} {the letter x} The meaning is that TEX first saw an \hbox token in vertical mode; this caused it to go ahead and read the ‘{’ behind the scenes. Then TEX entered restricted horizontal mode, and saw the blank space token that resulted from the end of line 2 in the file. Then it saw a math shift character token (still in restricted horizontal mode), which caused a shift to math mode; another blank space came through. Then \vbox inaugurated internal vertical mode, and \noindent instituted horizontal mode within that; two subsequent$ signs led to display math mode. (Only the first $was shown by \tracingcommands, because that one caused TEX to look ahead for another.) Ä The next thing in modes.log after the output above is ‘{\showlists}’. This is another handy diagnostic command that you can use to find out things that TEX ordinarily keeps to itself; it causes TEX to display the lists that are being worked on, in the current mode and in all enclosing modes where the work has been suspended: ### display math mode entered at line 5 \mathord .\fam1 x ### internal vertical mode entered at line 4 prevdepth ignored ### math mode entered at line 3 ### restricted horizontal mode entered at line 2 \glue 3.33333 plus 1.66666 minus 1.11111 spacefactor 1000 ### vertical mode entered at line 0 prevdepth ignored Chapter 13: Modes In this case the lists represent five levels of activity, all present at the end of line 6 of modes.tex. The current mode is shown first, namely, display math mode, which began on line 5. The current math list contains one “mathord” object, consisting of the letter x in family 1. (Have patience and you will understand what that means, when you learn about TEX’s math formulas.) Outside of display math mode comes internal vertical mode, to which TEX will return when the paragraph containing the displayed formula is complete. The vertical list on that level is empty; ‘prevdepth ignored’ means that \prevdepth has a value ≤ −1000 pt, so that the next interline glue will be omitted (cf. Chapter 12). The math mode outside of this internal vertical mode has an empty list, likewise, but the restricted horizontal mode enclosing the math mode contains some glue. Finally, we see the main vertical mode that encloses everything; this mode was ‘entered at line 0’, i.e., before the file modes.tex was input; nothing has been contributed so far to the vertical list on this outermost level. Ä x EXERCISE 13.2 Ä x EXERCISE 13.3 Why is there glue in one of these lists but not in the others? After this output of \showlists, the modes.log file contains further output from \tracingcommands. In fact, the next two lines of that file are {math shift character$} {horizontal mode: end-group character }} because the ‘$$’ on line 7 finishes the displayed formula, and this resumes horizontal mode for the paragraph that was interrupted. What do you think are the next three lines of modes.log ? Ä x EXERCISE 13.4 Suppose TEX has generated a document without ever leaving vertical mode. What can you say about that document? Ä Äx EXERCISE 13.5 Some of TEX’s modes cannot immediately enclose other modes; for example, display math mode is never directly enclosed by horizontal mode, even though displays occur within paragraphs, because an interrupted paragraph-so-far of horizontal mode is always completed and removed from TEX’s memory before the processing of a displayed formula begins. Give a complete characterization of all pairs of consecutive modes that can occur in the output of \showlists. Every mode of life has its conveniences. — SAMUEL JOHNSON, The Idler (1758) [Hindu musicians] have eighty-four modes, of which thirty-six are in general use, and each of which, it appears, has a peculiar expression, and the power of moving some particular sentiment or affection. — MOUNTSTUART ELPHINSTONE, History of India (1841) 89 (page 90) 14 How TEX Breaks Paragraphs into Lines Chapter 14: How TEX Breaks Paragraphs into Lines One of a typesetting system’s chief duties is to take a long sequence of words and to break it up into individual lines of the appropriate size. For example, every paragraph of this manual has been broken into lines that are 29 picas wide, but the author didn’t have to worry about such details when he composed the manuscript. TEX chooses breakpoints in an interesting way that considers each paragraph in its entirety; the closing words of a paragraph can actually influence the appearance of the first line. As a result, the spacing between words is as uniform as possible, and the computer is able to reduce the number of times that words must be hyphenated or formulas must be split between lines. The experiments of Chapter 6 have already illustrated the general ideas: We discussed the notion of “badness,” and we ran into “overfull” and “underfull” boxes in difficult situations. We also observed that different settings of TEX’s \tolerance parameter will produce different effects; a higher tolerance means that wider spaces are acceptable. TEX will find the absolutely best way to typeset any given paragraph, according to its ideas of minimum badness. But such “badness” doesn’t account for everything, and if you rely entirely on an automatic scheme you will occasionally encounter line breaks that are not really the best on psychological grounds; this is inevitable, because computers don’t understand things the way people do (at least not yet). Therefore you’ll sometimes want to tell the machine that certain places are not good breakpoints. Conversely, you will sometimes want to force a break at a particular spot. TEX provides a convenient way to avoid psychologically bad breaks, so that you will be able to obtain results of the finest quality by simply giving a few hints to the machine. “Ties”—denoted by ‘~’ in plain TEX—are the key to successful line breaking. Once you learn how to insert them, you will have graduated from the ranks of ordinary TEXnical typists to the select group of Distinguished TEXnicians. And it’s really not difficult to train yourself to insert occasional ties, almost without thinking, as you type a manuscript. When you type ~ it’s the same as typing a space, except that TEX won’t break a line at this space. Furthermore, you shouldn’t leave any blanks next to the ~, since they will count as additional spaces. If you put ~ at the very end of a line in your input file, you’ll get a wider space than you want, because the hreturni that follows the ~ produces an extra space. We have already observed in Chapter 12 that it’s generally a good idea to type ~ after an abbreviation that does not come at the end of a sentence. Ties also belong in several other places: In references to named parts of a document: Chapter~12 Appendix~A Figure~3 Theorem~1.2 Table~\hbox{B-8} Lemmas 5 and~6 (No ~ appears after ‘Lemmas’ in the final example, since there’s no harm in having ‘5 and 6’ at the beginning of a line. The use of \hbox is explained below.) 91 92 Chapter 14: How TEX Breaks Paragraphs into Lines Between a person’s forenames and between multiple surnames: Donald~E. Knuth Bartel~Leendert van~der~Waerden Luis~I. Trabb~Pardo Charles~XII Note that it is sometimes better to hyphenate a name than to break it between words; e.g., ‘Don-’ and ‘ald E. Knuth’ is more tolerable than ‘Donald’ and ‘E. Knuth’. The previous rule can be regarded as a special case of this one, since we may think of ‘Chapter 12’ as a compound name; another example is ‘register~X’. Sometimes a name is so long that we dare not tie it all together, lest there be no way to break the line: Charles Louis Xavier~Joseph de~la Vall\’ee~Poussin. Between math symbols in apposition with nouns: dimension~d width~w string~s of length~l function~f(x) However, the last example should be compared with string~s of length l~or more. Between symbols in series: 1,~2, or~3 a,~b, and~c. 1,~2, \dots,~n. When a symbol is a tightly bound object of a preposition: of~x from 0 to~1 increase z by~1 in common with~m. The rule does not, however, apply to compound objects: of u~and~v. When mathematical phrases are rendered in words: equals~n mod~2 less than~\epsilon modulo~p^e (given~X) for all large~n Compare ‘is~15’ with ‘is 15~times the height’. When cases are being enumerated within a paragraph: (b)~Show that f(x) is (1)~continuous; (2)~bounded. It would be nice to boil all of these rules down to one or two simple principles, and it would be even nicer if the rules could be automated so that keyboarding Chapter 14: How TEX Breaks Paragraphs into Lines could be done without them; but subtle semantic considerations seem to be involved. Therefore it’s best to use your own judgment with respect to ties. The computer needs your help. A tie keeps TEX from breaking at a space, but sometimes you want to prevent the machine from breaking at a hyphen or a dash. This can be done by using \hbox, because TEX will not split up the contents of a box; boxes are indecomposable units, once they have been constructed. We have already illustrated this principle in the ‘Table~\hbox{B-8}’ example considered earlier. Another example occurs when you are typing the page numbers in a bibliographic reference: It doesn’t look good to put ‘22.’ on a line by itself, so you can type ‘\hbox{13--22}.’ to prohibit breaking ‘13–22.’ On the other hand, TEX doesn’t often choose line breaks at hyphens, so you needn’t bother to insert \hbox commands unless you need to correct a bad break that TEX has already made on a previous run. x EXERCISE 14.1 Here are some phrases culled from previous chapters of this manual. How do you think the author typed them? (cf. Chapter 12). Chapters 12 and 21. line 16 of Chapter 6’s story lines 7 to 11 lines 2, 3, 4, and 5. (2) a big black bar All 256 characters are initially of category 12, letter x in family 1. the factor f , where n is 1000 times f . x EXERCISE 14.2 How would you type the phrase ‘for all n greater than n0 ’ ? x EXERCISE 14.3 And how would you type ‘exercise 4.3.2–15’ ? x EXERCISE 14.4 Why is it better to type ‘Chapter~12’ than to type ‘\hbox{Chapter 12}’ ? Ä x EXERCISE 14.5 TEX will sometimes break a math formula after an equals sign. How can you stop the computer from breaking the formula ‘x = 0’ ? Ä Äx EXERCISE 14.6 Explain how you could instruct TEX not to make any breaks after explicit hyphens and dashes. (This is useful in lengthy bibliographies.) Sometimes you want to permit a line break after a ‘/’ just as if it were a hyphen. For this purpose plain TEX allows you to say ‘\slash’; for example, ‘input\slash output’ produces ‘input/output’ with an optional break. 93 94 Chapter 14: How TEX Breaks Paragraphs into Lines If you want to force TEX to break between lines at a certain point in the middle of a paragraph, just say ‘\break’. However, that might cause the line to be really spaced out. If you want TEX to fill up the right-hand part of a line with blank space just before a forced line break, without indenting the next line, say ‘\hfil\break’. Ä You may have several consecutive lines of input for which you want the output to appear line-for-line in the same way. One solution is to type ‘\par’ at the end of each input line; but that’s somewhat of a nuisance, so plain TEX provides the abbreviation ‘\obeylines’, which causes each end-of-line in the input to be like \par. After you say \obeylines you will get one line of output per line of input, unless an input line ends with ‘%’ or unless it is so long that it must be broken. For example, you probably want to use \obeylines if you are typesetting a poem. Be sure to enclose \obeylines in a group, unless you want this “poetry mode” to continue to the end of your document. {\obeylines\smallskip Roses are red, \quad Violets are blue; Rhymes can be typeset \quad With boxes and glue. \smallskip} Ä x EXERCISE 14.7 Explain the uses of \quad in this poem. What would have happened if ‘\quad’ had been replaced by ‘\indent’ in both places? Roughly speaking, TEX breaks paragraphs into lines in the following way: Breakpoints are inserted between words or after hyphens so as to produce lines whose badnesses do not exceed the current \tolerance. If there’s no way to insert such breakpoints, an overfull box is set. Otherwise the breakpoints are chosen so that the paragraph is mathematically optimal, i.e., best possible, in the sense that it has no more “demerits” than you could obtain by any other sequence of breakpoints. Demerits are based on the badnesses of individual lines and on the existence of such things as consecutive lines that end with hyphens, or tight lines that occur next to loose ones. Ä But the informal description of line breaking in the previous paragraph is an oversimplification of what really happens. The remainder of this chapter explains the details precisely, for people who want to apply TEX in nonstandard ways. TEX’s line-breaking algorithm has proved to be general enough to handle a surprising variety of different applications; this, in fact, is probably the most interesting aspect of the whole TEX system. However, every paragraph from now on until the end of the chapter is prefaced by at least one dangerous bend sign, so you may want to learn the following material in easy stages instead of all at once. Ä Before the lines have been broken, a paragraph inside of TEX is actually a horizontal list, i.e., a sequence of items that TEX has gathered while in horizontal mode. We have been saying informally that a horizontal list consists of boxes Chapter 14: How TEX Breaks Paragraphs into Lines and glue; the truth is that boxes and glue aren’t the whole story. Each item in a horizontal list is one of the following types of things: a box (a character or ligature or rule or hbox or vbox); a discretionary break (to be explained momentarily); a “whatsit” (something special to be explained later); vertical material (from \mark or \vadjust or \insert); a glob of glue (or \leaders, as we will see later); a kern (something like glue that doesn’t stretch or shrink); a penalty (representing the undesirability of breaking here); “math-on” (beginning a formula) or “math-off” (ending a formula). The last four types (glue, kern, penalty, and math items) are called discardable, since they may change or disappear at a line break; the first four types are called nondiscardable, since they always remain intact. Many of the things that can appear in horizontal lists have not been touched on yet in this manual, but it isn’t necessary to understand them in order to understand line breaking. Sooner or later you’ll learn how each of the gismos listed above can infiltrate a horizontal list; and if you want to get a thorough understanding of TEX’s internal processes, you can always use \showlists with various features of the language, in order to see exactly what TEX is doing. Ä A discretionary break consists of three sequences of characters called the prebreak, post-break, and no-break texts. The idea is that if a line break occurs here, the pre-break text will appear at the end of the current line and the post-break text will occur at the beginning of the next line; but if no break occurs, the no-break text will appear in the current line. Users can specify discretionary breaks in complete generality by writing \discretionary{hpre-break texti}{hpost-break texti}{hno-break texti} where the three texts consist entirely of characters, boxes, and kerns. For example, TEX can hyphenate the word ‘difficult’ between the f’s, even though this requires breaking the ‘ffi’ ligature into ‘f-’ followed by an ‘fi’ ligature, if the horizontal list contains di\discretionary{f-}{fi}{ffi}cult. Fortunately you need not type such a mess yourself; TEX’s hyphenation algorithm works behind the scenes, taking ligatures apart and putting them into discretionary breaks when necessary. Ä The most common case of a discretionary break is a simple discretionary hyphen \discretionary{-}{}{} for which TEX accepts the abbreviation ‘\-’. The next most common case is \discretionary{}{}{} (an “empty discretionary”), which TEX automatically inserts after ‘-’ and after every ligature that ends with ‘-’. In the case of plain TEX, empty discretionaries are therefore inserted after hyphens and dashes. (Each font has an associated \hyphenchar, which we can assume for simplicity is equal to ‘-’.) 95 96 Chapter 14: How TEX Breaks Paragraphs into Lines Ä When TEX hyphenates words, it simply inserts discretionary breaks into the horizontal list. For example, the words ‘discretionary hyphens’ are transformed into the equivalent of dis\-cre\-tionary hy\-phens if hyphenation becomes necessary. But TEX doesn’t apply its hyphenation algorithm to any word that already contains a discretionary break; therefore you can use explicit discretionaries to override TEX’s automatic method, in an emergency. Ä x EXERCISE 14.8 Some compound words in German text change their spelling when they are split between lines. For example, ‘backen’ becomes ‘bak-ken’ and ‘Bettuch’ becomes ‘Bett-tuch’. How can you instruct TEX to produce this effect? Ä In order to save time, TEX tries first to break a paragraph into lines without inserting any discretionary hyphens. This first pass will succeed if a sequence of breakpoints is found for which none of the resulting lines has a badness exceeding the current value of \pretolerance. If the first pass fails, the method of Appendix H is used to hyphenate each word of the paragraph by inserting discretionary breaks into the horizontal list, and a second attempt is made using \tolerance instead of \pretolerance. When the lines are fairly wide, as they are in this manual, experiments show that the first pass succeeds more than 90% of the time, and that fewer than 2 words per paragraph need to be subjected to the hyphenation algorithm, on the average. But when the lines are very narrow the first pass usually fails rather quickly. Plain TEX sets \pretolerance=100 and \tolerance=200 as the default values. If you make \pretolerance=10000, the first pass will essentially always succeed, so hyphenations will not be tried (and the spacing may be terrible); on the other hand if you make \pretolerance=-1, TEX will omit the first pass and will try to hyphenate immediately. Ä Line breaks can occur only in certain places within a horizontal list. Roughly speaking, they occur between words and after hyphens, but in actuality they are permitted in the following five cases: a) at glue, provided that this glue is immediately preceded by a non-discardable item, and that it is not part of a math formula (i.e., not between math-on and math-off). A break “at glue” occurs at the left edge of the glue space. b) at a kern, provided that this kern is immediately followed by glue, and that it is not part of a math formula. c) at a math-off that is immediately followed by glue. d) at a penalty (which might have been inserted automatically in a formula). e) at a discretionary break. Notice that if two globs of glue occur next to each other, the second one will never be selected as a breakpoint, since it is preceded by glue (which is discardable). Ä Each potential breakpoint has an associated “penalty,” which represents the “aesthetic cost” of breaking at that place. In cases (a), (b), (c), the penalty is zero; in case (d) an explicit penalty has been specified; and in case (e) the penalty is the current value of \hyphenpenalty if the pre-break text is nonempty, or the current value of \exhyphenpenalty if the pre-break text is empty. Plain TEX sets \hyphenpenalty=50 and \exhyphenpenalty=50. Chapter 14: How TEX Breaks Paragraphs into Lines Ä For example, if you say ‘\penalty 100’ at some point in a paragraph, that position will be a legitimate place to break between lines, but a penalty of 100 will be charged. If you say ‘\penalty-100’ you are telling TEX that this is a rather good place to break, because a negative penalty is really a “bonus”; a line that ends with a bonus might even have “merits” (negative demerits). Ä Any penalty that is 10000 or more is considered to be so large that TEX will never break there. At the other extreme, any penalty that is −10000 or less is considered to be so small that TEX will always break there. The \nobreak macro of plain TEX is simply an abbreviation for ‘\penalty10000’, because this prohibits a line break. A tie in plain TEX is equivalent to ‘\nobreak\Ã’; there will be no break at the glue represented by \Ã in this case, because glue is never a legal breakpoint when it is preceded by a discardable item like a penalty. Ä x EXERCISE 14.9 Ä x EXERCISE 14.10 Guess how the \break macro is defined in plain TEX. What happens if you say \nobreak\break or \break\nobreak? Ä When a line break actually does occur, TEX removes all discardable items that follow the break, until coming to something non-discardable, or until coming to another chosen breakpoint. For example, a sequence of glue and penalty items will vanish as a unit, if no boxes intervene, unless the optimum breakpoint sequence includes one or more of the penalties. Math-on and math-off items act essentially as kerns that contribute the spacing specified by \mathsurround; such spacing will disappear into the line break if a formula comes at the very end or the very beginning of a line, because of the way the rules have been formulated above. Ä Ä The badness of a line is an integer that is approximately 100 times the cube of the ratio by which the glue inside the line must stretch or shrink to make an hbox of the required size. For example, if the line has a total shrinkability of 10 points, and if the glue is being compressed by a total of 9 points, the badness is computed to be 73 (since 100 × (9/10)3 = 72.9); similarly, a line that stretches by twice its total stretchability has a badness of 800. But if the badness obtained by this method turns out to be more than 10000, the value 10000 is used. (See the discussion of “glue set ratio” r and “glue set order” i in Chapter 12; if i 6= 0, there is infinite stretchability or shrinkability, so the badness is zero, otherwise the badness is approximately min(100r 3 , 10000).) Overfull boxes are considered to be infinitely bad; they are avoided whenever possible. Ä Ä A line whose badness is 13 or more has a glue set ratio exceeding 50%. We call such a line tight if its glue had to shrink, loose if its glue had to stretch, and very loose if it had to stretch so much that the badness is 100 or more. But if the badness is 12 or less we say that the line is decent. Two adjacent lines are said to be visually incompatible if their classifications are not adjacent, i.e., if a tight line is next to a loose or very loose line, or if a decent line is next to a very loose one. Ä Ä TEX rates each potential sequence of breakpoints by totalling up demerits that are assessed to individual lines. The goal is to choose breakpoints that yield the fewest total demerits. Suppose that a line has badness b, and suppose that the 97 98 Chapter 14: How TEX Breaks Paragraphs into Lines penalty p is associated with the breakpoint at the end of this line. As stated above, TEX will not even consider such a line if p ≥ 10000, or if b exceeds the current tolerance or pretolerance. Otherwise the demerits of such a line are defined by the formula d= ( (l + b)2 + p2 , (l + b)2 − p2 , (l + b)2 , if 0 ≤ p < 10000; if −10000 < p < 0; if p ≤ −10000. Here l is the current value of \linepenalty, a parameter that can be increased if you want TEX to try harder to keep all paragraphs to the minimum number of lines; plain TEX sets \linepenalty=10. For example, a line with badness 20 ending at glue will have (10 + 20)2 = 900 demerits, if l = 10, since there’s no penalty for a break at glue. Minimizing the total demerits of a paragraph is roughly the same as minimizing the sum of the squares of the badnesses and penalties; this usually means that the maximum badness of any individual line is also minimized, over all sequences of breakpoints. Ä Äx EXERCISE 14.11 The formula for demerits has a strange discontinuity: It seems more reasonable at first to define d = (l + b)2 − 100002 , in the case p ≤ −10000. Can you account for this apparent discrepancy? Ä Ä Additional demerits are assessed based on pairs of adjacent lines. If two con- secutive lines are visually incompatible, in the sense explained a minute ago, the current value of \adjdemerits is added to d. If two consecutive lines end with discretionary breaks, the \doublehyphendemerits are added. And if the second-last line of the entire paragraph ends with a discretionary, the \finalhyphendemerits are added. Plain TEX sets up the values \adjdemerits=10000, \doublehyphendemerits=10000, and \finalhyphendemerits=5000. Demerits are in units of “badness squared,” so the demerit-oriented parameters need to be rather large if they are to have much effect; but tolerances and penalties are given in the same units as badness. Ä Ä If you set \tracingparagraphs=1, your log file will contain a summary of TEX’s line-breaking calculations, so you can watch the tradeoffs that occur when parameters like \linepenalty and \hyphenpenalty and \adjdemerits are twiddled. The line-break data looks pretty scary at first, but you can learn to read it with a little practice; this, in fact, is the best way to get a solid understanding of line breaking. Here is the trace that results from the second paragraph of the story file in Chapter 6, when \hsize=2.5in and \tolerance=1000: []\tenrm Mr. Drofnats---or ‘‘R. J.,’’ as he [email protected]\discretionary via @@0 b=0 p=50 d=2600 @@1: line 1.2- t=2600 -> @@0 ferred to be called---was hap-pi-est when @ via @@1 b=131 p=0 d=29881 @@2: line 2.0 t=32481 -> @@1 he @ via @@1 b=25 p=0 d=1225 @@3: line 2.3 t=3825 -> @@1 was at work type-set-ting beau-ti-ful [email protected]\discretionary via @@2 b=1 p=50 d=12621 @\discretionary via @@3 b=291 p=50 d=103101 Chapter 14: How TEX Breaks Paragraphs into Lines @@4: line 3.2- t=45102 -> @@2 [email protected]\discretionary via @@3 b=44 p=50 d=15416 @@5: line 3.1- t=19241 -> @@3 ments. @\par via @@4 b=0 p=-10000 d=5100 @\par via @@5 b=0 p=-10000 d=5100 @@6: line 4.2- t=24341 -> @@5 Lines that begin with ‘@@’ represent feasible breakpoints, i.e., breakpoints that can be reached without any badness exceeding the tolerance. Feasible breakpoints are numbered consecutively, starting with @@1; the beginning of the paragraph is considered to be feasible too, and it is number @@0. Lines that begin with ‘@’ but not ‘@@’ are candidate ways to reach the feasible breakpoint that follows; TEX will select only the best candidate, when there is a choice. Lines that do not begin with ‘@’ indicate how far TEX has gotten in the paragraph. Thus, for example, we find ‘@@2: line 2.0 t=32481 -> @@1’ after ‘...hap-pi-est when’ and before ‘he’, so we know that feasible breakpoint @@2 occurs at the space between the words when and he. The notation ‘line 2.0’ means that this feasible break comes at the end of line 2, and that this line will be very loose. (The suffixes .0, .1, .2, .3 stand respectively for very loose, loose, decent, and tight.) A hyphen is suffixed to the line number if that line ends with a discretionary break, or if it is the final line of the paragraph; for example, ‘line 1.2-’ is a decent line that was hyphenated. The notation ‘t=32481’ means that the total demerits from the beginning of the paragraph to @@2 are 32481, and ‘-> @@1’ means that the best way to get to @@2 is to come from @@1. On the preceding line of trace data we see the calculations for a typeset line to this point from @@1: the badness is 131, the penalty is 0, hence there are 29881 demerits. Similarly, breakpoint @@3 presents an alternative for the second line of the paragraph, obtained by breaking between ‘he’ and ‘was’; this one makes the second line tight, and it has only 3825 demerits when the demerits of line 1 are added, so it appears that @@3 will work much better than @@2. However, the next feasible breakpoint (@@4) occurs after ‘doc-’, and the line from @@2 to @@4 has only 12621 demerits, while the line from @@3 to @@4 has a whopping 103101; therefore the best way to get from @@0 to @@4 is via @@2. If we regard demerits as distances, TEX is finding the “shortest paths” from @@0 to each feasible breakpoint (using a variant of a well-known algorithm for shortest paths in an acyclic graph). Finally the end of the paragraph comes at breakpoint @@6, and the shortest path from @@0 to @@6 represents the best sequence of breakpoints. Following the arrows back from @@6, we deduce that the best breaks in this particular paragraph go through @@5, @@3, and @@1. Ä Äx EXERCISE 14.12 Explain why there are 29881 demerits from @@1 to @@2, and 12621 demerits from @@2 to @@4. Ä Ä If ‘b=*’ appears in such trace data, it means that an infeasible breakpoint had to be chosen because there was no feasible way to keep total demerits small. Ä We still haven’t discussed the special trick that allows the final line of a paragraph to be shorter than the others. Just before TEX begins to choose breakpoints, it does two important things: (1) If the final item of the current horizontal 99 100 Chapter 14: How TEX Breaks Paragraphs into Lines list is glue, that glue is discarded. (The reason is that a blank space often gets into a token list just before \par or just before$$, and this blank space should not be part of the paragraph.) (2) Three more items are put at the end of the current horizontal list: \penalty10000 (which prohibits a line break); \hskip\parfillskip (which adds “finishing glue” to the paragraph); and \penalty-10000 (which forces the final break). Plain TEX sets \parfillskip=0pt plus1fil, so that the last line of each paragraph will be filled with white space if necessary; but other settings of \parfillskip are appropriate in special applications. For example, the present paragraph ends flush with the right margin, because it was typeset with \parfillskip=0pt; the author didn’t have to rewrite any of the text in order to make this possible, since a long paragraph generally allows so much flexibility that a line break can be forced at almost any point. You can have some fun playing with paragraphs, because the algorithm for line breaking occasionally appears to be clairvoyant. Just write paragraphs that are long enough.

Ä

x EXERCISE 14.13

Ä

x EXERCISE 14.14

Ben User decided to say ‘\hfilneg\par’ at the end of a paragraph, intending that the negative stretchability of \hfilneg would cancel with the \parfillskip of plain TEX. Why didn’t his bright idea work? How can you set \parfillskip so that the last line of a paragraph has exactly as much white space at the right as the first line has indentation at the left?

Ä Äx EXERCISE 14.15

Since TEX reads an entire paragraph before it makes any decisions about line breaks, the computer’s memory capacity might be exceeded if you are typesetting the works of some philosopher or modernistic novelist who writes 200-line paragraphs. Suggest a way to cope with such authors.

Ä

TEX has two parameters called \leftskip and \rightskip that specify glue to be inserted at the left and right of every line in a paragraph; this glue is taken into account when badnesses and demerits are computed. Plain TEX normally keeps \leftskip and \rightskip zero, but it has a ‘\narrower’ macro that increases both of their values by the current \parindent. You may want to use \narrower when quoting lengthy passages from a book. {\narrower\smallskip\noindent This paragraph will have narrower lines than the surrounding paragraphs do, because it uses the ‘‘narrower’’ feature of plain \TeX. The former margins will be restored after this group ends.\smallskip} (Try it.) The second ‘\smallskip’ in this example ends the paragraph. It’s important to end the paragraph before ending the group, for otherwise the effect of \narrower will disappear before TEX begins to choose line breaks.

Ä

x EXERCISE 14.16

When an entire paragraph is typeset in italic or slanted type, it sometimes appears to be offset on the page with respect to other paragraphs. Explain how you could use \leftskip and \rightskip to shift all lines of a paragraph left by 1 pt.

Chapter 14: How TEX Breaks Paragraphs into Lines Ä

101

x EXERCISE 14.17

The \centerline, \leftline, \rightline, and \line macros of plain TEX don’t take \leftskip and \rightskip into account. How could you make them do so?

Ä Ä If you suspect that \raggedright setting is accomplished by some appropriate

manipulation of \rightskip, you are correct. But some care is necessary. For example, a person can set \rightskip=0pt plus1fil, and every line will be filled with space at the right. But this isn’t a particularly good way to make ragged-right margins, because the infinite stretchability will assign zero badness to lines that are very short. To do a decent job of ragged-right setting, the trick is to set \rightskip so that it will stretch enough to make line breaks possible, yet not too much, because short lines should be considered bad. Furthermore the spaces between words should be fixed so that they do not stretch or shrink. (See the definition of \raggedright in Appendix B.) It would also be possible to allow a little variability in the interword glue, so that the right margin would not be quite so ragged but the paragraphs would still have an informal appearance.

Ä

TEX looks at the parameters that affect line breaking only when it is breaking lines. For example, you shouldn’t try to change the \hyphenpenalty in the middle of a paragraph, if you want TEX to penalize the hyphens in one word more than it does in another word. The relevant values of \hyphenpenalty, \rightskip, \hsize, and so on, are the ones that are current at the end of the paragraph. On the other hand, the width of indentation that you get implicitly at the beginning of a paragraph or when you say ‘\indent’ is determined by the value of \parindent at the time the indentation is contributed to the current horizontal list, not by its value at the end of the paragraph. Similarly, penalties that are inserted into math formulas within a paragraph are based on the values of \binoppenalty and \relpenalty that are current at the end of each particular formula. Appendix D contains an example that shows how to have both ragged-right and ragged-left margins within a single paragraph, without using \leftskip or \rightskip.

Ä

It’s possible to control the length of lines in a much more general way, if simple changes to \leftskip and \rightskip aren’t flexible enough for your purposes. For example, a semicircular hole has been cut out of the present paragraph, in order to make room for a circular illustration that conThe area of a circle is a mean tains some of Galileo’s immortal words about circles; all of the line proportional between any two regular and similar polybreaks in this paragraph and in the circular quotation were found gons of which one circumscribes it and the other is isoperimetric by TEX’s line-breaking algorithm. You can specify an essentially with it. In addition, the area of the circle is less than that of any circumarbitrary paragraph shape by saying \parshape=hnumberi, where scribed polygon and greater than that the hnumberi is a positive integer n, followed by 2n hdimeni specof any isoperimetric polygon. And further, of these circumscribed polygons, ifications. In general, ‘\parshape=n i1 l1 i2 l2 . . . in ln ’ specifies the one that has the greater number of sides has a smaller area than a paragraph whose first n lines will have lengths l1 , l2 , . . . , ln , the one that has a lesser number; but, on the other hand, the isorespectively, and they will be indented from the left margin by the perimetric polygon that has the greater number of respective amounts i1 , i2 , . . . , in . If the paragraph has fewer than sides is the larger. [Galileo, 1638] n lines, the additional specifications will be ignored; if it has more than n lines, the specifications for line n will be repeated ad infinitum. You can cancel the effect of a previously specified \parshape by saying ‘\parshape=0’.

Ä Äx EXERCISE 14.18

Typeset the following Pascalian quotation in the shape of an isosceles triangle:

102

Chapter 14: How TEX Breaks Paragraphs into Lines “I turn, in the following treatises, to various uses of those triangles whose generator is unity. But I leave out many more than I include; it is extraordinary how fertile in properties this triangle is. Everyone can try his hand.”

Ä

You probably won’t need unusual parshapes very often. But there’s a special case that occurs rather frequently, so TEX provides a special abbreviation for it in terms of two parameters called \hangindent and \hangafter. The command ‘\hangindent=hdimeni’ specifies a so-called hanging indentation, and the command ‘\hangafter=hnumberi’ specifies the duration of that indentation. Let x and n be the respective values of \hangindent and \hangafter, and let h be the value of \hsize; then if n ≥ 0, hanging indentation will occur on lines n + 1, n + 2, . . . of the paragraph, but if n < 0 it will occur on lines 1, 2, . . . , |n|. Hanging indentation means that lines will be of width h − |x| instead of their normal width h; if x ≥ 0, the lines will be indented at the left margin, otherwise they will be indented at the right margin. For example, the “dangerous bend” paragraphs of this manual have a hanging indentation of 3 picas that lasts for two lines; they were set with \hangindent=3pc and \hangafter=-2.

Ä

Plain TEX uses hanging indentation in its ‘\item’ macro, which produces a paragraph in which every line has the same indentation as a normal \indent. Furthermore, \item takes a parameter that is placed into the position of the indentation on the first line. Another macro called ‘\itemitem’ does the same thing but with double indentation. For example, suppose you type \item{1.} This is the first of several cases that are being enumerated, with hanging indentation applied to entire paragraphs. \itemitem{a)} This is the first subcase. \itemitem{b)} And this is the second subcase. Notice that subcases have twice as much hanging indentation. \item{2.} The second case is similar. Then you get the following output: 1. This is the first of several cases that are being enumerated, with hanging indentation applied to entire paragraphs. a) This is the first subcase. b) And this is the second subcase. Notice that subcases have twice as much hanging indentation. 2. The second case is similar. (Indentations in plain TEX are not actually as dramatic as those displayed here; Appendix B says ‘\parindent=20pt’, but this manual has been set with \parindent=36pt.) It is customary to put \medskip before and after a group of itemized paragraphs, and to say \noindent before any closing remarks that apply to all of the cases. Blank lines are not needed before \item or \itemitem, since those macros begin with \par.

Ä

x EXERCISE 14.19

Ä

x EXERCISE 14.20

Suppose one of the enumerated cases continues for two or more paragraphs. How can you use \item to get hanging indentation on the subsequent paragraphs? Explain how to make a “bulleted” item that says ‘•’ instead of ‘1.’.

Chapter 14: How TEX Breaks Paragraphs into Lines Ä Äx EXERCISE 14.21

The ‘\item’ macro doesn’t alter the right-hand margin. How could you indent at both sides?

Ä Äx EXERCISE 14.22

Explain how you could specify a hanging indentation of −2 ems (i.e., the lines should project into the left margin), after the first two lines of a paragraph.

Ä

If \parshape and hanging indentation have both been specified, \parshape takes precedence and \hangindent is ignored. You get the normal paragraph shape, in which every line width is \hsize, when \parshape=0, \hangindent=0pt, and \hangafter=1. TEX automatically restores these normal values at the end of every paragraph, and (by local definitions) whenever it enters internal vertical mode. For example, hanging indentation that might be present outside of a \vbox construction won’t occur inside that vbox, unless you ask for it inside.

Ä Äx EXERCISE 14.23

Suppose you want to leave room at the right margin for a rectangular illustration that takes up 15 lines, and you expect that three paragraphs will go by before you have typeset enough text to get past that illustration. Suggest a good way to do this without trial and error, given the fact that TEX resets hanging indentation.

Ä Ä If displayed equations occur in a paragraph that has a nonstandard shape, TEX

always assumes that the display takes up exactly three lines. For example, a paragraph that has four lines of text, then a display, then two more lines of text, is considered to be 4 + 3 + 2 = 9 lines long; the displayed equation will be indented and centered using the paragraph shape information appropriate to line 6.

Ä Ä TEX has an internal integer variable called \prevgraf that records the number

of lines in the most recent paragraph that has been completed or partially completed. You can use \prevgraf in the context of a hnumberi, and you can set \prevgraf to any desired nonnegative value if you want to make TEX think that it is in some particular part of the current paragraph shape. For example, let’s consider again a paragraph that contains four lines plus a display plus two more lines. When TEX starts the paragraph, it sets \prevgraf=0; when it starts the display, \prevgraf will be 4; when it finishes the display, \prevgraf will be 7; and when it ends the paragraph, \prevgraf will be 9. If the display is actually one line taller than usual, you could set \prevgraf=8 at the beginning of the two final lines; then TEX will think that a 10-line paragraph is being made. The value of \prevgraf affects line breaking only when TEX is dealing with nonstandard \parshape or \hangindent.

Ä Äx EXERCISE 14.24

Solve exercise 14.23 using \prevgraf.

Ä Ä You are probably convinced by now that TEX’s line-breaking algorithm has

plenty of bells and whistles, perhaps even too many. But there’s one more feature, called “looseness”; some day you might find yourself needing it, when you are fine-tuning the pages of a book. If you set \looseness=1, TEX will try to make the current paragraph one line longer than its optimum length, provided that there is a way to choose such breakpoints without exceeding the tolerance you have specified for the badnesses of individual lines. Similarly, if you set \looseness=2, TEX will try to

103

104

Chapter 14: How TEX Breaks Paragraphs into Lines make the paragraph two lines longer; and \looseness=-1 causes an attempt to make it shorter. The general idea is that TEX first finds breakpoints as usual; then if the optimum breakpoints produce n lines, and if the current \looseness is l, TEX will choose the final breakpoints so as to make the final number of lines as close as possible to n+l without exceeding the current tolerance. Furthermore, the final breakpoints will have fewest total demerits, considering all ways to achieve the same number of lines.

Ä Ä For example, you can set \looseness=1 if you want to avoid a lonely “club

line” or “widow line” on some page that does not have sufficiently flexible glue, or if you want the total number of lines in some two-column document to come out to be an even number. It’s usually best to choose a paragraph that is already pretty “full,” i.e., one whose last line doesn’t have much white space, since such paragraphs can generally be loosened without much harm. You might also want to insert a tie between the last two words of that paragraph, so that the loosened version will not end with only one “widow word” on the line; this tie will cover your tracks, so that people will find it hard to detect the fact that you have tampered with the spacing. On the other hand, TEX can take almost any sufficiently long paragraph and stretch it a bit, without substantial harm; the present paragraph is, in fact, one line looser than its optimum length.

Ä Ä TEX resets the looseness to zero at the same time as it resets \hangindent, \hangafter, and \parshape.

Ä Äx EXERCISE 14.25

Explain what TEX will do if you set \looseness=-1000.

Ä

Just before switching to horizontal mode to begin scanning a paragraph, TEX inserts the glue specified by \parskip into the vertical list that will contain the paragraph, unless that vertical list is empty so far. For example, ‘\parskip=3pt’ will cause 3 points of extra space to be placed between paragraphs. Plain TEX sets \parskip=0pt plus1pt; this gives a little stretchability, but no extra space.

Ä

After line breaking is complete, TEX appends the lines to the current vertical list that encloses the current paragraph, inserting interline glue as explained in Chapter 12; this interline glue will depend on the values of \baselineskip, \lineskip, and \lineskiplimit that are currently in force. TEX will also insert penalties into the vertical list, just before each glob of interline glue, in order to help control page breaks that might have to be made later. For example, a special penalty will be assessed for breaking a page between the first two lines of a paragraph, or just before the last line, so that “club” or “widow” lines that are detached from the rest of a paragraph will not appear all alone on a page unless the alternative is worse.

Ä

Here’s how interline penalties are calculated: TEX has just chosen the breakpoints for some paragraph, or for some partial paragraph that precedes a displayed equation; and n lines have been formed. The penalty between lines j and j + 1, given a value of j in the range 1 ≤ j < n, is the value of \interlinepenalty plus additional charges made in special cases: The \clubpenalty is added if j = 1, i.e., just after the first line; then the \displaywidowpenalty or the \widowpenalty is added if j = n − 1, i.e., just before the last line, depending on whether or not the current lines immediately precede a display; and finally the \brokenpenalty is added, if the jth line ended at a discretionary break. (Plain TEX sets \clubpenalty=150,

Chapter 14: How TEX Breaks Paragraphs into Lines \widowpenalty=150, \displaywidowpenalty=50, and \brokenpenalty=100; the value of \interlinepenalty is normally zero, but it is increased to 100 within footnotes, so that long footnotes will tend not to be broken between pages.)

Ä

x EXERCISE 14.26

Ä

x EXERCISE 14.27

Consider a five-line paragraph in which the second and fourth lines end with hyphens. What penalties does plain TEX put between the lines? What penalty goes between the lines of a two-line paragraph?

Ä Ä If you say \vadjust{hvertical listi} within a paragraph, TEX will insert the

specified internal vertical list into the vertical list that encloses the paragraph, immediately after whatever line contained the position of the \vadjust. For example, you can say ‘\vadjust{\kern1pt}’ to increase the amount of space between lines of a paragraph if those lines would otherwise come out too close together. (The author did it in the previous line, just to illustrate what happens.) Also, if you want to make sure that a page break will occur immediately after a certain line, you can say ‘\vadjust{\eject}’ anywhere in that line.

Ä Ä Later chapters discuss \insert and \mark commands that are relevant to

TEX’s page builder. If such commands appear within a paragraph, they are removed from whatever horizontal lines contain them and placed into the enclosing vertical list, together with other vertical material from \vadjust commands that might be present. In the final vertical list, each horizontal line of text is an hbox that is immediately preceded by interline glue and immediately followed by vertical material that has “migrated out” from that line (with left to right order preserved, if there are several instances of vertical material); then comes the interline penalty, if it is nonzero. Inserted vertical material does not influence the interline glue.

Ä Äx EXERCISE 14.28

Design a \marginalstar macro that can be used anywhere in a paragraph. It should use \vadjust to place an asterisk in the margin just to the left of the line where \marginalstar occurs.

Ä Ä When TEX enters horizontal mode, it will interrupt its normal scanning to read

tokens that were predefined by the command \everypar={htoken listi}. For example, suppose you have said ‘\everypar={A}’. If you type ‘B’ in vertical mode, TEX will shift to horizontal mode (after contributing \parskip glue to the current page), and a horizontal list will be initiated by inserting an empty box of width \parindent. Then TEX will read ‘AB’, since it reads the \everypar tokens before getting back to the ‘B’ that triggered the new paragraph. Of course, this is not a very useful illustration of \everypar; but if you let your imagination run you will think of better applications.

Ä Äx EXERCISE 14.29

Use \everypar to define an \insertbullets macro: All paragraphs in a group of the form ‘{\insertbullets ...\par}’ should have a bullet symbol ‘•’ as part of their indentation.

Ä Ä A paragraph of zero lines is formed if you say ‘\noindent\par’. If \everypar

is null, such a paragraph contributes nothing except \parskip glue to the current vertical list.

105

106

Chapter 14: How TEX Breaks Paragraphs into Lines Ä Äx EXERCISE 14.30

Guess what happens if you say ‘\noindent$$...$$ \par’.

Ä Ä Experience has shown that TEX’s line-breaking algorithm can be harnessed

to a surprising variety of tasks. Here, for example, is an application that indicates one of the possibilities: Articles that are published in Mathematical Reviews are generally signed with the reviewer’s name and address, and this information is typeset flush right, i.e., at the right-hand margin. If there is sufficient space to put such a name and address at the right of the final line of the paragraph, the publishers can save space, and at the same time the results look better because there are no strange gaps on the page. This is a case where the name and address fit in nicely with the review. A. Reviewer (Ann Arbor, Mich.) But sometimes an extra line must be added. N. Bourbaki (Paris) Let’s suppose that a space of at least two ems should separate the reviewer’s name from the text of the review, if they occur on the same line. We would like to design a macro so that the examples shown above could be typed as follows in an input file: ... with the review. \signed A. Reviewer (Ann Arbor, Mich.) ... an extra line must be added. \signed N. Bourbaki (Paris) Here is one way to solve the problem: \def\signed #1 (#2){{\unskip\nobreak\hfil\penalty50 \hskip2em\hbox{}\nobreak\hfil\sl#1\/ \rm(#2) \parfillskip=0pt \finalhyphendemerits=0 \par}}

If a line break occurs at the \penalty50, the \hskip2em will disappear and the empty \hbox will occur at the beginning of a line, followed by \hfil glue. This yields two lines whose badness is zero; the first of these lines is assessed a penalty of 50. But if no line break occurs at the \penalty50, there will be glue of 2 em plus 2 fil between the review and the name; this yields one line of badness zero. TEX will try both alternatives, to see which leads to the fewest total demerits. The one-line solution will usually be preferred if it is feasible.

Ä Äx EXERCISE 14.31

Explain what would happen if ‘\hbox{}’ were left out of the \signed macro.

Ä Äx EXERCISE 14.32

Why does the \signed macro say ‘\finalhyphendemerits=0’ ?

Ä Äx EXERCISE 14.33

In one of the paragraphs earlier in this chapter, the author used \break to force a line break in a specific place; as a result, the third line of that particular paragraph was really spaced out. Explain why all the extra space went into the third line, instead of being distributed impartially among the first three lines.

Chapter 14: How TEX Breaks Paragraphs into Lines Ä Ä If you want to avoid overfull boxes at all costs without trying to fix them manu-

ally, you might be tempted to set tolerance=10000; this allows arbitrarily bad lines to be acceptable in tough situations. But infinite tolerance is a bad idea, because TEX doesn’t distinguish between terribly bad and preposterously horrible lines. Indeed, a tolerance of 10000 encourages TEX to concentrate all the badness in one place, making one truly unsightly line instead of two moderately bad ones, because a single “writeoff” produces fewest total demerits according to the rules. There’s a much better way to get the desired effect: TEX has a parameter called \emergencystretch that is added to the assumed stretchability of every line when badness and demerits are computed, in cases where overfull boxes are otherwise unavoidable. If \emergencystretch is positive, TEX will make a third pass over a paragraph before choosing the line breaks, when the first passes did not find a way to satisfy the \pretolerance and \tolerance. The effect of \emergencystretch is to scale down the badnesses so that large infinities are distinguishable from smaller ones. By setting \emergencystretch high enough (based on \hsize) you can be sure that the \tolerance is never exceeded; hence overfull boxes will never occur unless the line-breaking task is truly impossible.

Ä Äx EXERCISE 14.34

Devise a \raggedcenter macro (analogous to \raggedright) that partitions the words of a paragraph into as few as possible lines of approximately equal size and centers each individual line. Hyphenation should be avoided if possible.

When the author objects to [a hyphenation] he should be asked to add or cancel or substitute a word or words that will prevent the breakage. Authors who insist on even spacing always, with sightly divisions always, do not clearly understand the rigidity of types. — T. L. DE VINNE, Correct Composition (1901) In reprinting his own works, whenever [William Morris] found a line that justified awkwardly, he altered the wording solely for the sake of making it look well in print. When a proof has been sent me with two or three lines so widely spaced as to make a grey band across the page, I have often rewritten the passage so as to fill up the lines better; but I am sorry to say that my object has generally been so little understood that the compositor has spoilt all the rest of the paragraph instead of mending his former bad work. — GEORGE BERNARD SHAW, in The Dolphin (1940)

107

(page 108)

15 How TEX Makes Lines into Pages

Chapter 15: How TEX Makes Lines into Pages TEX attempts to choose desirable places to divide your document into individual pages, and its technique for doing this usually works pretty well. But the problem of page make-up is considerably more difficult than the problem of line breaking that we considered in the previous chapter, because pages often have much less flexibility than lines do. If the vertical glue on a page has little or no ability to stretch or to shrink, TEX usually has no choice about where to start a new page; conversely, if there is too much variability in the glue, the result will look bad because different pages will be too irregular. Therefore if you are fussy about the appearance of pages, you can expect to do some rewriting of the manuscript until you achieve an appropriate balance, or you might need to fiddle with the \looseness as described in Chapter 14; no automated system will be able to do this as well as you. Mathematical papers that contain a lot of displayed equations have an advantage in this regard, because the glue that surrounds a display tends to be quite flexible. TEX also gets valuable room to maneuver when you have occasion to use \smallskip or \medskip or \bigskip spacing between certain paragraphs. For example, consider a page that contains a dozen or so exercises, and suppose that there is 3 pt of additional space between exercises, where this space can stretch to 4 pt or shrink to 2 pt. Then there is a chance to squeeze an extra line on the page, or to open up the page by removing one line, in order to avoid splitting an exercise between pages. Similarly, it is possible to use flexible glue in special publications like membership rosters or company telephone directories, so that individual entries need not be split between columns or pages, yet every column appears to be the same height. For ordinary purposes you will probably find that TEX’s automatic method of page breaking is satisfactory. And when it occasionally gives unpleasant results, you can force the machine to break at your favorite place by typing ‘\eject’. But be careful: \eject will cause TEX to stretch the page out, if necessary, so that the top and bottom baselines agree with those on other pages. If you want to eject a short page, filling it with blank space at the bottom, type ‘\vfill\eject’ instead. Ä

If you say ‘\eject’ in the middle of a paragraph, the paragraph will end first, as if you typed ‘\par\eject’. But Chapter 14 mentions that you can say ‘\vadjust{\eject}’ in mid-paragraph, if you want to force a page break after whatever line contains your current position when the full paragraph is eventually broken up into lines; the rest of the paragraph will go on the following page.

Ä

To prevent a page break, you can say ‘\nobreak’ in vertical mode, just as \nobreak in horizontal mode prevents breaks between lines. For example, it is wise to say \nobreak between the title of a subsection and the first line of text in that subsection. But \nobreak does not cancel the effect of other commands like \eject that tell TEX to break; it only inhibits a break at glue that immediately follows. You should become familiar with TEX’s rules for line breaks and page breaks if you want to maintain fine control over everything. The remainder of this chapter is devoted to the intimate details of page breaking.

109

110

Chapter 15: How TEX Makes Lines into Pages Ä

TEX breaks lists of lines into pages by computing badness ratings and penalties, more or less as it does when breaking paragraphs into lines. But pages are made up one at a time and removed from TEX’s memory; there is no looking ahead to see how one page break will affect the next one. In other words, TEX uses a special method to find the optimum breakpoints for the lines in an entire paragraph, but it doesn’t attempt to find the optimum breakpoints for the pages in an entire document. The computer doesn’t have enough high-speed memory capacity to remember the contents of several pages, so TEX simply chooses each page break as best it can, by a process of “local” rather than “global” optimization.

Ä

Let’s look now at the details of TEX’s page-making process. Everything you contribute to the pages of your document is placed on the main vertical list, which is the sequence of items that TEX has accumulated while in vertical mode. Each item in a vertical list is one of the following types of things: a box (an hbox or vbox or rule); a “whatsit” (something special to be explained later); a mark (another thing that will be explained later); an insertion (yet another thing that we will get to); a glob of glue (or \leaders, as we will see later); a kern (something like glue that doesn’t stretch or shrink); a penalty (representing the undesirability of breaking here). The last three types (glue, kern, and penalty items) are called discardable, for the same reason that we called them discardable in horizontal lists. You might want to compare these specifications with the analogous rules for the horizontal case, found in Chapter 14; it turns out that vertical lists are just like horizontal ones except that character boxes, discretionary breaks, \vadjust items, and math shifts cannot appear in vertical lists. Chapter 12 exhibits a typical vertical list in TEX’s internal box-and-glue representation.

Ä

Page breaks can occur only at certain places within a vertical list. The permissible breakpoints are exactly the same as in the horizontal case, namely a) at glue, provided that this glue is immediately preceded by a non-discardable item (i.e., by a box, whatsit, mark, or insertion); b) at a kern, provided that this kern is immediately followed by glue; c) at a penalty (which might have been inserted automatically in a paragraph).

Interline glue is usually inserted automatically between the boxes of a vertical list, as explained in Chapter 12, so there is usually a valid breakpoint between boxes.

Ä

As in horizontal lists, each potential breakpoint has an associated penalty, which is high for undesirable breakpoints and negative for desirable ones. The penalty is zero at glue and kern breaks, so it is nonzero only at explicit penalty breaks. If you say ‘\penalty-100’ between two paragraphs, you are indicating that TEX should try to break here because the penalty is negative; a bonus of 100 points for breaking at this place will essentially cancel up to 100 units of badness that might be necessary to achieve such a break. A penalty of 10000 or more is so large that it inhibits breaking; a penalty of −10000 or less is so small that it forces breaking.

Chapter 15: How TEX Makes Lines into Pages Ä

Plain TEX provides several control sequences that help to control page breaks. For example, \smallbreak, \medbreak, and \bigbreak specify increasingly desirable places to break, having respective penalties of −50, −100, and −200; furthermore, they will insert a \smallskip, \medskip, or \bigskip of space, respectively, if a break is not taken. However, \smallbreak, \medbreak, and \bigbreak do not increase existing glue unnecessarily; for example, if you say \smallbreak just after a displayed equation, you won’t get a \smallskip of space in addition to the glue that already follows a display. Therefore these commands can conveniently be used before and after the statements of theorems, in a format for mathematical papers. In the present manual the author has used a macro that puts \medbreak before and after every dangerousbend paragraph; \medbreak\medbreak is equivalent to a single \medbreak, so you don’t see two medskips when one such paragraph ends and another one begins.

Ä

The \goodbreak macro is an abbreviation for ‘\par\penalty-500’. This is a good thing to insert in your manuscript when proofreading, if you are willing to stretch some page a little bit extra in order to improve the following one. Later on if you make another change so that this \goodbreak command does not appear near the bottom of a page, it will have no effect; thus it is not as drastic as \eject.

Ä

The most interesting macro that plain TEX provides for page make-up is called \filbreak. It means, roughly, “Break the page here and fill the bottom with blank space, unless there is room for more copy that is itself followed by \filbreak.” Thus if you put \filbreak at the end of every paragraph, and if your paragraphs aren’t too long, every page break will occur between paragraphs, and TEX will fit as many paragraphs as possible on each page. The precise meaning of \filbreak is \vfil\penalty-200\vfilneg according to Appendix B; and this simple combination of TEX’s primitives produces the desired result: If a break is taken at the \penalty-200, the preceding \vfil will fill the bottom of the page with blank space, and the \vfilneg will be discarded after the break; but if no break is taken at the penalty, the \vfil and \vfilneg will cancel each other and have no effect.

Ä

Plain TEX also provides a \raggedbottom command, which is a vertical analog of \raggedright: It tells TEX to permit a small amount of variability in the bottom margins on different pages, in order to make the other spacing uniform.

Ä Ä We saw in Chapter 14 that breakpoints for paragraphs are chosen by comput-

ing “demerits” for each line and summing them over all lines. The situation for pages is simpler because each page is considered separately. TEX figures the “cost” of a page break by using the following formula:

 p,  

b + p + q, c= 100000,   ∞,

if if if if

b < ∞ and p ≤ −10000 and q < 10000; b < 10000 and −10000 < p < 10000 and q < 10000; b = 10000 and −10000 < p < 10000 and q < 10000; (b = ∞ or q ≥ 10000) and p < 10000.

Here b is the badness of the page that would be formed if a break were chosen here; p is the penalty associated with the current breakpoint; and q is ‘\insertpenalties’, the sum of all penalties for split insertions on the page, as explained below. Vertical badness is computed by the same rules as horizontal badness; it is an integer between 0 and 10000, inclusive, except when the box is overfull, when it is ∞ (infinity).

111

112

Chapter 15: How TEX Makes Lines into Pages Ä Ä When a page is completed, it is removed from the main vertical list and passed

to an “output routine,” as we will see later; so its boxes and glue eventually disappear from TEX’s memory. The remainder of the main vertical list exists in two parts: First comes the “current page,” which contains all the material that TEX has considered so far as a candidate for the next page to be broken off; then there are “recent contributions,” i.e., items that will be moved to the current page as soon as TEX finds it convenient to do so. If you say \showlists, TEX will display the contents of the current page and the recent contributions, if any, on your log file. (The example in Chapter 13 doesn’t show any such lists because they were both empty in that case. Chapter 24 explains more about TEX’s timing.)

Ä Ä Whenever TEX is moving an item from the top of the “recent contributions” to

the bottom of the “current page,” it discards a discardable item (glue, kern, or penalty) if the current page does not contain any boxes. This is how glue disappears at a page break. Otherwise if a discardable item is a legitimate breakpoint, TEX calculates the cost c of breaking at this point, using the formula that we have just discussed. If the resulting c is less than or equal to the smallest cost seen so far on the current page, TEX remembers the current breakpoint as the best so far. And if c = ∞ or if p ≤ −10000, TEX seizes the initiative and breaks the page at the best remembered breakpoint. Any material on the current page following that best breakpoint is moved back onto the list of recent contributions, where it will be considered again; thus the “current page” typically gets more than one page’s worth of material before the breakpoint is chosen.

Ä Ä This procedure may seem mysterious until you see it in action. Fortunately,

there is a convenient way to watch it; you can set \tracingpages=1, thereby instructing TEX to put its page-cost calculations into your log file. For example, here is what appeared on the log file when the author used \tracingpages=1 at the beginning of the present chapter: %% goal height=528.0, max depth=2.2 % t=10.0 g=528.0 b=10000 p=150 c=100000# % t=22.0 g=528.0 b=10000 p=0 c=100000# % t=34.0 g=528.0 b=10000 p=0 c=100000# .. . (25 similar lines are being omitted here) % % % % % % % % % % % % % % %

t=346.0 plus 2.0 g=528.0 b=10000 p=0 c=100000# t=358.0 plus 2.0 g=528.0 b=10000 p=150 c=100000# t=370.02223 plus 2.0 g=528.0 b=10000 p=-100 c=100000# t=398.0 plus 5.0 minus 2.0 g=528.0 b=10000 p=0 c=100000# t=409.0 plus 5.0 minus 2.0 g=528.0 b=10000 p=0 c=100000# t=420.0 plus 5.0 minus 2.0 g=528.0 b=10000 p=150 c=100000# t=431.0 plus 5.0 minus 2.0 g=528.0 b=10000 p=-100 c=100000# t=459.0 plus 8.0 minus 4.0 g=528.0 b=10000 p=0 c=100000# t=470.0 plus 8.0 minus 4.0 g=528.0 b=10000 p=0 c=100000# t=481.0 plus 8.0 minus 4.0 g=528.0 b=10000 p=0 c=100000# t=492.0 plus 8.0 minus 4.0 g=528.0 b=10000 p=0 c=100000# t=503.0 plus 8.0 minus 4.0 g=528.0 b=3049 p=0 c=3049# t=514.0 plus 8.0 minus 4.0 g=528.0 b=533 p=150 c=683# t=525.0 plus 8.0 minus 4.0 g=528.0 b=5 p=-100 c=-95# t=553.0 plus 11.0 minus 6.0 g=528.0 b=* p=0 c=*

Chapter 15: How TEX Makes Lines into Pages This trace output is admittedly not “user-friendly” in appearance, but after all it comes from deep inside TEX’s bowels where things have been reduced to numeric calculations. You can learn to read it with a little practice, but you won’t need to do so very often unless you need to plunge into page-breaking for special applications. Here’s what it means: The first line, which starts with ‘%%’, is written when the first box or insertion enters the current page list; it shows the “goal height” and the “max depth” that will be used for that page (namely, the current values of \vsize and \maxdepth). In the present manual we have \vsize=44pc and \maxdepth=2.2pt; dimensions in the log file are always displayed in points. The subsequent lines, which start with a single ‘%’, are written whenever a legal breakpoint is being moved from the list of recent contributions to the current page list. Every % line shows t, which is the total height so far if a page break were to occur, and g, which is the goal height; in this example g stays fixed at 528 pt, but g would have decreased if insertions such as footnotes had occurred on the page. The values of t are steadily increasing from 10 to 22 to 34, etc.; baselines are 12 pt apart at the top of the page and 11 pt apart at the bottom (where material is set in nine-point type). We are essentially seeing one % line per hbox of text being placed on the current page. However, the % lines are generated by the penalty or glue items that follow the hboxes, not by the boxes themselves. Each % line shows also the badness b, the penalty p, and the cost c associated with a breakpoint; if this cost is the best so far, it is marked with a ‘#’ sign, meaning that “this breakpoint will be used for the current page if nothing better comes along.” Notice that the first 40 or so breaks all have b = 10000, since they are so bad that TEX considers them indistinguishable; in such cases c = 100000, so TEX simply accumulates material until the page is full enough to have b < 10000. A penalty of 150 reflects the \clubpenalty or the \widowpenalty that was inserted as described in Chapter 14. The three lines that say p=-100 are the breakpoints between “dangerous bend” paragraphs; these came from \medbreak commands. The notation b=* and c=* on the final line means that b and c are infinite; the total height of 553 pt cannot be reduced to 528 pt by shrinking the available glue. Therefore the page is ejected at the best previous place, which turns out to be a pretty good break: b=5 and p=-100 yield a net cost of −95.

Ä Äx EXERCISE 15.1

Suppose the paragraph at the bottom of the example page had been one line shorter; what page break would have been chosen?

Ä Äx EXERCISE 15.2

The last two “% lines” of this example show the natural height of t jumping by 28 pt, from 525.0 to 553.0. Explain why there was such a big jump.

Ä Ä The \maxdepth parameter tells TEX to raise the bottom box on the page if

that box has too much depth, so that the depth of the constructed page will not exceed a specified value. (See the discussion of \boxmaxdepth in Chapter 12.) In our example \maxdepth=2.2pt, and the influence of this parameter can be seen in the line that says ‘% t=370.02223’. Ordinarily t would have been 370.0 at that breakpoint; but the hbox preceding it was unusual because it contained the letter j in \tt, and a 10-point typewriter-style j descends 2.22223 pt below the baseline. Therefore TEX figured badness as if the hbox were .02223 pt higher and only 2.2 pt deep.

Ä Ä Notice that the first “% line” of our example says t=10.0; this is a consequence

of another parameter, called \topskip. Glue disappears at a page break, but

113

114

Chapter 15: How TEX Makes Lines into Pages it is desirable to produce pages whose top and bottom baselines occur in predetermined positions, whenever possible; therefore TEX inserts special glue just before the first box on each page. This special glue is equal to \topskip, except that the natural space has been decreased by the height of the first box, or it has been set to zero in lieu of a negative value. For example, if \topskip=20pt plus2pt, and if the first box on the current page is 13 pt tall, TEX inserts ‘\vskip7pt plus2pt’ just above that box. Furthermore, if the first box is more than 20 pt tall, ‘\vskip0pt plus2pt’ is inserted. But this example is atypical, since the \topskip glue usually has no stretchability or shrinkability; plain TEX sets \topskip=10pt.

Ä Äx EXERCISE 15.3

Assume that \vsize=528pt, \maxdepth=2.2pt, \topskip=10pt, and that no \insert commands are being used. TEX will make pages that are 528 pt high, and the following two statements will normally be true: (a) The baseline of the topmost box on the page will be 10 pt from the top, i.e., 518 pt above the baseline of the page itself. (b) The baseline of the bottommost box on the page will coincide with the baseline of the page itself. Explain under what circumstances (a) and (b) will fail.

Ä Ä Since \vsize, \maxdepth, and \topskip are parameters, you can change them

at any time; what happens if you do? Well, TEX salts away the values of \vsize and \maxdepth when it prints the “%% line,” i.e., when the first box or insertion occurs on the current page; subsequent changes to those two parameters have no effect until the next current page is started. On the other hand, TEX looks at \topskip only when the first box is being contributed to the current page. If insertions occur before the first box, the \topskip glue before that box is considered to be a valid breakpoint; this is the only case in which a completed page might not contain a box.

Ä Ä You can look at the t and g values that are used in page breaking by referring

to the hdimeni values ‘\pagetotal’ and ‘\pagegoal’, respectively. You can even change them (but let’s hope that you know what you are doing). For example, the command \pagegoal=500pt overrides the previously saved value of \vsize. Besides \pagetotal, which represents the accumulated natural height, TEX maintains the quantities \pagestretch, \pagefilstretch, \pagefillstretch, \pagefilllstretch, \pageshrink, and \pagedepth. When the current page contains no boxes, \pagetotal and its relatives are zero and \pagegoal is 16383.99998 pt (TEX’s largest hdimeni); changing their values has no effect at such times. The integer q in the formula for page costs is also available for inspection and change; it is called \insertpenalties.

Ä Ä Page breaking differs from line breaking in one small respect that deserves

mention here: If you say \eject\eject, the second \eject is ignored, because it is equivalent to \penalty-10000 and penalties are discarded after a page break. But if you say \break\break in a paragraph, the second \break causes an empty line, because penalties are discarded after a break in a paragraph only if they do not belong to the final sequence of breakpoints. This technicality is unimportant in practice, because \break\break isn’t a good way to make an empty line; that line will usually be an underfull hbox, since it has only the \leftskip and \rightskip glue in it. Similarly, ‘\eject\eject’ would not be a good way to make an empty page, even if TEX were to change its rules somehow so that an \eject would never be ignored. The best way to eject an empty page is to say ‘\eject\line{}\vfil\eject’, and the best way to create an empty line is ‘\break\hbox{}\hfil\break’. Both of these avoid underfull boxes.

Chapter 15: How TEX Makes Lines into Pages Ä

You are probably wondering how page numbers and such things get attached to pages. The answer is that TEX allows you to do further processing after each page break has been chosen; a special “output routine” goes into action before pages actually receive their final form. Chapter 23 explains how to construct output routines and how to modify the output routine of plain TEX.

Ä

Every once in a while, TEX will produce a really awful-looking page and you will wonder what happened. For example, you might get just one paragraph and a lot of white space, when some of the text on the following page would easily fit into the white space. The reason for such apparently anomalous behavior is almost always that no good page break is possible; even the alternative that looks better to you is quite terrible as far as TEX is concerned! TEX does not distinguish between two choices that both have 10000 units of badness or more, even though some bad breaks do look much worse than others. The solution in such cases is to insert \eject or \vfill\eject in some acceptable spot, or to revise the manuscript. If this problem arises frequently, however, you probably are using a format that sets overly strict limitations on page format; try looking at the output of \tracingpages and modifying some of TEX’s parameters, until you have better luck.

Ä

The remainder of this chapter is about insertions: things like footnotes and illustrations, and how they interact with page breaks. Before we discuss the primitive operations by which TEX deals with insertions, we will take a look at the facilities that plain TEX provides at a higher level.

Ä

Illustrations can be inserted in several ways using plain TEX. The simplest of these is called a “floating topinsert”; you say \topinserthvertical mode materiali\endinsert

and TEX will attempt to put the vertical mode material at the top of the current page. If there’s no room for such an insertion on one page, TEX will insert it at the top of the next page. The hvertical mode materiali can contain embedded paragraphs that temporarily interrupt vertical mode in the usual way; for example: \topinsert \vskip 2in \hsize=3in \raggedright \noindent{\bf Figure 3.} This is the caption to the third illustration of my paper. I have left two inches of space above the caption so that there will be room to introduce special artwork. \endinsert The caption in this example will be set ragged-right in a 3-inch column at the left of the page. Plain TEX automatically adds a “bigskip” below each topinsert; this will separate the caption from the text. The effects of \hsize=3in and \raggedright do not extend past the \endinsert, since grouping is implied.

Ä

x EXERCISE 15.4

Modify this example so that the caption is moved over next to the right margin, instead of appearing at the left.

Ä

Similarly, if you say ‘\pageinsert hvertical mode materiali \endinsert’, the vertical mode material will be justified to the size of a full page (without a bigskip below it); the result will appear on the following page.

115

116

Chapter 15: How TEX Makes Lines into Pages Ä

There’s also ‘\midinsert hvertical mode materiali \endinsert’, which tries first to insert the material in place, wherever you happen to be, in the middle of the current page. If there is enough room, you get the effect of \bigskip\vbox{hvertical mode materiali}\bigbreak otherwise the \midinsert is effectively converted to a \topinsert. There is a slight probability that \midinsert will not find the best placement, because TEX is sometimes processing text ahead of the current page. You may want to say ‘\goodbreak’ just before \midinsert.

Ä

You should use the commands \topinsert, \pageinsert, \midinsert in vertical mode (i.e., between paragraphs), not inside of boxes or other insertions.

Ä

If you have two or more \topinsert or \pageinsert commands in quick succession, TEX may need to carry them over to several subsequent pages; but they will retain their relative order when they are carried over. For example, suppose you have pages that are nine inches tall, and suppose you have already specified 4 inches of text for some page, say page 25. Then suppose you make seven topinserts in a row, of respective sizes 1, 2, 3, 9, 3, 2, 1 inches; the 9-inch one is actually a \pageinsert. What happens? Well, the first and second will appear at the top of page 25, followed by the 4 inches of copy you have already typed; that copy will immediately be followed by two more inches that you type after the seven inserts. The third topinsert will appear at the top of page 26, followed by six more inches of text; the fourth will fill page 27; and the remaining three will appear at the top of page 28.

Ä

x EXERCISE 15.5

What would happen in the example just discussed if the final 1-inch insertion were a \midinsert instead of a \topinsert?

Ä

At the end of a paper, you probably want to make sure that no insertions are lost; and at the end of a chapter, you probably want to make sure that no insertions float into the following chapter. Plain TEX will flush out all remaining insertions, with blank space filling the bottom of incomplete pages, if you say ‘\vfill\supereject’.

Ä

Besides illustrations that are inserted at the top of a page, plain TEX will also insert footnotes at the bottom of a page. The \footnote macro is provided for use within paragraphs;* for example, the footnote in the present sentence was typed in the following way: ... paragraphs;\footnote*{Like this.} for example, ... There are two parameters to a \footnote; first comes the reference mark, which will appear both in the paragraph** and in the footnote itself, and then comes the text of the footnote.45 The latter text may be several paragraphs long, and it may contain * Like this. ** The author typed ‘paragraph\footnote{**}{The author ...}’ here. 45

And ‘footnote.\footnote{$^{45}$}{And ...}’ here. The footnotes in this manual appear in smaller type, and they are set with hanging indentation; furthermore a smallskip occurs between footnotes on the same page. But in plain TEX, footnotes

Chapter 15: How TEX Makes Lines into Pages displayed equations and such things, but it should not involve other insertions. TEX will ensure that each footnote occurs at the bottom of the same page as its reference.† A long footnote will be split, if necessary, and continued at the bottom of the following page, as you can see in the somewhat contrived example that appears here. Authors who are interested in good exposition should avoid footnotes whenever possible, since footnotes tend to be distracting.‡

Ä

The \footnote macro should be used only in paragraphs or hboxes that are contributed to TEX’s main vertical list; insertions will be lost if they occur inside of boxes that are inside of boxes. Thus, for example, you should not try to put a \footnote into a subformula of a math formula. But it’s OK to use footnotes within \centerline, e.g., \centerline{A paper by A. U. Thor% \footnote*{Supported by NSF.}} or even on the outer level of a table entry inside an \halign.

Ä Ä Topinserts work fine by themselves, and footnotes work fine by themselves,

but complications can arise when you try to mix them in devious ways. For example, if a \pageinsert floats to the page that follows a long footnote that had to be broken, both of the held-over insertions may try to force themselves onto the same page, and an overfull vbox may result. Furthermore, insertions cannot appear within insertions, so you can’t use \footnote within a \topinsert. If you really need a footnote in some caption, there’s a \vfootnote macro that can be used in vertical mode. To use it, you put a reference mark like ‘*’ in the caption, and then you say ‘\vfootnote*{The footnote}’ somewhere on the page where you guess that the caption will finally fall. In such complex circumstances you might want to rethink whether or not you are really using the most appropriate format for the exposition of your ideas.

Ä Ä Chapter 24 explains the exact rules about migration of vertical-mode material

(like footnotes) from horizontal lists to the enclosing vertical list. Insertions, marks, and the results of \vadjust all migrate in the same fashion.

Ä

Now let’s study the primitives of TEX that are used to construct macros like \topinsert and \footnote. We are about to enter behind the scenes into a sublanguage of TEX that permits users to do complex manipulations with boxes and glue. Our discussion will be in two parts: First we shall consider TEX’s “registers,” with which a user can do arithmetic related to typesetting; and then we shall discuss the insertion items that can appear in horizontal and vertical lists. Our discussion of the first topic (registers) will be marked with single dangerous-bend signs, since registers are of general use in advanced applications of TEX, whether or not they relate to insertions. But the second topic will be marked with double dangerous-bend signs, since insertions are rather esoteric. are typeset with the normal size of type, with \textindent used for the reference mark, and without extra smallskips. The \textindent macro is like \item, but it omits hanging indentation. † Printers often use the symbols \dag (†), \ddag (‡), \S (§), and \P (¶) as reference marks; sometimes also $\|$ (k). You can say, e.g., ‘\footnote\dag{...}’. ‡ Yet Gibbon’s Decline and Fall would not have been the same without footnotes.

117

118

Chapter 15: How TEX Makes Lines into Pages Ä

TEX has 256 registers called \count0 to \count255, each capable of containing integers between −2147483647 and +2147483647, inclusive; i.e., the magnitudes should be less than 231 . TEX also has 256 registers called \dimen0 to \dimen255, each capable of containing a hdimeni (see Chapter 10). There are another 256 registers called \skip0 to \skip255, each containing hgluei (see Chapter 12); and \muskip0 to \muskip255, each containing hmugluei (see Chapter 18). You can assign new values to these registers by saying \counthnumberi = hnumberi \dimenhnumberi = hdimeni \skiphnumberi = hgluei \muskiphnumberi = hmugluei and then you can add or subtract values of the same type by saying \advance\counthnumberi by hnumberi \advance\dimenhnumberi by hdimeni \advance\skiphnumberi by hgluei \advance\muskiphnumberi by hmugluei For example, ‘\dimen8=\hsize \advance\dimen8 by 1in’ sets register \dimen8 to an inch more than the current value of the normal line size.

Ä

If infinite glue components are added, lower order infinities disappear. For example, after the two commands \skip2 = 0pt plus 2fill minus 3fill \advance\skip2 by 4pt plus 1fil minus 2filll

the value of \skip2 will be 4 pt plus 2 fill minus 2 filll.

Ä

Multiplication and division are possible too, but only by integers. For example, ‘\multiply\dimen4 by 3’ triples the value of \dimen4, and ‘\divide\skip5 by 2’ cuts in half all three components of the glue that is currently registered in \skip5. You shouldn’t divide by zero, nor should you multiply by numbers that will make the results exceed the register capacities. Division of a positive integer by a positive integer discards the remainder, and the sign of the result changes if you change the sign of either operand. For example, 14 divided by 3 yields 4; −14 divided by 3 yields −4; −14 divided by −3 yields 4. Dimension values are integer multiples of sp (scaled points).

Ä

You can use any \count register in the context of a hnumberi, any \dimen register in the context of a hdimeni, any \skip register in the context of hgluei, and any \muskip register in the context of hmugluei. For example, ‘\hskip\skip1’ puts horizontal glue into a list, using the value of \skip1; and if \count5 is 20, the command ‘\advance\dimen20 by\dimen\count5’ is equivalent to ‘\multiply\dimen20 by 2’.

Ä

A \dimen register can be used also in the context of a hnumberi, and a \skip register can be used as a hdimeni or a hnumberi. TEX converts hgluei to hdimeni by omitting the stretch and shrink components, and it converts hdimeni to hnumberi by assuming units of sp (scaled points). For example, if \skip1 holds the value 1 pt plus 2 pt, then ‘\dimen1=\skip1’ sets \dimen1 equal to 1 pt; and the commands ‘\count2=\dimen1’ or ‘\count2=\skip1’ will set \count2 equal to 65536. These rules also apply to TEX’s internal parameters; for example, ‘\dimen2=\baselineskip’ will set \dimen2 to the natural space component of the current baselineskip glue.

Chapter 15: How TEX Makes Lines into Pages Ä

x EXERCISE 15.6

Test your knowledge of TEX’s registers by stating the results of each of the following commands when they are performed in sequence: \count1=50 \dimen2=\count1pt \divide\count1 by 8 \skip2=-10pt plus\count1fil minus\dimen2 \multiply\skip2 by-\count1 \divide\skip2 by \dimen2 \skip1=.5\dimen2 plus\skip2 minus\count\count1fill \multiply\skip2 by\skip1 \advance\skip1 by-\skip2

Ä

x EXERCISE 15.7

What is in \skip5 after the following three commands have acted? \skip5=0pt plus 1pt \advance\skip5 by \skip4

Ä

\count6=\skip2

x EXERCISE 15.8

(For mathematicians.) Explain how to round \dimen2 to the nearest multiple of \dimen3, assuming that \dimen3 is nonzero.

Ä

The registers obey TEX’s group structure. For example, changes to \count3 inside {...} will not affect the value of \count3 outside. Therefore TEX effectively has more than 256 registers of each type. If you want the effect of a register command to transcend its group, you must say \global when you change the value.

Ä

x EXERCISE 15.9

What is in \count1 after the following sequence of commands? \count1=5 {\count1=2 \global\advance\count1by\count1 \advance\count1by\count1}

Ä

The first ten \count registers, \count0 through \count9, are reserved for a special purpose: TEX displays these ten counts on your terminal whenever outputting a page, and it transmits them to the output file as an identification of that page. The counts are separated by decimal points on your terminal, with trailing ‘.0’ patterns suppressed. Thus, for example, if \count0=5 and \count2=7 when a page is being shipped out to the dvi file, and if the other count registers are zero, TEX will type ‘[5.0.7]’. Plain TEX uses \count0 for the page number, and it keeps \count1 through \count9 equal to zero; that is why you see just ‘[1]’ when page 1 is being output. In more complex applications the page numbers can have further structure; ten counts are shipped out so that there will be plenty of identification.

Ä

It’s usually desirable to have symbolic names for registers. TEX provides a \countdef command (similar to \chardef, cf. Chapter 8), which makes it easy to do this: You just say \countdef\chapno=28 and \chapno is henceforth an abbreviation for \count28. Similar commands \dimendef, \skipdef, and \muskipdef are available for the other types of numeric registers. After a control sequence has been defined by \countdef, it can be used in TEX commands exactly as if it were an integer parameter like \tolerance. Similarly, \dimendef effectively creates a new dimension parameter, \skipdef effectively creates a new glue parameter, and \muskipdef effectively creates a new muglue parameter.

119

120

Chapter 15: How TEX Makes Lines into Pages Ä

Besides the numerical registers, TEX also has 256 box registers called \box0 to \box255. A box register gets a value when you say \setboxhnumberi=hboxi; for example, ‘\setbox3=\hbox{A}’ sets \box3 to an hbox that contains the single letter A. Several other examples of \setbox have already appeared in Chapter 12. Chapter 10 points out that ‘2\wd3’ is a hdimeni that represents twice the width of \box3; similarly, \hthnumberi and \dphnumberi can be used to refer to the height and depth of a given box register.

Ä

Box registers are local to groups just as arithmetic registers are. But there’s a big difference between box registers and all the rest: When you use a \box, it loses its value. For example, the construction ‘\raise2pt\box3’ in a horizontal list not only puts the contents of \box3 into the list after raising it by 2 pt, it also makes \box3 void. TEX does this for efficiency, since it is desirable to avoid copying the contents of potentially large boxes. If you want to use a box register without wiping out its contents, just say ‘\copy’ instead of ‘\box’; for example, ‘\raise2pt\copy3’.

Ä

Another way to use a box register is to extract the inside of an hbox by saying ‘\unhbox’. This annihilates the contents of the register, like ‘\box’ does, and it also removes one level of boxing. For example, the commands \setbox3=\hbox{A} \setbox3=\hbox{\box3 B} \setbox4=\hbox{A} \setbox4=\hbox{\unhbox4 B}

put \hbox{\hbox{A}B} into \box3 and \hbox{AB} into \box4. Similarly, \unvbox unwraps a vbox. If you want to construct a large box by accretion (e.g., a table of contents), it is best to use \unhbox or \unvbox as in the \setbox4 example; otherwise you use more of TEX’s memory space, and you might even obtain boxes inside boxes nested to such a deep level that hardware or software limits are exceeded.

Ä

The operations \unhcopy and \unvcopy are related to \unhbox and \unvbox as \copy is to \box. (But their names are admittedly peculiar.)

Ä

An unboxing operation “unsets” any glue that was set at the box’s outer level. For example, consider the sequence of commands \setbox5=\hbox{A \hbox{B C}} \setbox6=\hbox to 1.05\wd5{\unhcopy5}

This makes \box6 five percent wider than \box5; the glue between A and \hbox{B C} stretches to make the difference, but the glue inside the inner hbox does not change.

Ä

A box register is either “void” or it contains an hbox or a vbox. There is a difference between a void register and one that contains an empty box whose height, width, and depth are zero; for example, if \box3 is void, you can say \unhbox3 or \unvbox3 or \unhcopy3 or \unvcopy3, but if \box3 is equal to \hbox{} you can say only \unhbox3 or \unhcopy3. If you say ‘\global\setbox3=hboxi’, register \box3 will become “globally void” when it is subsequently used or unboxed.

Ä

x EXERCISE 15.10

What is in register \box5 after the following commands?

\setbox5=\hbox{A}

Ä

x EXERCISE 15.11

\setbox5=\hbox{\copy5\unhbox5\box5\unhcopy5}

And what’s in \box3 after ‘{\global\setbox3=\hbox{A}\setbox3=\hbox{}}’ ?

Chapter 15: How TEX Makes Lines into Pages Ä

If you are unsure about how TEX operates on its registers, you can experiment online by using certain ‘\show’ commands. For example, \showthe\count1

\showthe\dimen2

\showthe\skip3

will display the contents of \count1, \dimen2, and \skip3; and ‘\showbox4’ will display the contents of \box4. Box contents will appear only in the log file, unless you say ‘\tracingonline=1’. Plain TEX provides a macro ‘\tracingall’ that turns on every possible mode of interaction, including \tracingonline. The author used these features to check the answers to several of the exercises above.

Ä

Large applications of TEX make use of different sets of macros written by different groups of people. Chaos would reign if a register like \count100, say, were being used simultaneously for different purposes in different macros. Therefore plain TEX provides an allocation facility; cooperation will replace confusion if each macro writer uses these conventions. The idea is to say, e.g., ‘\newcount’ when you want to dedicate a \count register to a special purpose. For example, the author designed a macro called ‘\exercise’ to format the exercises in this manual, and one of the features of \exercise is that it computes the number of the current exercise. The format macros in Appendix E reserve a \count register for this purpose by saying \newcount\exno

and then the command ‘\exno=0’ is used at the beginning of each chapter. Similarly, ‘\advance\exno by1’ is used whenever a new exercise comes along, and ‘\the\exno’ is used to typeset the current exercise number. The \newcount operation assigns a unique count register to its argument \exno, and it defines \exno with a \countdef command. All of the other format macros are written without the knowledge of exactly which \count register actually corresponds to \exno.

Ä

Besides \newcount, plain TEX provides \newdimen, \newskip, \newmuskip, and \newbox; there also are \newtoks, \newread, \newwrite, \newfam, and \newinsert, for features we haven’t discussed yet. Appendices B and E contain several examples of the proper use of allocation. In the cases of \newbox, \newread, etc., the allocated number is defined by \chardef. For example, if the command ‘\newbox\abstract’ is used to define a box register that will contain an abstract, and if the \newbox operation decides to allocate \box45 for this purpose, then it defines the meaning of \abstract by saying ‘\chardef\abstract=45’. TEX allows \chardef’d quantities to be used as integers, so that you can say \box\abstract and \copy\abstract, etc. (There is no \boxdef command.)

Ä

x EXERCISE 15.12

Design a \note macro that produces footnotes numbered sequentially. For example,1 it should produce the footnotes here2 if you type ... example,\note{First note.} it should produce the footnotes here\note{Second note.} if ...

(Use \newcount to allocate a \count register for the footnotes.) 1

First note.

2

Second note.

121

122

Chapter 15: How TEX Makes Lines into Pages Ä

Sometimes, however, you want to use a register just for temporary storage, and you know that it won’t conflict with anybody else’s macros. Registers \count255, \dimen255, \skip255, and \muskip255 are traditionally kept available for such purposes. Furthermore, plain TEX reserves \dimen0 to \dimen9, \skip0 to \skip9, \muskip0 to \muskip9, and \box0 to \box9 for “scratchwork”; these registers are never allocated by the \new... operations. We have seen that \count0 through \count9 are special, and \box255 also turns out to be special; so those registers should be avoided unless you know what you are doing.

Ä Ä Of course any register can be used for short-term purposes inside a group

(including \count0 to \count9 and \box255, and including registers that have been allocated for other purposes), since register changes are local to groups. However, you should be sure that TEX will not output any pages before the group has ended, because output routines might otherwise be invoked at unfortunate times. TEX is liable to invoke an output routine whenever it tries to move something from the list of recent contributions to the current page, because it might discover a page break with c = ∞ then. Here is a list of the times when that can happen: (a) At the beginning or end of a paragraph, provided that this paragraph is being contributed to the main vertical list. (b) At the beginning or end of a displayed equation within such a paragraph. (c) After completing an \halign in vertical mode. (d) After contributing a box or penalty or insertion to the main vertical list. (e) After an \output routine has ended.

Ä Ä Now that we are armed with the knowledge of TEX’s flexible registers, we

can plunge into the details of insertions. There are 255 classes of insertions, \insert0 to \insert254, and they are tied to other registers of the same number. For example, \insert100 is connected with \count100, \dimen100, \skip100, and \box100. Therefore plain TEX provides an allocation function for insertions as it does for registers; Appendix B includes the command \newinsert\footins

which defines \footins as the number for footnote insertions. Other commands that deal with footnotes refer to \count\footins, \dimen\footins, and so on. The macros for floating topinserts are similarly prefaced by ‘\newinsert\topins’, which defines \topins as the number of their class. Each class of insertions is independent, but TEX preserves the order of insertions within a class. It turns out that \footins is class 254, and \topins is class 253, but the macros do not use such numbers directly.

Ä Ä For our purposes let’s consider a particular class of insertions called class n; we will then be dealing with TEX’s primitive command

\insert n{hvertical mode materiali} which puts an insertion item into a horizontal or vertical list. For this class of insertions \box n is where the material appears when a page is output; \count n is the magnification factor for page breaking; \dimen n is the maximum insertion size per page; \skip n is the extra space to allocate on a page. For example, material inserted with \insert100 will eventually appear in \box100.

Chapter 15: How TEX Makes Lines into Pages Ä Ä Let the natural height plus depth of \insert n be x; then \count n is 1000

times the factor by which x affects the page goal. For example, plain TEX sets \count\footins=1000, since there is a one-to-one relationship: A 10-point footnote effectively makes a page 10 pt shorter. But if we have an application where footnotes appear in double columns, a count value of 500 would be appropriate. One of the insertion classes in Appendix E makes marginal notes for proofreading purposes; in that case the count value is zero. No actual magnification is done; \count n is simply a number used for bookkeeping, when estimating the costs of various page breaks.

Ä Ä The first footnote on a page requires extra space, since we want to separate

the footnotes from the text, and since we want to output a horizontal rule. Plain TEX sets ‘\skip\footins=\bigskipamount’; this means that a bigskip of extra space is assumed to be added by the output routine to any page that contains at least one insertion of class \footins.

Ä Ä Sometimes it is desirable to put a maximum limitation on the size of insertions;

for example, people usually don’t want an entire page to consist of footnotes. Plain TEX sets \dimen\footins=8in; this means that \box\footins is not supposed to accumulate more than 8 inches of footnotes for any one page.

Ä Ä You might want to review the page-breaking algorithm explained at the be-

ginning of this chapter, before reading further. On the other hand, maybe you don’t really want to read the rest of this chapter at all, ever.

Ä Ä Here now is the algorithm that TEX performs when an \insert n is moved from the “recent contributions” to the “current page.” (Remember that such a move does not mean that the insertion will actually take place; the current page will be backed up later, to the breakpoint of least cost, and only the insertions preceding that breakpoint will actually be performed.) Let g and t be the current \pagegoal and \pagetotal; let q be the \insertpenalties accumulated for the current page; and let d and z be the current \pagedepth and \pageshrink. (The value of d is at most \maxdepth; this value has not yet been incorporated into t.) Finally, let x be the natural height plus depth of the \insert n that we are moving to the current page; and let f be the corresponding magnification factor, i.e., \count n divided by 1000.

Step 1. If there is no previous \insert n on the current page, decrease g by hf + w, where h is the current height plus depth of \box n, and where w is the natural space component of \skip n; also include the stretch and shrink components of \skip n in the totals for the current page (in particular, this affects z). Step 2. If a previous \insert n on the current page has been split, add the parameter called \floatingpenalty to q, and omit Steps 3 and 4. Step 3. Test if the current insertion will fit on the page without splitting. This means that it will not make the height plus depth of \box n surpass \dimen n, when it is added to \box n together with all previous \insert n amounts on the current page; furthermore, it means that either xf ≤ 0 or t + d + xf − z ≤ g. If both tests are passed, subtract xf from g and omit Step 4. Step 4. (The current insertion will be split, at least tentatively; but the split will not actually take place if the least-cost page turns out to have occurred earlier than the present insertion.) First compute the largest amount v such that a height plus depth

123

124

Chapter 15: How TEX Makes Lines into Pages of v will not make the total insertions into \box n bigger than \dimen n, and such that t + d + vf ≤ g. (Notice that z is omitted from the latter formula, but the available shrinkability was considered in Step 3 when we tried to avoid splitting.) Then find the least-cost way to split the beginning of the vertical list of the insertion so as to obtain a box of height v. (Use an algorithm just like page-breaking, but without the complexity of insertion; an additional ‘\penalty-10000’ item is assumed to be present at the end of the vertical list, to ensure that a legal breakpoint exists.) Let u be the natural height plus depth of that least-cost box, and let r be the penalty associated with the optimum breakpoint. Decrease g by uf , and increase q by r. (If \tracingpages=1, the log file should now get a cryptic message that says ‘% split n to v,u p=r’. For example, % split254 to 180.2,175.3 p=100 means that the algorithm has tried to split an \insert254 to 180.2 pt; the best split is actually 175.3 pt tall, and the penalty for breaking there is 100.)

Ä Ä This algorithm is admittedly complicated, but no simpler mechanism seems

to do nearly as much. Notice that penalties of −10000 inside insertions will make certain splits very attractive in Step 4, so the user can provide hints about where to break, in difficult situations. The algorithm provides a variety of different behaviors: Floating insertions can be accommodated as a special case of split insertions, by making each floating topinsert start with a small penalty, and by having zero as the associated \floatingpenalty; non-floating insertions like footnotes are accommodated by associating larger penalties with split insertions (see Appendix B).

Ä Ä The splitting operation mentioned in Step 4 is also available as a primitive:

‘\vsplithnumberi tohdimeni’ produces a vbox obtained by splitting off a specified amount of material from a box register. For example, \setbox200=\vsplit100 to 50pt

sets \box200 to a vbox whose height is 50 pt; it goes through the vertical list inside \box100 (which should be a vbox) and finds the least-cost break assuming a goal height of 50 pt, considering badnesses and penalties just as in the case of page-breaking (but with q = 0). The algorithm uses \splitmaxdepth instead of \maxdepth to govern the maximum depth of boxes. Then it prunes the top of \box100 by removing everything up to and including any discardable items that immediately follow the optimum breakpoint; and it uses \splittopskip to insert new glue before the first box inside \box100, just as \topskip glue appears at the top of a page. However, if the optimum breakpoint occurs at the end of the vertical list inside \box100—a ‘\penalty-10000’ item is assumed to be present there—or if all items after the optimum breakpoint are discarded, \box100 will be void after the \vsplit. And if \box100 was void before the \vsplit, both \box100 and \box200 will be void afterwards.

Ä Ä You’d better not change \box n, \count n, \dimen n, or \skip n while TEX is

contributing insertions to the current page, since TEX’s algorithm assumes that those quantities are static. But you can change \floatingpenalty, \splittopskip, and \splitmaxdepth; TEX will use the values that were current just inside the closing right brace of ‘\insert n{...}’ when it splits and floats insertions. For example, Appendix B uses \floatingpenalty=20000 in footnote insertions, to discourage footnotes that split before others can start, but \floatingpenalty=0 in floating topinserts. Ap-

Chapter 15: How TEX Makes Lines into Pages pendix B also uses special values of \splittopskip and \splitmaxdepth, together with struts, so that split footnotes will be typeset with the same spacing as unsplit ones.

Ä Ä The \footnote macro puts an \insert into the horizontal list of a paragraph.

After the paragraph has been broken into lines, this insertion will move out into the vertical list just after the line that contained it (see Chapter 14). Since there is no legal breakpoint between that box (i.e., that line) and the insertion, TEX will put the insertion onto the page that contains the line that contains the insertion.

Ä Äx EXERCISE 15.13

Study the page-breaking algorithm carefully. Is it possible that a footnote might not appear on the same page as its reference?

Ä Ä When the best page break is finally chosen, TEX removes everything after

the chosen breakpoint from the bottom of the “current page,” and puts it all back at the top of the “recent contributions.” The chosen breakpoint itself is placed at the very top of the recent contributions. If it is a penalty item, the value of the penalty is recorded in \outputpenalty and the penalty in the contribution list is changed to 10000; otherwise \outputpenalty is set to 10000. The insertions that remain on the current page are of three kinds: For each class n there are unsplit insertions, followed possibly by a single split insertion, followed possibly by others. If \holdinginserts > 0, all insertions remain in place (so that they might be contributed again); otherwise they are all removed from the current page list as follows: The unsplit insertions are appended to \box n, with no interline glue between them. (Struts should be used, as in the \vfootnote macro of Appendix B.) If a split insertion is present, it is effectively \vsplit to the size that was computed previously in Step 4; the top part is treated as an unsplit insertion, and the remainder (if any) is converted to an insertion as if it had not been split. This remainder, followed by any other floating insertions of the same class, is held over in a separate place. (They will show up on the “current page” if \showlists is used while an \output routine is active; the total number of such insertions appears in \insertpenalties during an \output routine.) Finally, the remaining items before the best break on the current page are put together in a \vbox of height g, where g was the \pagegoal at the time of the break, using the saved value of \maxdepth; this box becomes \box255. Now the user’s \output routine enters TEX’s scanner (see Chapter 23); its duty is to assemble the final pages based on the contents of \box255 and any insertion boxes that it knows about. The output routine will probably unbox those boxes, so that their glue can be reset; the glue in insertion boxes usually cooperates nicely with the glue on the rest of the page, when it is given a chance. After the \output routine is finished, held-over insertion items are placed first on the list of recent contributions, followed by the vertical list constructed by \output, followed by the recent contributions beginning with the page break. (Deep breath.) You got that? Since it is impossible to foresee how [footnotes] will happen to come out in the make-up, it is impracticable to number them from 1 up on each page. The best way is to number them consecutively throughout an article or by chapters in a book. — UNIVERSITY OF CHICAGO PRESS, Manual of Style (1910) Don’t use footnotes in your books, Don. — JILL KNUTH (1962)

125

(page 126)

16 Typing Math Formulas

Chapter 16: Typing Math Formulas

TEX is designed to handle complex mathematical expressions in such a way that most of them are easy to input. The basic idea is that a complicated formula is composed of less complicated formulas put together in a simple way; the less complicated formulas are, in turn, made up of simple combinations of formulas that are even less complicated; and so on. Stating this another way, if you know how to type simple formulas and how to combine formulas into larger ones, you will be able to handle virtually any formula at all. So let’s start with simple ones and work our way up. The simplest formula is a single letter, like ‘x’, or a single number, like ‘2’. In order to put these into a TEX text, you type ‘$x$’ and ‘$2$’, respectively. Notice that all mathematical formulas are enclosed in special math brackets; we are using $as the math bracket in this manual, in accord with the plain TEX format defined in Appendix B, because mathematics is supposedly expensive. When you type ‘$x$’ the ‘x’ comes out in italics, but when you type ‘$2$’ the ‘2’ comes out in roman type. In general, all characters on your keyboard have a special interpretation in math formulas, according to the normal conventions of mathematics printing: Letters now denote italic letters, while digits and punctuation denote roman digits and punctuation; a hyphen (-) now denotes a minus sign (−), which is almost the same as an em-dash but not quite (see Chapter 2). The first$ that you type puts you into “math mode” and the second takes you out (see Chapter 13). So if you forget one $or type one$ too many, TEX will probably become thoroughly confused and you will probably get some sort of error message. Formulas that have been typeset by a printer who is unaccustomed to mathematics usually look quite strange to a mathematician, because a novice printer usually gets the spacing all wrong. In order to alleviate this problem, TEX does most of its own spacing in math formulas; and it ignores any spaces that you yourself put between $’s. For example, if you type ‘$ x$’ and ‘$ 2 $’, they will mean the same thing as ‘$x$’ and ‘$2$’. You can type ‘$(x + y)/(x - y)$’ or ‘$(x+y) / (x-y)$’, but both will result in ‘(x + y)/(x − y)’, a formula in which there is a bit of extra space surrounding the + and − signs but none around the / sign. Thus, you do not have to memorize the complicated rules of math spacing, and you are free to use blank spaces in any way you like. Of course, spaces are still used in the normal way to mark the end of control sequences, as explained in Chapter 3. In most circumstances TEX’s spacing will be what a mathematician is accustomed to; but we will see in Chapter 18 that there are control sequences by which you can override TEX’s spacing rules if you want to. One of the things mathematicians like to do is make their formulas look like Greek to the uninitiated. In plain TEX language you can type ‘$$\alpha, \beta, \gamma, \delta;$$’ and you will get the first four Greek letters α, β, γ, δ; furthermore there are uppercase Greek letters like ‘Γ’, which you can get by typing ‘$\Gamma$’. Don’t feel intimidated if you aren’t already familiar with 127 128 Chapter 16: Typing Math Formulas Greek letters; they will be easy to learn if you need them. The only difficulty is that some symbols that look nearly the same must be carefully distinguished. For example, the Greek letters \nu (ν) and \kappa (κ) should not be confused with the italic letters v and x; the Greek \phi (φ) is different from the slashed zero called \emptyset (∅). A lowercase epsilon (²) is quite different from the symbol used to denote membership in a set (∈); type ‘$\epsilon$’ for ² and ‘$\in$’ for ∈. Some of the lowercase Greek letters have variant forms in plain TEX’s math italic fonts: ‘$(\phi,\theta,\epsilon,\rho)$’ yields ‘(φ, θ, ², ρ)’ while ‘$(\varphi,\vartheta,\varepsilon,\varrho)$’ yields ‘(ϕ, ϑ, ε, %)’. Besides Greek letters, there are a lot of funny symbols like ‘≈’ (which you get by typing ‘$\approx$’) and ‘7→’ (which you get by typing ‘$\mapsto$’). A complete list of these control sequences and the characters they correspond to appears in Appendix F. Such control sequences are allowed only in math mode, i.e., between$’s, because the corresponding symbols appear in the math fonts. x EXERCISE 16.1 What should you type to get the formula ‘γ + ν ∈ Γ’ ? x EXERCISE 16.2 Look at Appendix F to discover the control sequences for ‘≤’, ‘≥’, and ‘6=’. (These are probably the three most commonly used math symbols that are not present on your keyboard.) What does plain TEX call them? Now let’s see how the more complex formulas get built up from simple ones. In the first place, you can get superscripts (up high) and subscripts (down low) by using ‘^’ and ‘_’, as shown in the following examples: Input

Output

$x^2$ $x_2$ $2^x$ $x^2y^2$ $x ^ 2y ^ 2$ $x_2y_2$ $_2F_3$

x2 x2 2x x2 y 2 x2 y 2 x 2 y2 2 F3

Notice that ^ and _ apply only to the next single character. If you want several things to be superscripted or subscripted, just enclose them in braces: $x^{2y}$ $2^{2^x}$ $2^{2^{2^x}}$ $y_{x_2}$ $y_{x^2}$

x2y x 22 2x 22 y x2 y x2

Chapter 16: Typing Math Formulas

The braces in these examples have been used to specify “subformulas,” i.e., simpler parts of a larger formula. TEX makes a box for each subformula, and treats that box as if it were a single symbol. Braces also serve their usual purpose of grouping, as discussed in Chapter 5. It is illegal to type ‘x^y^z’ or ‘x_y_z’; TEX will complain of a “double superscript” or “double subscript.” You must type ‘x^{y^z}’ or ‘x^{yz}’ or ‘x_{y_z}’ or ‘x_{yz}’ in order to make your intention clear. A superscript or subscript following a character applies to that character only; but when following a subformula it applies to that whole subformula, and it will be raised or lowered accordingly. For example, $((x^2)^3)^4$

((x2 )3 )4

${({(x^2)}^3)}^4$

((x2 ) )

3 4

In the first formula the ‘^3’ and ‘^4’ are superscripts on the right parentheses, i.e., on the ‘)’ characters that immediately precede them, but in the second formula they are superscripts on the subformulas that are enclosed in braces. The first alternative is preferable, because it is much easier to type and it is just as easy to read. Ä

A subscript or superscript following nothing (as in the ‘_2F_3’ example on the preceding page, where the ‘_2’ follows nothing) is taken to mean a subscript or superscript of an empty subformula. Such notations are (fortunately) rare in mathematics; but if you do encounter them it is better to make your intention clear by showing the empty subformula explicitly with braces. In other words, the best way to get ‘2 F3 ’ in a formula is to type ‘{}_2F_3’ or ‘{_2}F_3’ or ‘{_2F_3}’.

Ä

x EXERCISE 16.3

Ä

x EXERCISE 16.4

What difference, if any, is there between the output of ‘$x + _2F_3$’ and the output of ‘$x + {}_2F_3$’ ? Describe the differences between the outputs of ‘${x^y}^z$’ and ‘$x^{y^z}$’.

You can have simultaneous subscripts and superscripts, and you can specify them in any order: $x^2_3$ $x_3^2$ $x^{31415}_{92}+\pi$

x23 x23 x31415 +π 92

$x_{y^a_b}^{z_c^d}$

xyca

super b scripts

zd b

Notice that simultaneous are positioned over each other. However, a subscript will be “tucked in” slightly when it follows certain letters; for example, ‘$P_2^2$’ produces ‘P22 ’. If for some reason you want the left edges of both subscript and superscript to be aligned, you can fool TEX by inserting a null subformula: ‘$P{}_2^2$’ produces ‘P 22 ’.

129

130

Chapter 16: Typing Math Formulas

The control sequence \prime stands for the symbol ‘0’, which is used mostly in superscripts. In fact, ‘0’ is so big as it stands that you would never want to use it except in a subscript or superscript, where it occurs in a smaller size. Here are some typical examples: Input

Output

$y_1^\prime$ $y_2^{\prime\prime}$ $y_3^{\prime\prime\prime}$

y10 y200 y3000

Since single and double primes occur rather frequently, plain TEX provides a convenient abbreviation: You can simply type ’ instead of ^\prime, and ’’ instead of ^{\prime\prime}, and so on. $f’[g(x)]g’(x)$ $y_1’+y_2’’$ $y’_1+y’’_2$ $y’’’_3+g’^2$ Ä

x EXERCISE 16.5

Ä

x EXERCISE 16.6

f 0 [g(x)]g 0 (x) y10 + y200 y10 + y200 y3000 + g 02

Why do you think TEX treats \prime as a large symbol that appears only in superscripts, instead of making it a smaller symbol that has already been shifted up into the superscript position? Mathematicians sometimes use “tensor notation” in which subscripts and superscripts are staggered, as in ‘Ri jk l ’. Explain how to achieve such an effect.

Another way to get complex formulas from simple ones is to use the control sequences \sqrt, \underline, or \overline. Like ^ and _, these operations apply to the character or subformula that follows them: √ 2 $\sqrt2$ √ $\sqrt{x+2}$ x+2 $\underline4$ 4 $\overline{x+y}$ x+y $\overline x+\overline y$ x+y $x^{\underline n}$ xn $x^{\overline{m+n}}$ xm+n p √ $\sqrt{x^3+\sqrt\alpha}$ x3 + α √ You can also get cube roots ‘ 3 ’ and similar things by using \root: √ 3 $\root 3 \of 2$ 2 √ n $\root n \of {x^n+y^n}$ xn + y n √ n+1 a $\root n+1 \of a$

Chapter 16: Typing Math Formulas

Ä

The \sqrt and \underline and \overline operations are able to place lines above or below subformulas of any size or shape; the bar lines change their size and position, so that they are long enough to cover the subformula, and high enough or low enough not to bump into it. For example, consider ‘\overline l’ ( l ) versus ‘\overline m’ ( m ): the first has a shorter bar line, and this line has been raised higher than the bar in the second. Similarly, the bar in ‘\underline y’ ( y ) is lower than the bar in ‘\underline x’ ( x ); and square root signs appear of positions √ in√a variety √ based on the height and depth of what is being \sqrt’d: a + d + y. TEX knows the height, depth, and width of every letter and every subformula, because it considers them to be boxes, as explained in Chapter 11. If you have a formula in which there is only one \sqrt, or only one \overline or \underline, the normal positioning rules work fine; but sometimes you want to have uniformity between of a p members p p different complex formula. For example, you might want to typeset ‘ a + d + y’, putting all square roots in the same vertical position. There’s an easy way to do this, using the control sequence \mathstrut as follows: $\sqrt{\mathstrut a}+\sqrt{\mathstrut d}+\sqrt{\mathstrut y}$. A \mathstrut is an invisible box whose width is zero; its height and depth are the height and depth of a parenthesis ‘(’. Therefore subformulas that contain \mathstrut will always have the same height and depth, unless they involve more complicated constructions like subscripts and superscripts. Chapter 18 discusses more powerful operations called \smash and \phantom by which you can obtain complete control over the positioning of roots and similar signs.

x EXERCISE 16.7 Test your understanding of what you have read so far in this chapter by explaining what should be typed to get the following formulas. (Be sure to check your answer with Appendix A to confirm that you’re right.) p p 3 1 − x2 w + z pe11 abcd h00n (αx) 1010 2n+1 (n + 1)2 e

x EXERCISE 16.8 What mistake did B. C. Dull discover after he typed the following? If$x = y$, then $x$ is equal to $y.$

x EXERCISE 16.9 Explain how to type the following sentence: Deleting an element from an n-tuple leaves an (n − 1)-tuple. x EXERCISE 16.10 List all the italic letters that descend below the baseline. (These are the letters for which \underline will lower its bar line.) We have discussed the fact that the characters you type have special meanings in math mode, but the examples so far are incomplete; they don’t reveal all the power that is at your fingertips just after you press the ‘$’ key. It’s time now to go back to basics: Let us make a systematic survey of what each character does, when it is used in a formula. 131 132 Chapter 16: Typing Math Formulas The 52 letters (A to Z and a to z) denote italic symbols (A to Z and a to z), which a mathematician would call “variables.” TEX just calls them “ordinary symbols,” because they make up the bulk of math formulas. There are two variants of lowercase L in plain TEX, namely ‘l’ (which you get by simply typing ‘l’) and ‘’ (which you get by typing ‘\ell’). Although mathematicians commonly write something that looks like ‘’ in their manuscripts, they do so only to distinguish it from the numeral ‘1’. This distinguishability problem is not present in printed mathematics, since an italic ‘l’ is quite different from a ‘1’; therefore it is traditional to use ‘l’ unless ‘’ has been specifically requested. Plain TEX also treats the 18 characters 0 1 2 3 4 5 6 7 8 9 ! ? . | / ‘ @ " as ordinary symbols; i.e., it doesn’t insert any extra space when these symbols occur next to each other or next to letters. Unlike the letters, these 18 characters remain in roman type when they appear in formulas. There’s nothing special for you to remember about them, except that the vertical line ‘|’ has special uses that we shall discuss later. Furthermore, you should be careful to distinguish between ‘oh’ and ‘zero’: The italic letter O is almost never used in formulas unless it appears just before a left parenthesis, as in ‘O(n)’; and the numeral 0 is almost never used just before a left parenthesis unless it is preceded by another digit, as in ‘10(n − 1)’. Watch for left parentheses and you’ll be 0K. (Lowercase o’s also tend to appear only before left parentheses; type ‘x_0’ instead of ‘x_o’, since the formula ‘x0 ’ is generally more correct than ‘xo ’.) The three characters +, -, and * are called “binary operations,” because they operate on two parts of a formula. For example, + is a plus sign, which is used for the sum of two numbers; - is a minus sign. The asterisk (*) is rarer in mathematics, but it also behaves as a binary operation. Here are some examples of how TEX typesets binary operations when they appear next to ordinary symbols: Input Output$x+y-zx+y*zx*y/z$x+y−z x+y∗z x ∗ y/z Notice that - and * produce quite different math symbols from what you get in normal text: The hyphen (-) becomes a minus sign (−), and the raised asterisk (*) drops down to a lower level (∗). Ä TEX does not treat / as a binary operation, even though a slash stands for division (which qualifies as a binary operation on mathematical grounds). The reason is that printers traditionally put extra space around the symbols +, −, and ∗, but not around /. If TEX were to typeset / as a binary operation, the formula ‘$1/2$’ would come out ‘1 / 2’, which is wrong; so TEX considers / to be an ordinary symbol. Chapter 16: Typing Math Formulas Ä Appendix F lists many more binary operations, for which you type control sequences instead of single characters. Here are some examples:$x\times y\cdot zx\circ y\bullet zx\cup y\cap zx\sqcup y\sqcap zx\vee y\wedge zx\pm y\mp z$x×y·z x◦y•z x∪y∩z xtyuz x∨y∧z x±y∓z It is important to distinguish × (\times) from X (X) and from x (x); to distinguish ∪ (\cup) from U (U) and from u (u); to distinguish ∨ (\vee) from V (V) and from v (v); to distinguish ◦ (\circ) from O (O) and from o (o). The symbols ‘∨’ and ‘∧’ can also be called \lor and \land, since they frequently stand for binary operations that are called “logical or” and “logical and.” Ä Incidentally, binary operations are treated as ordinary symbols if they don’t occur between two quantities that they can operate on. For example, no extra space is inserted next to the +, −, and ∗ in cases like the following:$x=+13.142-(D*)$x = +1 3.142− (D∗) Consider also the following examples, which show that binary operations can be used as ordinary symbols in superscripts and subscripts:$K_n^+,K_n^-z^*_{ij}g^\circ \mapsto g^\bulletf^*(x) \cap f_*(y)$Ä Kn+ , Kn− ∗ zij g ◦ 7→ g • f ∗ (x) ∩ f∗ (y) x EXERCISE 16.11 How would you obtain the formulas ‘z ∗2 ’ and ‘h0∗ (z)’ ? Plain TEX treats the four characters =, , and : as “relations” because they express a relationship between two quantities. For example, ‘x < y’ means that x is less than y. Such relationships have a rather different meaning from binary operations like +, and the symbols are typeset somewhat differently:$x=y>zx:=yx\le y\ne zx\sim y\simeq zx\equiv y\not\equiv zx\subset y\subseteq z$x=y>z x := y x ≤ y 6= z x∼y'z x ≡ y 6≡ z x⊂y⊆z (The last several examples show some of the many other relational symbols that plain TEX makes available via control sequences; see Appendix F.) 133 134 Chapter 16: Typing Math Formulas The two characters ‘,’ (comma) and ‘;’ (semicolon) are treated as punctuation marks in formulas; this means that TEX puts a little extra space after them, but not before them.$f(x,y;z)$f (x, y; z) It isn’t customary to put extra space after a ‘.’ (period) in math formulas, so TEX treats a period as an ordinary symbol. If you want the ‘:’ character to be treated as a punctuation mark instead of as a relation, just call it \colon:$f:A\to Bf\colon A\to B$f :A→B f: A → B If you want to use a comma as an ordinary symbol (e.g., when it appears in a large number), just put it in braces; TEX treats anything in braces as an ordinary symbol. For instance,$12,345x12{,}345x$Ä 12, 345x 12,345x (wrong) (right) x EXERCISE 16.12 What’s an easy way to get a raised dot in a decimal constant (e.g., ‘3·1416’)? So far we have considered letters, other ordinary symbols, binary operations, relations, and punctuation marks; hence we have covered almost every key on the typewriter. There are just a few more: The characters ‘(’ and ‘[’ are called “openings,” while ‘)’ and ‘]’ are called “closings”; these act pretty much like ordinary symbols, but they help TEX to decide when a binary operation is not really being used in a binary way. Then there is the character ’, which we know is used as an abbreviation for \prime superscripts. Finally, we know that plain TEX reserves the other ten characters: \$ % # & ~ { } _ ^ These are not usable for symbols in math mode unless their \catcode values are changed (see Chapter 7). Although { and } specify grouping, the control sequences ‘\{’ and ‘\}’ can be used to get ‘{’ as an opening and ‘}’ as a closing. Ä Ä All of these math mode interpretations are easily changeable, since each char-

acter has a \mathcode, as explained in Chapter 17; none of the conventions are permanently built into TEX. However, most of them are so standard that it is usually unwise to make many changes, except perhaps in the interpretations of ‘, ", and @.

The special characters ^ and _ that designate superscripts and subscripts should not be used except in formulas. Similarly, the names of math symbols like \alpha and \approx, and the control sequences for math operations like \overline, must not invade ordinary text. TEX uses these facts to detect missing dollar signs in your input, before such mistakes cause too much trouble. For example, suppose you were to type The smallest $n such that$2^n>1000$is~10. Chapter 16: Typing Math Formulas TEX doesn’t know that you forgot a ‘$’ after the first ‘n’, because it doesn’t understand English; so it finds a “formula” between the first two $signs: The smallest nsuchthat after which it thinks that ‘2’ is part of the text. But then the ^ reveals an inconsistency; TEX will automatically insert a$ before the ^, and you will get an error message. In this way the computer has gotten back into synch, and the rest of the document can be typeset as if nothing had happened. Ä

Conversely, a blank line or \par is not permitted in math mode. This gives TEX another way to recover from a missing $; such errors will be confined to the paragraph in which they occur. Ä If for some reason you cannot use ^ and _ for superscripts and subscripts, because you have an unusual keyboard or because you need ^ for French accents or something, plain TEX lets you type \sp and \sb instead. For example, ‘$x\sp2$’ is another way to get ‘x2 ’. On the other hand, some people are lucky enough to have keyboards that contain additional symbols besides those of standard ASCII. When such symbols are available, TEX can be set up to make math typing a bit more pleasant. For example, at the author’s installation there are keys labeled ↑ and ↓ that produce visible symbols (these make superscripts and subscripts look much nicer on the screen); there are keys for the relations ≤, ≥, and ≠ (these save time); and there are about two dozen more keys that occasionally come in handy. (See Appendix C.) Ä Mathematicians are fond of using accents over letters, because this is often an effective way to indicate relationships between mathematical objects, and because it greatly extends the number of available symbols without increasing the number of necessary fonts. Chapter 9 discusses the use of accents in ordinary text, but mathematical accents are somewhat different, because spacing is not the same; TEX uses special conventions for accents in formulas, so that the two sorts of accents will not be confused with each other. The following math accents are provided by plain TEX:$\hat a\check a\tilde a\acute a\grave a\dot a\ddot a\breve a\bar a\vec a$a ˆ a ˇ a ˜ a ´ a  a˙ a ¨ a ˘ a ¯ ~a The first nine of these are called \^, \v, \~, \’, \‘, \., \", \u, and \=, respectively, when they appear in text; \vec is an accent that appears only in formulas. TEX will complain if you try to use \^ or \v, etc., in formulas, or if you try to use \hat or \check, etc., in ordinary text. 135 136 Chapter 16: Typing Math Formulas Ä It’s usually a good idea to define special control sequences for accented letters that you need frequently. For example, you can put \def\Ahat{{\hat A}} \def\chat{{\hat c}} \def\scheck{{\check s}} \def\xtilde{{\tilde x}} \def\zbar{{\bar z}} ˆ cˆ, sˇ, x at the beginning of a manuscript that uses the symbols A, ˜, and z¯ more than, say, five times. This saves you a lot of keystrokes, and it makes the manuscript easier to read. Chapter 20 explains how to define control sequences. Ä When the letters i and j are accented in math formulas, dotless symbols ı and  should be used under the accents. These symbols are called \imath and \jmath in plain TEX. Thus, for example, a paper that uses ‘ˆı’ and ‘ˆ ’ ought to begin with the following definitions: \def\ihat{{\hat\imath}} \def\jhat{{\hat\jmath}} ˆ You can put accents on top of accents, making symbols like Aˆ that might cause a mathematician to squeal with ecstasy. However, it takes a bit of finesse to get the upper accent into a position that looks right, because the designer of a font for mathematics usually tells TEX to position math accents in special ways for special letters. Plain TEX provides a control sequence called \skew that makes it fairly easy to shift superaccents into their proper place. For example, ‘\skew6\hat\Ahat’ was used to produce the symbol above. The number ‘6’ in this example was chosen by trial and error; ‘5’ seems to put the upper accent a bit too far left, while ‘7’ makes it a bit too far right, at least in the author’s opinion. The idea is to fiddle with the amount of skew until you find what pleases you best. Ä Ä It’s possible, in fact, to put math accents on any subformula, not just on single characters or accented characters. But there’s usually not much point in doing so, because TEX just centers the accent over the whole subformula. For example, ‘$\hat{I+M}$’ yields ‘I +ˆ M ’. In particular, a \bar accent always stays the same size; it’s not like \overline, which grows with the formula under it. Some people prefer the longer line from \overline even when it applies to only a single letter; for example, ‘$\bar z+\overline z$’ produces ‘¯ z + z’, and you can take your pick when you define \zbar. However, plain TEX does provide two accents that grow; they are called \widehat and \widetilde:$\widehat x,\widetilde x\widehat{xy},\widetilde{xy}\widehat{xyz},\widetilde{xyz}$x b, x e x cy, x fy xd yz, xg yz The third example here shows the maximum size available. x EXERCISE 16.13 This has been another long chapter; but cheer up, you have learned a lot! Prove 2 it by explaining what to type in order to get the formulas e−x , D ∼ pα M + l, Chapter 16: Typing Math Formulas −1 and gˆ ∈ (H π1 )0 . (In the last example, assume that a control sequence \ghat has already been defined, so that \ghat produces the accented letter gˆ.) Producing Greek letters is as easy as π. You just type ... as easy as$\pi$. — LESLIE LAMPORT, The LaTEX Document Preparation System (1983) TEX has no regard for the glories of the Greek tongue— as far as it is concerned, Greek letters are just additional weird symbols, and they are allowed only in math mode. In a pinch you can get the output τ ²χ by typing$\tau\epsilon\chi$, but if you’re actually setting Greek text, you will be using a different version of TEX, designed for a keyboard with Greek letters on it, and you shouldn’t even be reading this manual, which is undoubtedly all English to you. — MICHAEL SPIVAK, The Joy of TEX (1982) 137 (page 138) 17 More about Math Chapter 17: More about Math Another thing mathematicians like to do is make fractions—and they like to build symbols up on top of each other in a variety of different ways: ¶ µ 3 X n+1 n+1 1 Zn2 . and and and 3 2 3 n=1 You can get these four formulas as displayed equations by typing ‘$$1\over2$$’ and ‘$$n+1\over3$$’ and ‘$$n+1\choose3$$’ and ‘$$\sum_{n=1}^3 Z_n^2$$’; we shall study the simple rules for such constructions in this chapter. First let’s look at fractions, which use the ‘\over’ notation. The control sequence \over applies to everything in the formula unless you use braces to enclose it in a specific subformula; in the latter case, \over applies to everything in that subformula. Input Output $$x+y^2\over k+1$$ x + y2 k+1 $${x+y^2\over k}+1$$ $$x+{y^2\over k}+1$$ $$x+{y^2\over k+1}$$ $$x+y^{2\over k+1}$$ x + y2 +1 k y2 x+ +1 k y2 x+ k+1 2 x + y k+1 You aren’t allowed to use \over twice in the same subformula; instead of typing something like ‘a \over b \over 2’, you must specify what goes over what: $${a\over b}\over 2$$ $$a\over{b\over 2}$$ a b 2 a b 2 Unfortunately, both of these alternatives look pretty awful. Mathematicians tend to “overuse” \over when they first begin to typeset their own work on a system like TEX. A good typist or copy editor will convert fractions to a “slashed form,” whenever a built-up construction would be too small or too crowded. For example, the last two cases should be treated as follows: a/b $$a/b \over 2$$ 2 a $$a \over b/2$$ b/2 Conversion to slashed form takes a little bit of mathematical knowhow, since parentheses sometimes need to be inserted in order to preserve the meaning of 139 140 Chapter 17: More about Math the formula. Besides substituting ‘/’ for ‘\over’, the two parts of the fraction should be put in parentheses unless they are single symbols; for example, ab bea+1 comes simply a/b, but a+1 b becomes (a + 1)/b, and b+1 becomes (a + 1)/(b + 1). Furthermore, the entire fraction should generally be enclosed in parentheses if it appears next to something else; for example, ab x becomes (a/b)x. If you are a typist without mathematical training, it’s best to ask the author of the manuscript for help, in doubtful cases; you might also tactfully suggest that unsightly fractions be avoided altogether in future manuscripts. x EXERCISE 17.1 2 What’s a better way to render the formula x + y k+1 ? x EXERCISE 17.2 Convert ‘ a+1 b+1 x’ to slashed form. x EXERCISE 17.3 What surprise did B. L. User get when he typed ‘$$x = (y^2\over k+1)$$’ ? x EXERCISE 17.4 How can you make ‘7 12 c/’ ? (Assume that the control sequence \cents yields ‘/c’.) The examples above show that letters and other symbols sometimes get smaller when they appear in fractions, just as they get smaller when they are used as exponents. It’s about time that we studied TEX’s method for choosing the sizes of things. TEX actually has eight different styles in which it can treat formulas, namely display style text style script style scriptscript style (for (for (for (for formulas displayed on lines by themselves) formulas embedded in the text) formulas used as superscripts or subscripts) second-order superscripts or subscripts) and four other “cramped” styles that are almost the same except that exponents aren’t raised quite so much. For brevity we shall refer to the eight styles as D, D0 , T, T 0 , S, S 0 , SS , SS 0 , where D is display style, D 0 is cramped display style, T is text style, etc. TEX also uses three different sizes of type for mathematics; they are called text size, script size, and scriptscript size. The normal way to typeset a formula with TEX is to enclose it in dollar signs$ . . . $; this yields the formula in text style (style T ). Or you can enclose it in double dollar signs $$. . .$$; this displays the formula in display style (style D). The subformulas of a formula might, of course, be in different styles. Once you know the style, you can determine the size of type that TEX will use: If a letter is in style D, D0 , T, T 0 S, S 0 SS , SS 0 then it will be set in text size (like this) script size (like this) scriptscript size (like this) Chapter 17: More about Math There is no “SSS ” style or “scriptscriptscript” size; such tiny symbols would be even less readable than the scriptscript ones. Therefore TEX stays with scriptscript size as the minimum: In a formula of style D, T D0 , T 0 S, SS S 0 , SS 0 the superscript style is S S0 SS SS 0 and the subscript style is S0 S0 SS 0 SS 0 For example, if x^{a_b} is to be typeset in style D, then a_b will be set in style S, and b in style SS 0 ; the result is ‘xab ’. So far we haven’t seen any difference between styles D and T . Actually there is a slight difference in the positioning of exponents, although script size is used in each case: You get x2 in D style and x2 in T style and x2 in D0 or T 0 style—do you see the difference? But there is a big distinction between D style and T style when it comes to fractions: In a formula α\over β of style D D0 T T0 S, SS S 0 , SS 0 the style of the numerator α is T T0 S S0 SS SS 0 and the style of the denominator β is T0 T0 S0 S0 SS 0 SS 0 Thus if you type ‘$1\over2$’ (in a text) you get 12 , namely style S over style S 0 ; but if you type ‘$$1\over2$$’ you get 1 2 (a displayed formula), which is style T over style T 0 . Ä While we’re at it, we might as well finish the style rules: \underline does not change the style. Math accents, and the operations \sqrt and \overline, change uncramped styles to their cramped counterparts; for example, D changes to D 0 , but D0 stays as it was. Ä x EXERCISE 17.5 State the style and size of each part of the formula formula itself is in style D. p 0 pe2 , assuming that the Suppose you don’t like the style that TEX selects by its automatic style rules. Then you can specify the style you want by typing \displaystyle or \textstyle or \scriptstyle or \scriptscriptstyle; the style that you select will apply until the end of the formula or subformula, or until you select 141 142 Chapter 17: More about Math another style. For example, ‘$$n+\scriptstyle n+\scriptscriptstyle n.$$’ produces the display n +n+n. This is a rather silly example, but it does show that the plus signs get smaller too, as the style changes. TEX puts no space around + signs in script styles. Here’s a more useful example of style changes: Sometimes you need to typeset a “continued fraction” made up of many other fractions, all of which are supposed to be in display style: 1 a0 + 1 a1 + 1 a2 + 1 a4 a3 + In order to get this effect, the idea is to type $$a_0+{1\over\displaystyle a_1+ {\strut 1\over\displaystyle a_2+ {\strut 1\over\displaystyle a_3+ {\strut 1\over a_4}}}}$$ (The control sequence \strut has been used to make the denominators taller; this is a refinement that will be discussed in Chapter 18. Our concern now is with the style commands.) Without the appearances of \strut and \displaystyle in this formula, the result would be completely different: a0 + 1 a1 + 1 a2 + 1 a3 + 1 a4 Ä These examples show that the numerator and denominator of a fraction are generally centered with respect to each other. If you prefer to have the numerator or denominator appear flush left, put ‘\hfill’ after it; or if you prefer flush right, put ‘\hfill’ at the left. For example, if the first three appearances of ‘1\over’ in the previous example are replaced by ‘1\hfill\over’, you get the display a0 + 1 a1 + 1 a2 + 1 a3 + 1 a4 (a format for continued fractions that many authors prefer). This works because \hfill stretches at a faster rate than the glue that is actually used internally by TEX when it centers the numerators and denominators. Chapter 17: More about Math TEX has another operation ‘\atop’, which is like \over except that it leaves out the fraction line: x $$x\atop y+2$$ y+2 The plain TEX format in Appendix B also defines ‘\choose’, which is like \atop but it encloses the result in parentheses: µ ¶ n $$n\choose k$$ k It is called \choose because it’s a common notation for the so-called binomial coefficient that tells how many ways there are to choose k things out of n things. You can’t mix \over and \atop and \choose with each other. For example, ‘$$n \choose k \over 2$$’ is illegal; you must use grouping, to get either ‘$${n\choose k}\over2$$’ or ‘$$n\choose{k\over2}$$’, i.e., ¡n ¢ µ ¶ n k or k . 2 2 The latter formula, incidentally, would look better as ‘$$n\choose k/2$$’ or ‘$$n\choose{1\over2}k$$’, yielding ¶ µ ¶ µ n n or . 1 k/2 2k x EXERCISE 17.6 ¡ ¢ n As alternatives to µ ¶ 1 n 2 k k , discuss how you could obtain the two displays µ ¶ n k . and 2 2 x EXERCISE 17.7 Explain how to specify the displayed formula µ ¶ p 2 p−2 1 1 x y − . 2 1 − x 1 − x2 Ä TEX has a generalized version of \over and \atop in which you specify the exact thickness of the line rule by typing ‘\abovehdimeni’. For example, $$\displaystyle{a\over b}\above1pt\displaystyle{c\over d}$$ will produce a compound fraction with a heavier (1 pt thick) rule as its main bar: a b . c d This sort of thing occurs primarily in textbooks on elementary mathematics. 143 144 Chapter 17: More about Math P Mathematicians often use the sign to stand for “summation” and the sign to stand for “integration.” If you’re a typist P but not a mathematician, R all you need to remember is that \sum stands for and \int for ; these abbreviations appear in Appendix symbols, R F together with all theSotherQ H in case P N you forget. Symbols like and (and a few others like and and and , all listed in Appendix F) are called large operators, and you type them just as you type ordinary symbols or letters. The difference is that TEX will choose a larger large operator in display style than it will in text style. For example, P$\sum x_n$yields xn (T style) X $$\sum x_n$$ yields xn (D style). R A displayed \sum usually occurs with “limits,” i.e., with subformulas that are to appear above and below it. You type limits just as if they were superscripts and subscripts; for example, if you want m X n=1 you type either ‘$$\sum_{n=1}^m$$’ or ‘$$\sum^m_{n=1}$$’. According P to the m normal conventions of mathematical typesetting, TEX will change this to ‘ n=1 ’ (i.e., without limits) if it occurs in text style rather than in display style. Integrations are slightly different from summations, in that the superscripts and subscripts are not set as limits even in display style: R +∞$\int_{-\infty}^{+\infty}$yields (T style) −∞ Z +∞ (D style). $$\int_{-\infty}^{+\infty}$$ yields −∞ R Ä Some printers prefer to set limits above and below signs; this takes more space on the page, but it gives a better appearance if the subformulas are complex, because it keeps them out of the way of the rest of the formula. Similarly, limits are occasionally desirable Pin text style or script style; but some printers prefer not to set limits on displayed signs. You can change TEX’s convention by simply typing ‘\limits’ or ‘\nolimits’ immediately after the large operator. For example, π $$\int\limits_0^{\pi\over2}$$ yields Z2 0 $$\sum\nolimits_{n=1}^m$$ yields Xm n=1 Ä Ä If you say ‘\nolimits\limits’ (presumably because some macro like \int specifies \nolimits, but you do want them), the last word takes precedence. There’s also a command ‘\displaylimits’ that can be used to restore TEX’s normal conventions; i.e., the limits will be displayed only in styles D and D 0 . Chapter 17: More about Math Ä Sometimes you need to put two or more rows of limits under a large operator; you can do this with ‘\atop’. For example, if you want the displayed formula X P (i, j) 0≤i≤m 0 x) = exp(−x/µ) max log2 Pn 1≤n≤m sin x =1 x The last two formulas, which are displays, show that some of the specialP control sequences are treated by TEX as “large operators” with limits just like : The subscript on \max is not treated like the subscript on \log. Subscripts and superscripts will become limits when they are attached to \det, \gcd, \inf, \lim, \liminf, \limsup, \max, \min, \Pr, and \sup, in display style. $$\lim_{x\to0}{\sin x\over x}=1$$ lim x→0 Chapter 18: Fine Points of Mathematics Typing x EXERCISE 18.2 Express the following display in plain TEX language, using ‘\nu’ for ‘ν’: ∞ X ¡ ¢ 1 − cos2m (ν!n π/n) . p1 (n) = lim m→∞ ν=0 Ä If you need roman type for some mathematical function or operator that isn’t included in plain TEX’s list of 32, it is easy to define a new control sequence by mimicking the definitions in Appendix B. Or, if you need roman type just for a “one shot” use, it is even easier to get what you want by switching to \rm type, as follows: p Var(X) xmax − xmin LL(k) ⇒ LR(k) exp(x + constant) x3 + lower order terms$\sqrt{{\rm Var}(X)}x_{\rm max}-x_{\rm min}{\rm LL}(k)\Rightarrow{\rm LR}(k)\exp(x+{\rm constant})x^3+{\rm lower\ order\ terms}$Notice the uses of ‘\Ã’ in the last case; without them, the result would have been ‘x3 + lowerorderterms’, because ordinary blank spaces are ignored in math mode. Ä You can also use \hbox instead of \rm to get roman letters into formulas. For example, four of the last five formulas can be generated by p Var(X) LL(k) ⇒ LR(k) exp(x + constant) x3 + lower order terms$\sqrt{\hbox{Var}(X)}\hbox{LL}(k)\Rightarrow\hbox{LR}(k)\exp(x+\hbox{constant})x^3+\hbox{lower order terms}$In this case ‘\Ã’ isn’t necessary, because the material in an \hbox is processed in horizontal mode, when spaces are significant. But such uses of \hbox have two disadvantages: (1) The contents of the box will be typeset in the same size, whether or not the box occurs as a subscript; for example, ‘$x_{\hbox{max}}$’ yields ‘x max ’. (2) The font that’s used inside \hbox will be the “current font,” so it might not be roman. For example, if you are typesetting the statement of some theorem that is in slanted type, and ifp that theorem refers to ‘$\sqrt{\hbox{Var}(X)}$’, you will get the unintended result ‘ Var(X)’. In order to make sure that an \hbox uses roman type, you need to specify \rm, e.g., ‘$\sqrt{\hbox{\rm Var}(X)}$’; and then the \hbox serves no purpose. We will see later, however, that \hbox can be very useful in displayed formulas. Ä Äx EXERCISE 18.3 When the displayed formula ‘$$\lim_{n\to\infty}x_n {\rm\ exists} \iff \limsup_{n\to\infty}x_n = \liminf_{n\to\infty}x_n.$$’ is typeset with the standard macros of plain TEX, you get lim xn exists ⇐⇒ lim sup xn = lim inf xn . n→∞ n→∞ n→∞ But some people prefer a different notation: Explain how you could change the definitions of \limsup and \liminf so that the display would be lim xn exists ⇐⇒ lim xn = lim xn . n→∞ n→∞ n→∞ 163 164 Chapter 18: Fine Points of Mathematics Typing Ä The word ‘mod’ is also generally set in roman type, when it occurs in formulas; but this word needs more care, because it is used in two different ways that require two different treatments. Plain TEX provides two different control sequences, \bmod and \pmod, for the two cases: \bmod is to be used when ‘mod’ is a binary operation (i.e., when it occurs between two quantities, like a plus sign usually does), and \pmod is to be used when ‘mod’ occurs parenthetically at the end of a formula. For example, gcd(m, n) = gcd(n, m mod n) x ≡ y + 1 (mod m2 )$\gcd(m,n)=\gcd(n,m\bmod n)x\equiv y+1\pmod{m^2}$The ‘b’ in ‘\bmod’ stands for “binary”; the ‘p’ in ‘\pmod’ stands for “parenthesized.” Notice that \pmod inserts its own parentheses; the quantity that appears after ‘mod’ in the parentheses should be enclosed in braces, if it isn’t a single symbol. Ä x EXERCISE 18.4 Ä x EXERCISE 18.5 Ä What did poor B. L. User get when he typed ‘$x\equiv0 (\pmod y^n)$’ ? Explain how to produce µ ¶ n k µ bn/pc bk/pc ¶µ n mod p k mod p (mod p). The same mechanism that works for roman type in formulas can be used to get other styles of type as well. For example, \bf yields boldface:$\bf a+b=\Phi_m$a + b = Φm Notice that whole formula didn’t become emboldened in this example; the ‘+’ and ‘=’ stayed the same. Plain TEX sets things up so that commands like \rm and \bf will affect only the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, the uppercase Greek letters \Gamma to \Omega, and math accents like \hat and \tilde. Incidentally, no braces were used in this example, because$’s have the effect of grouping; \bf changes the current font, but the change is local, so it does not affect the font that was current outside the formula.

Ä Ä The bold fonts available in plain TEX are “bold roman,” rather than “bold

italic,” because the latter are rarely needed. However, TEX could readily be set up to make use of bold math italics, if desired (see Exercise 17.20). A more extensive set of math fonts would also include script, Fraktur, and “blackboard bold” styles; plain TEX doesn’t have these, but other formats like AMS-TEX do.

Ä

Besides \rm and \bf, you can say \cal in formulas to get uppercase letters in a “calligraphic” style. For example, ‘$\cal A$’ produces ‘A’ and ‘$\cal Z$’ produces ‘Z’. But beware: This works only with the letters A to Z; you’ll get weird results if you apply \cal to lowercase or Greek letters.

Ä

There’s also \mit, which stands for “math italic.” This affects uppercase Greek, so that you get (Γ, ∆, Θ, Λ, Ξ, Π, Σ, Υ, Φ, Ψ, Ω) instead of (Γ, . . . , Ω). When \mit is in effect, the ordinary letters A to Z and a to z are not changed; they are set in italics as usual, because they ordinarily come from the math italic font. Conversely, uppercase Greek letters and math accents are unaffected by \rm, because they ordinarily come from the roman font. Math accents should not be used when the \mit family has been selected, because the math italic font contains no accents.

Chapter 18: Fine Points of Mathematics Typing

Ä

x EXERCISE 18.6

Ä

x EXERCISE 18.7

Type the formula x ¯T Mx = 0 ⇐⇒ x = 0, using as few keystrokes as possible. (The first ‘0’ is roman, the second is bold. The superscript ‘T’ is roman.) Figure out how to typeset ‘S ⊆ Σ ⇐⇒ S ∈ S’.

Ä

Plain TEX also allows you to type \it, \sl, or \tt, if you want text italic, slanted, or typewriter letters to occur in a math formula. However, these fonts are available only in text size, so you should not try to use them in subscripts.

Ä

If you’re paying attention, you probably wonder why both \mit and \it are provided; the answer is that \mit is “math italic” (which is normally best for formulas), and \it is “text italic” (which is normally best for running text). $This\ is\ math\ italic.$ {\it This is text italic.}

T his is math italic. This is text italic.

The math italic letters are a little wider, and the spacing is different; this works better in most formulas, but it fails spectacularly when you try to type certain italic words like ‘dif f erent’ using math mode (‘$different$’). A wide ‘f ’ is usually desirable in formulas, but it is undesirable in text. Therefore wise typists use \it in a math formula that is supposed to contain an actual italic word. Such cases almost never occur in classical mathematics, but they are common when computer programs are being typeset, since programmers often use multi-letter “identifiers”: $\it last:=first$ $\it x\_coord(point\_2)$

last := first x coord (point 2 )

The first of these examples shows that TEX recognizes the ligature ‘fi ’ when text italic occurs in a math formula; the other example illustrates the use of short underlines to break up identifier names. When the author typeset this manual, he used ‘$\it SS$’ to refer to style SS , since ‘$SS$’ makes the S’s too far apart: SS.

Ä

x EXERCISE 18.8

What plain TEX commands will produce the following display?

available +

n X i=1

Ä Äx EXERCISE 18.9

¡ ¢ max full (i), reserved (i) = capacity.

How would you go about typesetting the following computer program, using the macros of plain TEX? for j := 2 step 1 until n do begin accum := A[j]; k := j − 1; A[0] := accum; while A[k] > accum do begin A[k + 1] := A[k]; k := k − 1; end; A[k + 1] := accum; end.

165

166

Chapter 18: Fine Points of Mathematics Typing

3. Spacing between formulas. Displays often contain more than one formula; for example, an equation is frequently accompanied by a side condition: Fn = Fn−1 + Fn−2 ,

n ≥ 2.

In such cases you need to tell TEX how much space to put after the comma, because TEX’s normal spacing conventions would bunch things together; without special precautions you would get Fn = Fn−1 + Fn−2 , n ≥ 2. The traditional hot-metal technology for printing has led to some ingrained standards for situations like this, based on what printers call a “quad” of space. Since these standards seem to work well in practice, TEX makes it easy for you to continue the tradition: When you type ‘\quad’ in plain TEX format, you get a printer’s quad of space in the horizontal direction. Similarly, ‘\qquad’ gives you a double quad (twice as much); this is the normal spacing for situations like the Fn example above. Thus, the recommended procedure is to type $$F_n = F_{n-1} + F_{n-2}, \qquad n \ge 2.$$

It is perhaps worth reiterating that TEX ignores all the spaces in math mode (except, of course, the space after ‘\qquad’, which is needed to distinguish between ‘\qquad n’ and ‘\qquadn’); so the same result would be obtained if you were to leave out all but one space: $$F_n=F_{n-1}+F_{n-2},\qquad n\ge2.$$ Whenever you want spacing that differs from the normal conventions, you must specify it explicitly by using control sequences such as \quad and \qquad. Ä

A quad used to be a square piece of blank type, 1 em wide and 1 em tall— approximately the size of a capital M, as explained in Chapter 10. This tradition has not been fully retained: The control sequence \quad in plain TEX is simply an abbreviation for ‘\hskip 1em\relax’, so TEX’s quad has width but no height.

Ä

You can use \quad in text as well as in formulas; for example, Chapter 14 illustrates how \quad applies to poetry. When \quad appears in a formula it stands for one em in the current text font, independent of the current math size or style or family. Thus, for example, \quad is just as wide in a subscript as it is on the main line of a formula.

Sometimes a careless author will put two formulas next to each other in the text of a paragraph. For example, you might find a sentence like this: The Fibonacci numbers satisfy Fn = Fn−1 + Fn−2 , n ≥ 2. Everybody who teaches proper mathematical style is agreed that formulas ought to be separated by words, not just by commas; the author of that sentence should at least have said ‘for n ≥ 2’, not simply ‘n ≥ 2’. But alas, such lapses are commonplace, and many prominent mathematicians are hopelessly addicted

Chapter 18: Fine Points of Mathematics Typing

to clusters of formulas. If we are not allowed to change their writing style, we can at least insert extra space where they neglected to insert an appropriate word. An additional interword space generally works well in such cases; for example, the sentence above was typeset thus: ... $F_n=F_{n-1}+F_{n-2}$, \ $n\ge2$.}$$The ‘\Ã’ here gives a visual separation that partly compensates for the bad style. x EXERCISE 18.10 Put the following paragraph into TEX form, treating punctuation and spacing carefully; also insert ties to prevent bad line breaks. Let H be a Hilbert space, C a closed bounded convex subset of H, T a nonexpansive self map of C. Suppose that as n → ∞, an,k → 0 P∞ for each k, and γn = k=0 (an,k+1 −an,k )+ → 0. Then for each x in C, P∞ An x = k=0 an,k T k x converges weakly to a fixed point of T . 4. Spacing within formulas. Chapter 16 says that TEX does automatic spacing of math formulas so that they look right, and this is almost true. But occasionally you must give TEX some help. The number of possible math formulas is vast, and TEX’s spacing rules are rather simple, so it is natural that exceptions should arise. Of course, it is desirable to have fine units of spacing for this purpose, instead of the big chunks that arise from \Ã, \quad and \qquad. The basic elements of space that TEX puts into formulas are called thin spaces, medium spaces, and thick spaces. In order to get a feeling for these units, let’s take a look at the Fn example again: Thick spaces occur just before and after the = sign, and also before and after the ≥ ; medium spaces occur just before and after the + sign. Thin spaces are slightly smaller, but noticeable; it’s a thin space that makes the difference between ‘loglog’ and ‘log log’. The normal space between words of a paragraph is approximately equal to two thin spaces. TEX inserts thin spaces, medium spaces, and thick spaces into formulas automatically, but you can add your own spacing whenever you want to, by using the control sequences \, thin space (normally 1/6 of a quad); \> medium space (normally 2/9 of a quad); \; thick space (normally 5/18 of a quad); \! negative thin space (normally −1/6 of a quad). In most cases you can rely on TEX’s spacing while you are typing a manuscript, and you’ll want to insert or delete space with these four control sequences only in rare circumstances after you see what comes out. Ä Ä We observed a minute ago that \quad spacing does not change with the style of formula, nor does it depend on the math font families that are being used. But thin spaces, medium spaces, and thick spaces do get bigger and smaller as the size of type gets bigger and smaller; this is because they are defined in terms of hmugluei, 167 168 Chapter 18: Fine Points of Mathematics Typing a special brand of glue intended for math spacing. You specify hmugluei just as if it were ordinary glue, except that the units are given in terms of ‘mu’ (math units) instead of pt or cm or something else. For example, Appendix B contains the definitions \thinmuskip = 3mu \medmuskip = 4mu plus 2mu minus 4mu \thickmuskip = 5mu plus 5mu and this defines the thin, medium, and thick spaces that TEX inserts into formulas. According to these specifications, thin spaces in plain TEX do not stretch or shrink; medium spaces can stretch a little, and they can shrink to zero; thick spaces can stretch a lot, but they never shrink. Ä Ä There are 18 mu to an em, where the em is taken from family 2 (the math symbols family). In other words, \textfont 2 defines the em value for mu in display and text styles; \scriptfont 2 defines the em for script size material; and \scriptscriptfont 2 defines it for scriptscript size. Ä Ä You can insert math glue into any formula just by giving the command ‘\mskiphmugluei’. For example, ‘\mskip 9mu plus 2mu’ inserts one half em of space, in the current size, together with some stretchability. Appendix B defines ‘\,’ to be an abbreviation for ‘\mskip\thinmuskip’. Similarly, you can use the command ‘\mkern’ when there is no stretching or shrinking; ‘\mkern18mu’ gives one em of horizontal space in the current size. TEX insists that \mskip and \mkern be used only with mu; conversely, \hskip and \kern (which are also allowed in formulas) must never give units in mu. Formulas involving calculus look best when an extra thin space appears before dx or dy or d whatever; but TEX doesn’t do this automatically. Therefore a well-trained typist will remember to insert ‘\,’ in examples like the following: Input \int_0^\infty f(x)\,dx y\,dx-x\,dy dx\,dy=r\,dr\,d\theta x\,dy/dx Output R∞ f (x) dx 0 y dx − x dy dx dy = r dr dθ x dy/dx Notice that no ‘\,’ was desirable after the ‘/’ in the last example. Similarly, there’s no need for ‘\,’ in cases like Z x dt$$\int_1^x{dt\over t}$$t 1 since the dt appears all by itself in the numerator of a fraction; this detaches it visually from the rest of the formula. x EXERCISE 18.11 Explain how to handle the display Z ∞ t − ib iat e dt = eab E1 (ab), 2 + b2 t 0 a, b > 0. Chapter 18: Fine Points of Mathematics Typing Ä When physical units appear in a formula, they should be set in roman type and separated from the preceding material by a thin space: 55\rm\,mi/hr g=9.8\rm\,m/sec^2 \rm1\,ml=1.000028\,cc Ä 55 mi/hr g = 9.8 m/sec2 1 ml = 1.000028 cc x EXERCISE 18.12 Typeset the following display, assuming that ‘\hbar’ generates ‘¯ h’: h ¯ = 1.0545 × 10−27 erg sec. Ä Thin spaces should also be inserted after exclamation points (which stand for the “factorial” operation in a formula), if the next character is a letter or a number or an opening delimiter: (2n)!/\bigl(n!\,(n+1)!\bigr) (2n)!/(n! (n + 1)!)$${52!\over13!\,13!\,26!}$$52! 13! 13! 26! Besides these cases, you will occasionally encounter formulas in which the symbols are bunched up too tightly, or where too much white space appears, because of certain unlucky combinations of shapes. It’s usually impossible to anticipate optical glitches like this until you see the first proofs of what you have typed; then you get to use your judgment about how to add finishing touches that provide extra beauty, clarity, and finesse. A tastefully applied ‘\,’ or ‘\!’ will open things up or close things together so that the reader won’t be distracted from the mathematical significance of the formula. Square root signs and multiple integrals are often candidates for such fine tuning. Here are some examples of situations to look out for: √ 2x \sqrt2\,x √ \sqrt{\,\log x} log x ¡ √ ¢ O\bigl(1/\sqrt n\,\bigr) O 1/ n [\,0,1) [ 0, 1) \log n\,(\log\log n)^2 log n (log log n)2 x^2\!/2 x2/2 n/\!\log n n/log n \Gamma_{\!2}+\Delta^{\!2} Γ2 + ∆2 R_i{}^j{}_{\!kl} Ri jkl R xR y dF (u, v) \int_0^x\!\int_0^y dF(u,v) 0 0 ZZ dx dy$$\int\!\!\!\int_D dx\,dy$$D In each of these formulas the omission of \, or \! would lead to somewhat less satisfactory results. 169 170 Chapter 18: Fine Points of Mathematics Typing Ä Ä Most of these examples where thin-space corrections are desirable arise because of chance coincidences. For example, the superscript in x^2/2 leaves a hole before the slash (x2 /2); a negative thin space helps to fill that hole. The positive thin space in \sqrt{\,\log x} compensates for the fact that ‘log x’ begins with a tall, unslanted letter; and so on. But two of the examples involve corrections that were necessary because TEX doesn’t really know a great deal about mathematics: (1) In the formula \log n(\log\log n)^2, TEX inserts no thin space before the left parenthesis, because there are similar formulas like \log n(x) where no such space is desired. (2) In the formula n/\log n, TEX automatically inserts an unwanted thin space before \log, since the slash is treated as an ordinary symbol, and since a thin space is usually desirable between an ordinary symbol and an operator like \log. Ä Ä In fact, TEX’s rules for spacing in formulas are fairly simple. A formula is con- verted to a math list as described at the end of Chapter 17, and the math list consists chiefly of “atoms” of eight basic types: Ord (ordinary), Op (large operator), Bin (binary operation), Rel (relation), Open (opening), Close (closing), Punct (punctuation), and Inner (a delimited subformula). Other kinds of atoms, which arise from commands like \overline or \mathaccent or \vcenter, etc., are all treated as type Ord; fractions are treated as type Inner. The following table is used to determine the spacing between pairs of adjacent atoms: Right atom Left atom Ord Op Bin Rel Open Close Punct Inner Ord Op Bin Rel Open Close Punct Inner 0 1 (2) (3) 0 0 (1) (1) 1 1 (2) (3) 0 1 (1) 1 (2) * * * * (2) * (2) (3) (3) * 0 0 (3) (1) (3) 0 0 (2) (3) 0 0 (1) (1) 0 0 * 0 0 0 (1) 0 0 0 * 0 0 0 (1) (1) (1) (1) (2) (3) 0 (1) (1) (1) Here 0, 1, 2, and 3 stand for no space, thin space, medium space, and thick space, respectively; the table entry is parenthesized if the space is to be inserted only in display and text styles, not in script and scriptscript styles. For example, many of the entries in the Rel row and the Rel column are ‘(3)’; this means that thick spaces are normally inserted before and after relational symbols like ‘=’, but not in subscripts. Some of the entries in the table are ‘*’; such cases never arise, because Bin atoms must be preceded and followed by atoms compatible with the nature of binary operations. Appendix G contains precise details about how math lists are converted to horizontal lists; this conversion is done whenever TEX is about to leave math mode, and the inter-atomic spacing is inserted at that time. Ä Ä For example, the displayed formula specification$$x+y=\max\{x,y\}+\min\{x,y\}$$will be transformed into the sequence of atoms x + y = max { x , y } + min { x , y } Chapter 18: Fine Points of Mathematics Typing of respective types Ord, Bin, Ord, Rel, Op, Open, Ord, Punct, Ord, Close, Bin, Op, Open, Ord, Punct, Ord, and Close. Inserting spaces according to the table gives Ord \> Bin \> Ord \; Rel \; Op Open Ord Punct \, Ord Close \> Bin \> Op Open Ord Punct \, Ord Close and the resulting formula is x + y = max{x, y} + min{x, y} i.e., x + y = max{x, y} + min{x, y} . This example doesn’t involve subscripts or superscripts; but subscripts and superscripts merely get attached to atoms without changing the atomic type. Ä Äx EXERCISE 18.13 Use the table to determine what spacing TEX will insert between the atoms of the formula ‘f(x,y)5\,\} {x | x > 5} {x : x > 5} (Some authors prefer to use a colon instead of ‘|’, as in the second example here.) When the delimiters get larger, as in ª ©¡ ¢¯ x, f (x) ¯ x ∈ D Chapter 18: Fine Points of Mathematics Typing they should be called \bigl, \bigm, and \bigr; for example, the formula just given would be typed \bigl\{\,\bigl(x,f(x)\bigr)\bigm|x\in D\,\bigr\} and formulas that involve still larger delimiters would use \Big or \bigg or even \Bigg, as explained in Chapter 17. x EXERCISE 18.21 © ¯ ª How would you typeset the formula x3 ¯ h(x) ∈ {−1, 0, +1} ? Ä x EXERCISE 18.22 Sometimes the condition that defines a set is given as a fairly long English description, not as a formula; for example, consider ‘{ p | p and p + 2 are prime }’. An hbox would do the job: \{\,p\mid\hbox{p and p+2 are prime}\,\} but a long formula like this is troublesome in a paragraph, since an hbox cannot be broken between lines, and since the glue inside the \hbox does not vary with the interword glue in the line that contains it. Explain how the given formula could be typeset with line breaks allowed. [Hint: Go back and forth between math mode and horizontal mode.] Displayed formulas often involve another sort of brace, to indicate a choice between various alternatives, as in the construction ½ x, if x ≥ 0; |x| = −x, otherwise. You can typeset it with the control sequence \cases:$$|x|=\cases{x,&if $x\ge0$;\cr -x,&otherwise.\cr}Look closely at this example and notice that it uses the character &, which we said in Chapter 7 was reserved for special purposes. Here for the first time in this manual we have an example of why & is so special: Each of the cases has two parts, and the & separates those parts. To the left of the & is a math formula that is implicitly enclosed in ...; to the right of the & is ordinary text, which is not implicitly enclosed in .... For example, the ‘-x,’ in the second line will be typeset in math mode, but the ‘otherwise’ will be typeset in horizontal mode. Blank spaces after the & are ignored. There can be any number of cases, but there usually are at least two. Each case should be followed by \cr. Notice that the \cases construction typesets its own ‘{’; there is no corresponding ‘}’. ( x EXERCISE 18.23 1/3 Typeset the display f (x) = 2/3 0 if 0 ≤ x ≤ 1; if 3 ≤ x ≤ 4; elsewhere. 175 176 Chapter 18: Fine Points of Mathematics Typing Ä You can insert ‘\noalign{hvertical mode materiali}’ just after any \cr within \cases, as explained in Chapter 22, because \cases is an application of the general alignment constructions considered in that chapter. For example, the command ‘\noalign{\vskip2pt}’ can be used to put a little extra space between two of the cases. Ä Horizontal braces will be set over or under parts of a displayed formula if you use the control sequences \overbrace or \underbrace. Such constructions are considered to be large operators like \sum, so you can put limits above them or below them by specifying superscripts or subscripts, as in the following examples:\overbrace{x+\cdots+x}^{k\rm\;times}\underbrace{x+y+z}_{>\,0}.$$z k times }| { x + ··· + x x+y+z. | {z } >0 8. Matrices. Now comes the fun part. Mathematicians in many different disciplines like to construct rectangular arrays of formulas that have been arranged in rows and columns; such an array is called a matrix. Plain TEX provides a \matrix control sequence that makes it convenient to deal with the most common types of matrices. For example, suppose that you want to specify the display   x−λ 1 0 A= 0 x−λ 1 . 0 0 x−λ All you do is type$$A=\left(\matrix{x-\lambda&1&0\cr 0&x-\lambda&1\cr 0&0&x-\lambda\cr}\right).$$This is very much like the \cases construction we looked at earlier; each row of the matrix is followed by \cr, and ‘&’ signs are used between the individual entries of each row. Notice, however, that you are supposed to put your own \left and \right delimiters around the matrix; this makes \matrix different from \cases, which inserts a big ‘{’ automatically. The reason is that \cases always involves a left brace, but different delimiters are used in different matrix constructions. On the other hand, parentheses are used more often than other delimiters, so you can write \pmatrix if you want plain TEX to fill in the parentheses for you; the example above then reduces to Ä$$A=\pmatrix{x-\lambda&...&x-\lambda\cr}.$$   u x x EXERCISE 18.24   a b c , using \lgroup and \rgroup. v y     Typeset the display     d e f  w z Chapter 18: Fine Points of Mathematics Typing Ä The individual entries of a matrix are normally centered in columns. Each column is made as wide as necessary to accommodate the entries it contains, and there’s a quad of space between columns. If you want to put something flush right in its column, precede it by \hfill; if you want to put something flush left in its column, follow it by \hfill. Ä Each entry of a matrix is treated separately from the others, and it is typeset as a math formula in text style. Thus, for example, if you say \rm in one entry, it does not affect the others. Don’t try to say ‘{\rm x&y}’. Matrices often appear in the form of generic patterns that use ellipses (i.e., dots) to indicate rows or columns that are left out. You can typeset such matrices by putting the ellipses into rows and/or columns of their own. Plain TEX provides \vdots (vertical dots) and \ddots (diagonal dots) as companions to \ldots for constructions like this. For example, the generic matrix   a11 a12 . . . a1n  a21 a22 . . . a2n  A= .. ..  ..  ... . . .  am1 am2 ... amn is easily specified:$$A=\pmatrix{a_{11}&a_{12}&\ldots&a_{1n}\cr a_{21}&a_{22}&\ldots&a_{2n}\cr \vdots&\vdots&\ddots&\vdots\cr a_{m1}&a_{m2}&\ldots&a_{mn}\cr}$$  y1 x EXERCISE 18.25  ..  How can you get TEX to produce the column vector  .  ? yk Ä Sometimes a matrix is bordered at the top and left by formulas that give labels to the rows and columns. Plain TEX provides a special macro called \bordermatrix for this situation. For example, the display C C 1 M= I b C0 0  is obtained when you type I 0 1−b a C0  0 0  1−a$$M=\bordermatrix{&C&I&C’\cr C&1&0&0\cr I&b&1-b&0\cr

C’&0&a&1-a\cr}$$The first row gives the upper labels, which appear above the big left and right parentheses; the first column gives the left labels, which are typeset flush left, just before the matrix itself. The first column in the first row is normally blank. Notice that \bordermatrix inserts its own parentheses, like \pmatrix does. 177 178 Chapter 18: Fine Points of Mathematics Typing Ä It’s usually inadvisable to put matrices into the text of a paragraph, because they are so big that they ¡are¢ better displayed. But occasionally you may want to specify a small matrix like 10 11 , which you can typeset for example as b c ‘1\,1\choose0\,1’. Similarly, the small matrix ( al m ) can be typeset as n \bigl({a\atop l}{b\atop m}{c\atop n}\bigr) The \matrix macro does not produce small arrays of this sort. 9. Vertical spacing. If you want to tidy up an unusual formula, you know already how to move things farther apart or closer together, by using positive or negative thin spaces. But such spaces affect only the horizontal dimension; what if you want something to be moved higher or lower? That’s an advanced topic. Ä Appendix B provides a few macros that can be used to fool TEX into thinking that certain formulas are larger or smaller than they really are; such tricks can be used to move other parts of the formula up or down or left or right. For example, we have already discussed the use of \mathstrut in Chapter 16 and \strut in Chapter 17; these invisible boxes caused TEX to put square root signs and the denominators of continued fractions into different positions than usual. Ä If you say ‘\phantom{hsubformulai}’ in any formula, TEX will do all of its spacing as if you had said simply ‘{hsubformulai}’, but the subformula itself will be invisible. Thus, for example, ‘\phantom{0}2’ takes up just as much space as ‘02’ in the current style, but only the 2 will actually appear on the page. PIf you want to leave blank space for a new symbol that has exactly the same size as , but if you are forced to put that symbol in by hand for some reason, ‘\mathop{\phantom\sum}’ will leave exactly the right amount of blank space. (The ‘\mathop’ here makes this phantom behave like \sum, i.e., as a large operator.) Ä Even more useful than \phantom is \vphantom, which makes an invisible box whose height and depth are the same as those of the corresponding \phantom, but the width is zero. Thus, \vphantom makes a vertical strut that can increase a formula’s effective height or depth. Plain TEX defines \mathstrut to be an abbreviation for ‘\vphantom(’. There’s also \hphantom, which has the width of a \phantom, but its height and depth are zero. Ä Plain TEX also provides ‘\smash{hsubformulai}’, a macro that yields the same result as ‘{hsubformulai}’ but makes the height and depth zero. By using both \smash and \vphantom you can typeset any subformula and give it any desired nonnegative height and depth. For example, \mathop{\smash\limsup\vphantom\liminf} produces a large operator that says ‘lim sup’, but its height and depth are those of \liminf (i.e., the depth is zero). Ä Äx EXERCISE 18.26 If you want to underline some text, you could use a macro like \def\undertext#1{\underline{\hbox{#1}}} to do the job. But this doesn’t always work right. Discuss better alternatives. Chapter 18: Fine Points of Mathematics Typing Ä Ä You can also use \raise and \lower to adjust the vertical positions of boxes in formulas. For example, the formula ‘2^{\raise1pt\hbox{\scriptstyle n n}}’ will have its superscript n one point higher than usual (2 instead of 2n ). Note that it was necessary to say \scriptstyle in this example, since the contents of an \hbox will normally be in text style even when that hbox appears in a superscript, and since \raise can be used only in connection with a box. This method of positioning is not used extremely often, but it is sometimes helpful if the \root macro doesn’t put its argument in a suitable place. For example, \root\raisehdimeni\hbox{\scriptscriptstylehargumenti}\of... will move the argument up by a given amount. Ä Ä Instead of changing the sizes of subformulas, or using \raise, you can also control vertical spacing by changing the parameters that TEX uses when it is converting math lists to horizontal lists. These parameters are described in Appendix G; you need to be careful when changing them, because such changes are global (i.e., not local to groups). Here is an example of how such a change might be made: Suppose that you are designing a format for chemical typesetting, and that you expect to be setting a lot of formulas like ‘Fe+2 2 Cr2 O4 ’. You may not like the fact that the subscript in Fe+2 is lower than the subscript in Cr2 ; and you don’t want to force users 2 to type monstrosities like \rm Fe_2^{+2}Cr_2^{\vphantom{+2}}O_4^{\vphantom{+2}} just to get the formula Fe+2 2 Cr2 O4 with all subscripts at the same level. Well, all you need to do is set ‘\fontdimen16\tensy=2.7pt’ and ‘\fontdimen17\tensy=2.7pt’, assuming that \tensy is your main symbol font (\textfont2); this lowers all normal subscripts to a position 2.7 pt below the baseline, which is enough to make room for a possible superscript that contains a plus sign. Similarly, you can adjust the positioning of superscripts by changing \fontdimen14\tensy. There are parameters for the position of the axis line, the positions of numerator and denominator in a generalized fraction, the spacing above and below limits, the default rule thickness, and so on. Appendix G gives precise details. 10. Special features for math hackers. TEX has a few more primitive operations for math mode that haven’t been mentioned yet. They are occasionally useful if you are designing special formats. Ä Ä If a glue or kern specification is immediately preceded by ‘\nonscript’, TEX will not use that glue or kern in script or scriptscript styles. Thus, for example, the sequence ‘\nonscript\;’ produces exactly the amount of space specified by ‘(3)’ in the spacing table for mathematics that appeared earlier in this chapter. Ä Ä Whenever TEX has scanned a  and is about to read a math formula that appears in text, it will first read another list of tokens that has been predefined by the command \everymath={htoken listi}. (This is analogous to \everypar, which was described in Chapter 14.) Similarly, you can say \everydisplay={htoken listi} to predefine a list of tokens for TEX to read just after it has scanned an opening$$, i.e., just before reading a formula that is to be displayed. With \everymath and \everydisplay, you can set up special conventions that you wish to apply to all formulas.

179

180

Chapter 18: Fine Points of Mathematics Typing

11. Summary. We have discussed more different kinds of formulas in this chapter than you will usually find in any one book of mathematics. If you have faithfully done the exercises so far, you can face almost any formula with confidence. Ä

But here are a few more exercises, to help you review what you have learned. Each of the following “challenge formulas” illustrates one or more of the principles already discussed in this chapter. The author confesses that he is trying to trip you up on several of these. Nevertheless, if you try each one before looking at the answer, and if you’re alert for traps, you should find that these formulas provide a good way to consolidate and complete your knowledge.

Ä

x EXERCISE 18.27

Ä

x EXERCISE 18.28

Ä

x EXERCISE 18.29

Ä

x EXERCISE 18.30

Ä

x EXERCISE 18.31

Ä

x EXERCISE 18.32

Ä

x EXERCISE 18.33

Ä

x EXERCISE 18.34

Ä

x EXERCISE 18.35

Challenge number 1: Explain how to type the phrase ‘nth root’, where ‘nth ’ is treated as a mathematical formula with a superscript in roman type.

Pr( m = n | m + n = 3 ).

Challenge number 3:

√ sin 18◦ = 14 ( 5 − 1).

Challenge number 4:

k = 1.38 × 10−16 erg/◦ K.

Challenge number 5:

¯ ⊂ N L∗ /N = L ¯ ∗ ⊆ · · · ⊆ N L∗n /N = L ¯ ∗n . Φ 1 1

Challenge number 6:

I(λ) =

Challenge number 7:

R1

Challenge number 8:

0

···

RR

R1 0

D

g(x, y)eiλh(x,y) dx dy .

f (x1 , . . . , xn ) dx1 . . . dxn .

Challenge number 9: Here’s a display.

x2m ≡ Ä

S−1 TS = dg(ω1 , . . . , ωn ) = Λ.

Challenge number 2:

½

2 2 Q(Xm − P 2 Wm ) − 2S 2 2 2 − P 2 Wm ) − 2S 2 P22 (Xm

(m odd) (m even)

x EXERCISE 18.36

Challenge number 10: And another.

(1 + x1 z + x21 z 2 + · · · ) . . . (1 + xn z + x2n z 2 + · · · ) = Ä

(mod N ).

x EXERCISE 18.37

Challenge number 11: And another.

Y µX

j≥0

k≥0

ajk z

k

=

X

n≥0

z

n

Ã

X

k0 ,k1 ,...≥0 k0 +k1 +···=n

1 . (1 − x1 z) . . . (1 − xn z) !

a0k0 a1k1 . . . .

Chapter 18: Fine Points of Mathematics Typing

Ä

x EXERCISE 18.38

Challenge number 12: And,

(n1 + n2 + · · · + nm )! = n1 ! n 2 ! . . . n m ! Ä

x EXERCISE 18.39

Challenge number 13: Yet another display.

ΠR Ä

µ ¶µ ¶ µ ¶ n1 + n 2 n1 + n 2 + n 3 n1 + n 2 + · · · + n m ... . n2 n3 nm

·

¸ Y R (1 − q a1 +n )(1 − q a2 +n ) . . . (1 − q aM +n ) a1 , a 2 , . . . , a M . = (1 − q b1 +n )(1 − q b2 +n ) . . . (1 − q bN +n ) b1 , b 2 , . . . , b N n=0

x EXERCISE 18.40

Challenge number 14: And another.

X

f (p) =

p prime

Ä

Z

f (t) dπ(t). t>1

x EXERCISE 18.41

Challenge number 15: Still another. l b’s

k a’s

z }| { z }| { {a, . . . , a, b, . . . , b}. | {z } k+l elements

Ä

x EXERCISE 18.42

Challenge number 16: Put a \smallskip between the rows of matrices in the compound matrix ¶ µ ¶ µ

Ä

x EXERCISE 18.43

  

a b c d

µ

0

e g

f h

i k

j l

 ¶ .

Challenge number 17: Make the columns flush left here.

¯ ¯ ¯ ¯ ¯ det ¯¯ ¯ ¯ ¯

c0 c1 c2 .. .

c1 c2 c3 .. .

c2 c3 c4 .. .

... ... ...

cn

cn+1

cn+2

...

Ä Äx EXERCISE 18.44

¯ cn ¯ ¯ cn+1 ¯ ¯ cn+2 ¯ > 0. ¯ .. ¯ . ¯ ¯ c2n

Challenge number 18: The main problem here is to prime the

X0 x∈A

def

f (x) =

X

x∈A x6=0

f (x).

P

.

181

182

Chapter 18: Fine Points of Mathematics Typing

Ä Äx EXERCISE 18.45

Challenge number 19: You may be ready now for this display. def

2 ↑↑ k = 2

Ä Äx EXERCISE 18.46

22

··

·2

o

k

.

Challenge number 20: And finally, when you have polished off all the other examples, here’s the ultimate test. Explain how to obtain the commutative diagram

0

−→

0

−→

OC ° ° °

OC

ι

−→ −→

E  φ y

π∗ OD

ρ

−→

0   y

−→

0

R1 f∗ OV (−D) −→   yθi ⊗γ −1 ¡ ¢ R1 f∗ OV (−iM ) ⊗ γ −1   y

0

δ

−→

L  ψ y

0

using \matrix. (Many of the entries are blank.)

12. Words of advice. The number of different notations is enormous and still growing, so you will probably continue to find new challenges as you continue to type mathematical papers. It’s a good idea to keep a personal notebook in which you record all of the non-obvious formulas that you have handled successfully, showing both the final output and what you typed to get it. Then you’ll be able to refer back to those solutions when you discover that you need to do something similar, a few months later. If you’re a mathematician who types your own papers, you have now learned how to get enormously complex formulas into print, and you can do so without going through an intermediary who may somehow distort their meaning. But please, don’t get too carried away by your newfound talent; the fact that you are able to typeset your formulas with TEX doesn’t necessarily mean that you have found the best notation for communicating with the readers of your work. Some notations will be unfortunate even when they are beautifully formatted.

Chapter 18: Fine Points of Mathematics Typing

Mathematicians are like Frenchmen: whenever you say something to them, they translate it into their own language, and at once it is something entirely different. — GOETHE, Maxims and Reflexions (1829) The best notation is no notation; whenever it is possible to avoid the use of a complicated alphabetic apparatus, avoid it. A good attitude to the preparation of written mathematical exposition is to pretend that it is spoken. Pretend that you are explaining the subject to a friend on a long walk in the woods, with no paper available; fall back on symbolism only when it is really necessary. — PAUL HALMOS, How to Write Mathematics (1970)

183

(page 184)

19 Displayed Equations

Chapter 19: Displayed Equations

By now you know how to type mathematical formulas so that TEX will handle them with supreme elegance; your knowledge of math typing is nearly complete. But there is one more part to the story, and the purpose of this chapter is to present the happy ending. We have discussed how to deal with individual formulas; but displays often involve a whole bunch of different formulas, or different pieces of a huge formula, and it’s a bit of a problem to lay them out so that they line up properly with each other. Fortunately, large displays generally fall into a few simple patterns. 1. One-line displays. Before plunging into the general question of display layout, let’s recapitulate what we have already covered. If you type ‘$$hformulai$$’, TEX will display the formula in flamboyant display style, centering it on a line by itself. We have also noted in Chapter 18 that it’s possible to display two short formulas at once, by typing ‘$$hformula1 i\qquadhformula2 i$$’; this reduces the two-formula problem to a one-formula problem. You get the two formulas separated by two quads of space, the whole being centered on a line. Displayed equations often involve ordinary text. Chapter 18 explains how to get roman type into formulas without leaving math mode, but the best way to get text into a display is to put it into an \hbox. There needn’t even be any math at all; to typeset Displayed Text you can simply say ‘$$\hbox{Displayed Text}$$’. But here’s a more interesting example: Xn = X k

if and only if

Y n = Yk

and

Z n = Zk .

Formulas and text were combined in this case by typing $$X_n=X_k \qquad\hbox{if and only if}\qquad Y_n=Y_k \quad\hbox{and}\quad Z_n=Z_k.$$ Notice that \qquad appears around ‘if and only if’, but a single \quad surrounds ‘and’; this helps to indicate that the Y and Z parts of the display are related more closely to each other than to the X part. Consider now the display Yn = Xn mod p

and

Zn = Xn mod q

for all n ≥ 0.

Can you figure out how to type this? One solution is $$Y_n=X_n\bmod p \quad\hbox{and}\quad Z_n=X_n\bmod q \qquad\hbox{for all }n\ge0.$$ Notice that a space has been left after ‘all’ in the hbox here, since spaces disappear when they are out in formula-land. But there’s a simpler and more logical way to proceed, once you get used to TEX’s idea of modes: You can type ... \qquad\hbox{for all $n\ge0$.}$$185 186 Chapter 19: Displayed Equations Wow—that’s math mode inside of horizontal mode inside of display math mode. But in this way your manuscript mirrors what you are trying to accomplish, while the previous solution (with the space after ‘all’) looks somewhat forced. x EXERCISE 19.1 Typeset the following four displays (one at a time): ∞ ³ ´−1 X p an z n converges if |z| < lim sup n |an | . n→∞ n=0 f (x + ∆x) − f (x) → f 0 (x) ∆x Ä as ∆x → 0. kui k = 1, ui · uj = 0 if i 6= j.      an arc  an arc   is The confluent image of an arc or a circle . a circle     a fan or an arc a fan x EXERCISE 19.2 Sometimes display style is too grandiose, when the formula being displayed is 1 x 2 or something equally simple. One day B. L. User tried to remedy this by typing it as ‘$$y={\scriptstyle1\over\scriptstyle2}x$$’, but the resulting formula y= 1 y= x 2 wasn’t at all what he had in mind. What’s the right way to get simply ‘y = 21 x’ when you don’t want big fractions in displays? Ä x EXERCISE 19.3 Ä x EXERCISE 19.4 What difference, if any, is there between the result of typing ‘$$hformulai$$’ and the result of typing ‘$$\hbox{$hformulai$}’ ? You may have noticed that most of the displays in this manual are not centered; displayed material is usually aligned at the left with the paragraph indentation, as part of the book design, because this is an unusual book. Explain how you could typeset a formula like 1 1 1 + − + · · · = ln 2 2 3 4 that is off-center in this way. 1− If you’ve had previous experience typing mathematical papers, you probably have been thinking, “What about equation numbers? When is this book going to talk about them?” Ah yes, now is the time to discuss those sneaky little labels that appear off to the side of displays. If you typehformulai\eqnohformulai$$Chapter 19: Displayed Equations TEX will display the first formula and it will also put an equation number (the second formula) at the right-hand margin. For example,$$x^2-y^2 = (x+y)(x-y).\eqno(15)$$will produce this: x2 − y 2 = (x + y)(x − y). (15) You can also get equation numbers at the left-hand margin, with \leqno. For example,$$x^2-y^2 = (x+y)(x-y).\leqno(16)$$will produce this: x2 − y 2 = (x + y)(x − y). (16) Notice that you always give the equation number second, even when it is going to appear at the left. Everything from the \eqno or \leqno command to the$$ that ends the display is the equation number. Thus, you’re not allowed to have two equation numbers in the same display; but there’s a way to get around that restriction, as we’ll see later. Ä

Nowadays people are using right-hand equation numbers more and more, because a display most often comes at the end of a sentence or clause, and the right-hand convention keeps the number from intruding into the clause. Furthermore, it’s often possible to save space when a displayed equation follows a short text line, since less space is needed above the display; such savings are not possible with \leqno, because there’s no room for overlap. For example, there is less space above display (15) than there is above (16) in our illustrations of \eqno and \leqno, although the formulas and text are otherwise identical.

Ä

If you look closely at (15) and (16) above, you can see that the displayed formulas have been centered without regard to the presence of the equation numbers. But when a formula is large, TEX makes sure that it does not interfere with its number; the equation number may even be placed on a line by itself.

x EXERCISE 19.5 How would you produce the following display? Y X Á Y 1 = zn (1 − q k ). (1 − q k z) k≥0

Ä

n≥0

(160 )

1≤k≤n

x EXERCISE 19.6

Equation numbers are math formulas, typeset in text style. So how can you get an equation number like ‘(3–1)’ (with an en-dash)?

Ä Äx EXERCISE 19.7

B. L. User tried typing ‘\eqno(*)’ and ‘\eqno(**)’, and he was pleased to discover that this produced the equation numbers ‘(∗)’ and ‘(∗∗)’. [He had been a bit worried that they would come out ‘(*)’ and ‘(**)’ instead.] But then a few months later he tried ‘\eqno(***)’ and got a surprise. What was it?

187

188

Chapter 19: Displayed Equations

Ä Ä Somewhere in this manual there ought to be a description of exactly how TEX displays formulas; i.e., how it centers them, how it places the equation numbers, how it inserts extra space above and below, and so on. Well, now is the time for those rules to be stated. They are somewhat complex, because they interact with things like \parshape, and because they involve several parameters that haven’t been discussed yet. The purpose of the rules is to explain exactly what sorts of boxes, glue, and penalties are placed onto the current vertical list when a display occurs.

Ä Ä If a display occurs after, say, four lines of a paragraph, TEX’s internal register

called \prevgraf will be equal to 4 when the display starts. The display will be assumed to take three lines, so \prevgraf will become 7 when the paragraph is resumed at the end of the display (unless you have changed \prevgraf in the meantime). TEX assigns special values to three hdimeni parameters immediately after the opening $$is sensed: \displaywidth and \displayindent are set to the line width z and the shift amount s for line number \prevgraf+2, based on the current paragraph shape or hanging indentation. (Usually \displaywidth is the same as \hsize, and \displayindent is zero, but the paragraph shape can vary as described in Chapter 14.) Furthermore, \predisplaysize is set to the effective width p of the line preceding the display, as follows: If there was no previous line (e.g., if the$$ was preceded by \noindent or by the closing $$of another display), p is set to −16383.99999 pt (i.e., to the smallest legal dimension, −\maxdimen). Otherwise TEX looks inside the hbox that was formed by the previous line, and sets p to the position of the right edge of the rightmost box inside that hbox, plus the indentation by which the enclosing hbox has been moved right, plus two ems in the current font. However, if this value of p depends on the fact that glue in that hbox was stretching or shrinking—for example, if the \parfillskip glue is finite, so that the material preceding it has not been set at its natural width—then p is set to \maxdimen. (This doesn’t happen often, but it keeps TEX machine independent, since p never depends on quantities that may be rounded differently on different computers.) Notice that \displaywidth and \displayindent are not affected by \leftskip and \rightskip, but \predisplaysize is. The values of \displaywidth, \displayindent, and \predisplaysize will be used by TEX after the displayed formula has been read, as explained below; your program can examine them and/or change them, if you want the typesetting to be done differently. Ä Ä After a display has been read, TEX converts it from a math list to a horizontal list h in display style, as explained in Appendix G. An equation number, if present, is processed in text style and put into an hbox a with its natural width. Now the fussy processing begins: Let z, s, and p be the current values of \displaywidth, \displayindent, and \predisplaysize. Let q and e be zero if there is no equation number; otherwise let e be the width of the equation number, and let q be equal to e plus one quad in the symbols font (i.e., in \textfont2). Let w0 be the natural width of the displayed formula h. If w0 + q ≤ z, list h is packaged in an hbox b having its natural width w0 . But if w0 + q > z (i.e., if the display is too wide to fit at its natural width), TEX performs the following “squeeze routine”: If e 6= 0 and if there is enough shrinkability in the displayed formula h to reduce its width to z − q, then list h is packaged in an hbox b of width z − q. Otherwise e is set to zero, and list h is packaged in a (possibly overfull) hbox b of width min(w0 , z). Ä Ä (Continuation.) TEX tries now to center the display without regard to the equation number. But if such centering would make it too close to that number Chapter 19: Displayed Equations (where “too close” means that the space between them is less than the width e), the equation is either centered in the remaining space or placed as far from the equation number as possible. The latter alternative is chosen only if the first item on list h is glue, since TEX assumes that such glue was placed there in order to control the spacing precisely. But let’s state the rules more formally: Let w be the width of box b. TEX computes a displacement d, to be used later when positioning box b, by first setting d = 12 (z − w). If e > 0 and if d < 2e, then d is reset to 12 (z − w − e) or to zero, where zero is chosen if list h begins with a glue item. Ä Ä (Continuation.) TEX is now ready to put things onto the current vertical list, just after the material previously constructed for the paragraph-so-far. First comes a penalty item, whose cost is an integer parameter called \predisplaypenalty. Then comes glue. If d + s ≤ p, or if there was a left equation number (\leqno), TEX sets ga and gb to glue items specified by the parameters \abovedisplayskip and \belowdisplayskip, respectively; otherwise ga and gb become glue items corresponding to \abovedisplayshortskip and \belowdisplayshortskip. [Translation: If the predisplaysize is short enough so that it doesn’t overlap the displayed formula, the glue above and below the display will be “short” by comparison with the glue that is used when there is an overlap.] If e = 0 and if there is an \leqno, the equation number is appended as an hbox by itself, shifted right s and preceded by interline glue as usual; an infinite penalty is also appended, to prevent a page break between this number and the display. Otherwise a glue item ga is placed on the vertical list. Ä Ä (Continuation.) Now comes the displayed equation itself. If e 6= 0, the equation number box a is combined with the formula box b as follows: Let k be a kern of width z − w − e − d. In the \eqno case, box b is replaced by an hbox containing (b, k, a); in the \leqno case, box b is replaced by an hbox containing (a, k, b), and d is set to zero. In all cases, box b is then appended to the vertical list, shifted right by s + d. Ä Ä (Continuation.) The final task is to append the glue or the equation number that follows the display. If there was an \eqno and if e = 0, an infinite penalty is placed on the vertical list, followed by the equation number box a shifted right by s + z minus its width, followed by a penalty item whose cost is the value of \postdisplaypenalty. Otherwise a penalty item for the \postdisplaypenalty is appended first, followed by a glue item for gb as specified above. TEX now adds 3 to \prevgraf and returns to horizontal mode, ready to resume the paragraph. Ä Ä One consequence of these rules is that you can force an equation number to appear on a line by itself by making its width zero, i.e., by saying either ‘\eqno\llap{hformulai}’ or ‘\leqno\rlap{hformulai}’. This makes e = 0, and the condition e = 0 controls TEX’s positioning logic, as explained in the rules just given. Ä Ä Plain TEX sets \predisplaypenalty=10000, because fine printers tradition- ally shun displayed formulas at the very top of a page. You can change \predisplaypenalty and \postdisplaypenalty if you want to encourage or discourage page breaks just before or just after a display. For example, ‘$$\postdisplaypenalty= -10000hformulai$$’ will force a page break, putting the formula at the bottom line. It is better to force a page break this way than to say \eject right after$$...$$; such an eject (which follows the \belowdisplayskip glue below the display) causes the page to be short, because it leaves unwanted glue at the bottom. 189 190 Chapter 19: Displayed Equations Ä Äx EXERCISE 19.8 Read the rules carefully and deduce the final position of ‘x = y’ in the formula$$\quad x=y \hskip10000pt minus 1fil \eqno(5)assuming that there is no hanging indentation. Also consider \leqno instead of \eqno. Ä Ä TEX also allows “alignment displays,” which are not processed in math mode because they contain no formulas at the outer level. An alignment display is created by commands of the general formhassignmentsi\halign{halignmenti}hassignmentsiwhere the hassignmentsi are optional things like parameter changes that do not produce any math lists. In such displays, the \halign is processed exactly as if it had appeared in vertical mode, and it will construct a vertical list v as usual, except that each row of the alignment will be shifted right by the \displayindent. After the alignment and the closing assignments have been processed, TEX will put a \predisplaypenalty item and some \abovedisplayskip glue on the main vertical list, followed by v, followed by a \postdisplaypenalty item and \belowdisplayskip glue. Thus, alignment displays are essentially like ordinary alignments, except that they can interrupt paragraphs; furthermore, they are embedded in glue and penalties just like other displays. The \displaywidth and \predisplaysize do not affect the result, although you could use those parameters in your \halign. An entire alignment display is considered to be only three lines long, as far as \prevgraf is concerned. 2. Multi-line displays. OK, the use of displayed formulas is very nice. But when you try typing a lot of manuscripts you will run into some displays that don’t fit the simple pattern of a one-line formula with or without an equation number. Plain TEX provides special control sequences that will cover most of the remaining cases. Multi-line displays usually consist of several equations that should be lined up by their ‘=’ signs, as in X1 + · · · + Xp = m, Y1 + · · · + Yq = n. The recommended procedure for such a display is to use \eqalign, which works with special markers & and \cr that we have already encountered in connection with \cases and \matrix in Chapter 18. Here’s how to type this particular one:\eqalign{X_1+\cdots+X_p&=m,\cr Y_1+\cdots+Y_q&=n.\cr}There can be any number of equations in an \eqalign; the general pattern is \eqalign{hleft-hand side1 i&hright-hand side1 i\cr hleft-hand side2 i&hright-hand side2 i\cr .. . hleft-hand siden i&hright-hand siden i\cr} Chapter 19: Displayed Equations where each hright-hand sidei starts with the symbol on which you want alignment to occur. For example, every right-hand side often begins with an = sign. The equations will be typeset in display style. x EXERCISE 19.9 In practice, the left-hand sides of aligned formulas are often blank, and the alignment is often done with respect to other symbols as well as =. For example, the following display is typical; see if you can guess how the author typed it: T (n) ≤ T (2dlg ne ) ≤ c(3dlg ne − 2dlg ne ) < 3c · 3lg n = 3c nlg 3 . The result of \eqalign is a vertically centered box. This makes it easy to get a formula like   ( )  2  α = f (z)   x = α − β β = f (z 2 ) .   y = 2γ  3  γ = f (z ) You simply use \eqalign twice in the same line:\left\{ \eqalign{\alpha&=f(z)\cr \beta&=f(z^2)\cr \gamma&=f(z^3)\cr} \right\}\qquad\left\{ \eqalign{x&=\alpha^2-\beta\cr y&=2\gamma\cr}\right\}.x EXERCISE 19.10 Try your hand at the numbered two-line display P (x) = a0 + a1 x + a2 x2 + · · · + an xn , P (−x) = a0 − a1 x + a2 x2 − · · · + (−1)n an xn . (30) [Hint: Use the fact that \eqalign produces a vertically centered box; the equation number ‘(30)’ is supposed to appear halfway between the two lines.] x EXERCISE 19.11 What happens if you forget the & in one equation of an \eqalign? Ä Multi-line formulas sometimes fit together in odd ways, and you’ll find that every once in a while you will want to move certain lines farther apart or closer together. If you type ‘\noalign{\vskiphgluei}’ after any \cr, TEX will insert the given amount of extra glue just after that particular line. For example, \noalign{\vskip3pt} will put 3 pt of additional space between lines. You can also change the amount of space before the first line, in the same way. 191 192 Chapter 19: Displayed Equations The next level of complexity occurs when you have several aligned equations with several equation numbers. Or perhaps some of the lines are numbered and others are not: (x + y)(x − y) = x2 − xy + yx − y 2 = x2 − y 2 ; 2 2 2 (x + y) = x + 2xy + y . (4) (5) For this situation plain TEX provides \eqalignno; you use it like \eqalign, but on each line that you want an equation number you add ‘&hequation numberi’ just before the \cr. The example above was generated by\eqalignno{(x+y)(x-y)&=x^2-xy+yx-y^2\cr &=x^2-y^2;&(4)\cr (x+y)^2&=x^2+2xy+y^2.&(5)\cr}Notice that the second & is omitted unless there’s an equation number. And there’s also \leqalignno, which puts equation numbers at the left. In this case it is appropriate to move the ‘(4)’ to the beginning of its equation: (4) (5) (x + y)(x − y) = x2 − xy + yx − y 2 = x2 − y 2 ; (x + y)2 = x2 + 2xy + y 2 . Although the equation numbers appear at the left, you are still supposed to input them at the right, just as you do with \leqno; in other words, you should type ‘\leqalignno{(x+y)(x-y)&...&(4)\cr...}’ to get the previous display. Caution: \eqalignno and \leqalignno both center the set of equations without regard to the widths of the equation numbers. If the equations or their numbers get too wide, they might overlap, yet no error message will be given. x EXERCISE 19.12 Typeset the following display: (9) gcd(u, v) = gcd(v, u); (10) gcd(u, v) = gcd(−u, v). x EXERCISE 19.13 And here’s another one to try, just to keep in practice: ¶2 Z ∞ Z ∞ µZ ∞ 2 2 −x2 e−(x +y ) dx dy dx = e −∞ = = Z Z −∞ −∞ 2π Z ∞ 2 e−r r dr dθ 0 0 = π. 0 2π µ 2 ¯r=∞ ¶ e−r ¯¯ dθ − 2 ¯r=0 (11) Chapter 19: Displayed Equations Ä Although \eqalign and \eqalignno look nearly the same, there’s really a fundamental distinction between them: \eqalign makes a single, vertically centered box, which is no wider than it needs to be; but \eqalignno generates a set of lines that have the full display width (reaching all the way to both margins). Thus, for example, you can use \eqalign several times in a display, but \eqalignno can appear only once. If you try to use \eqno in conjunction with \eqalign, you get a decent result, but if you try to use \eqno in connection with \eqalignno you’ll get some sort of weird error message(s). Ä Ä The definitions in Appendix B reveal why \eqalign and \eqalignno behave differently: \eqalign is an abbreviation for \vcenter{\halign{...}}, while \eqalignno is an abbreviation for \halign to\displaywidth{...}; thus the \eqalignno macro generates an “alignment display.” Ä Ä This difference between \eqalign and \eqalignno has two interesting con- sequences. (1) It’s impossible to break an \eqalign between pages, but an \eqalignno can be broken. In fact, you can force a page break after a particular line if you insert ‘\noalign{\break}’ after the \cr for that line. You can prohibit all breaks in an \eqalignno if you set \interdisplaylinepenalty=10000; or you can enclose the whole works in a \vbox:\vbox{\eqalignno{...}}(2) You can also insert a line of text between two equations, without losing the alignment. For example, consider the two displays x=y+z and x2 = y 2 + z 2 . These were actually generated as a single display by typing\eqalignno{x&=y+z\cr \noalign{\hbox{and}} x^2&=y^2+z^2.\cr}Therefore the fact that their = signs line up is not just a lucky coincidence. Sometimes you will want to adjust the spacing above or below such a line of inserted text, by putting a \vskip or two inside of the \noalign{...}. Incidentally, this example also shows that it is possible to use \eqalignno without giving any equation numbers. Ä Äx EXERCISE 19.14 What happens if \eqalign is substituted for \eqalignno in this last example? Ä Äx EXERCISE 19.15 Our friend Ben User got into trouble again when he tried to move an equation number up higher than its usual position, by typing this:\eqalignno{...&\raise6pt\hbox{(5)}\cr}What was his oversight, and what could he have done instead? 193 194 Chapter 19: Displayed Equations Ä For other types of displays, plain TEX provides \displaylines, which lets you display any number of formulas in any way you want, without any alignment. The general form is\displaylines{hdisplayed formula1 i\cr hdisplayed formula2 i\cr .. . hdisplayed formulan i\cr}Each formula will be centered, because \displaylines puts \hfil at the left and the right of each line; you can override this centering to get things flush left or flush right by inserting \hfill, which takes precedence over \hfil. Ä x EXERCISE 19.16 Use \displaylines to typeset the three-line display if if x≡y x ≡ x; x≡y and then y≡z (1) y ≡ x; then (2) x ≡ z. (3) Ä If you look closely at the multi-line displays in this chapter, you’ll see that the baselines are farther apart than they are in normal text; mathematics publishers generally do this in order to make the displays easier to read. In accordance with this tradition, \eqalign and its relatives automatically increase the \baselineskip. If you are making a multi-line display with TEX’s primitive \halign command, instead of using one of the plain TEX macros, you might want to make this same baseline adjustment, and you can do it easily by saying ‘\openup1\jot \halign{...}$$’. The \openup macro increases \lineskip and \lineskiplimit as well as \baselineskip. If you say ‘\openup2\jot’, the lines are spread apart 2 extra units, where plain TEX opens things up in units of 3 pt. Since$$...acts as a group, the effect of \openup will disappear when the display is finished. Any hdimeni can follow \openup, but it’s customary to express the amount symbolically in terms of a \jot instead of using absolute units; then your manuscript can be used with a variety of different formats. Ä Ä Plain TEX’s \displaylines, \eqalignno, and \leqalignno macros begin with ‘\openup1\jot’. If you don’t want the lines to be opened up, you can cancel this by saying, e.g., ‘\openup-1\jot \eqalignno{...}$$’, because \openup has a cumulative effect. Ä Ä Suppose that you have decided to make a homegrown display having the gen- eral form ‘$$\openup1\jot \halign{...}’; and for convenience, let’s suppose that the normal conventions of plain TEX are in force, so that \jot=3pt and \baselineskip=12pt. Then the \openup macro changes the baselineskip distance to 15 pt. It follows that the baseline of the text line that immediately precedes the display will be 15 pt above the topmost baseline of the display, plus the \abovedisplayskip. But when the paragraph resumes, its next baseline will be only 12 pt below the bottom baseline of the display, plus the \belowdisplayskip, because the \baselineskip parameter will have reverted to its normal value. The \eqalignno and \displaylines macros say ‘\noalign{\vskip−d}’ before their first lines, where d is the net amount of opening-up, in order to compensate for this difference. Chapter 19: Displayed Equations 3. Long formulas. Our discussion of mathematics typing is almost complete; we need to deal with just one more problem: What should be done when a formula is so long that it doesn’t fit on a single line? For example, suppose that you encounter the equation σ(234 −1, 235 , 1) = −3+(234 −1)/235 +235/(234 −1)+7/235 (234 −1)−σ(235 , 234 −1, 1). You’ll have to break it up somehow; TEX has done its best to squeeze everything together by shrinking the spaces next to the + and − signs to zero, but still the line has come out overfull. Let’s try to break that equation just before the ‘+7’. One common way to do this is to type\eqalign{\sigma(2^{34}-1,2^{35},1) &=-3+(2^{34}-1)/2^{35}+2^{35}\!/(2^{34}-1)\cr &\qquad+7/2^{35}(2^{34}-1)-\sigma(2^{35},2^{34}-1,1).\cr}$$which yields σ(234 − 1, 235 , 1) = −3 + (234 − 1)/235 + 235/(234 − 1) + 7/235 (234 − 1) − σ(235 , 234 − 1, 1). The idea is to treat a long one-line formula as a two-line formula, using \qquad on the second line so that the second part of the formula appears well to the right of the = sign on the first line. x EXERCISE 19.17 Explain how to deal with the following display. xn u1 + · · · + xn+t−1 ut = xn u1 + (axn + c)u2 + · · · ¡ ¢ + at−1 xn + c(at−2 + · · · + 1) ut = (u1 + au2 + · · · + at−1 ut )xn + h(u1 , . . . , ut ). (47) Ä It’s quite an art to decide how to break long displayed formulas into several lines; TEX never attempts to break them, because no set of rules is really adequate. The author of a mathematical manuscript is generally the best judge of what to do, since break positions depend on subtle factors of mathematical exposition. For example, it is often desirable to emphasize some of the symmetry or other structure that underlies a formula, and such things require a solid understanding of exactly what is going on in that formula. Ä Nevertheless, it is possible to state a few rules of thumb about how to deal with long formulas in displays, since there are some principles that the best mathematical typesetters tend to follow: a) Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations and relations. Thus, we didn’t end the first line of our σ( . . . ) example with ‘(2^{34}-1)+’; we ended it with ‘(2^{34}-1)’ and began the second line with ‘+’. 195 196 Chapter 19: Displayed Equations b) When an equation is broken before a binary operation, the second line should start at least two quads to the right of where the innermost subformula containing that binary operation begins on the first line. For example, if you wish to break$$\sum_{0\d \unknowntrue\else\unknownfalse\fi \multiply\a by\d \ifnum\a=\p \global\primefalse\unknownfalse\fi} The computation is fairly straightforward, except that it involves a loop inside a loop; therefore \testprimality introduces an extra set of braces, to keep the inner loop control from interfering with the outer loop. The braces make it necessary to say ‘\global’ when \ifprime is being set true or false. TEX spent more time constructing

Chapter 20: Definitions (also called Macros)

that sentence than it usually spends on an entire page; the \trialdivision macro was expanded 132 times.

Ä Ä The \loop macro that does all these wonderful things is actually quite simple. It puts the code that’s supposed to be repeated into a control sequence called \body, and then another control sequence iterates until the condition is false: \def\loop#1\repeat{\def\body{#1}\iterate} \def\iterate{\body\let\next=\iterate\else\let\next=\relax\fi\next} The expansion of \iterate ends with the expansion of \next; therefore TEX is able to remove \iterate from its memory before invoking \next, and the memory does not fill up during a long loop. Computer scientists call this “tail recursion.”

Ä Ä The \hex macro below, which converts count register \n to hexadecimal no-

tation, illustrates a recursive control structure in which many copies of \hex can be active simultaneously. Recursion works better than simple \loop iteration in this application because the hexadecimal digits are discovered from right to left, while they must be output from left to right. (The number in \n should be ≥ 0.) \def\hex{{\count0=\n \divide\n by16 \ifnum\n>0 \hex\fi \count2=\n \multiply\count2 by-16 \advance\count0 by\count2 \hexdigit}} \def\hexdigit{\ifnum\count0250 \setbox0=\line{\trialtextb}\fi The badness is between 0 and 10000 unless the box is overfull, when \badness=1000000.

If age or weaknes doe prohibyte bloudletting, you must use boxing. — PHILIP BARROUGH, The Methode of Phisicke (1583) The only thing that never looks right is a rule. There is not in existence a page with a rule on it that cannot be instantly and obviously improved by taking the rule out. — GEORGE BERNARD SHAW, in The Dolphin (1940)

229

(page 230)

22 Alignment

Chapter 22: Alignment

231

Printers charge extra when you ask them to typeset tables, and they do so for good reason: Each table tends to have its own peculiarities, so it’s necessary to give some thought to each one, and to fiddle with alternative approaches until finding something that looks good and communicates well. However, you needn’t be too frightened of doing tables with TEX, since plain TEX has a “tab” feature that handles simple situations pretty much like you would do them on a typewriter. Furthermore, TEX has a powerful alignment mechanism that makes it possible to cope with extremely complex tabular arrangements. Simple cases of these alignment operations will suffice for the vast majority of applications. Let’s consider tabbing first. If you say ‘\settabs n \columns’, plain TEX makes it easy to produce lines that are divided into n equal-size columns. Each line is specified by typing \+htext1 i&htext2 i& · · · \cr where htext1 i will start flush with the left margin, htext2 i will start at the left of the second column, and so on. Notice that ‘\+’ starts the line. The final column is followed by ‘\cr’, which old-timers will recognize as an abbreviation for the “carriage return” operation on typewriters that had carriages. For example, consider the following specification: \settabs 4 \columns \+&&Text that starts in the third column\cr \+&Text that starts in the second column\cr \+\it Text that starts in the first column, and&&& the fourth, and&beyond!\cr After ‘\settabs4\columns’ each \+ line is divided into quarters, so the result is Text that starts in the third column Text that starts in the second column Text that starts in the first column, and the fourth, and

beyond!

This example merits careful study because it illustrates several things. (1) The ‘&’ is like the TAB key on many typewriters; it tells TEX to advance to the next tab position, where there’s a tab at the right edge of each column. In this example, TEX has set up four tabs, indicated by the dashed lines; a dashed line is also shown at the left margin, although there isn’t really a tab there. (2) But ‘&’ isn’t exactly like a mechanical typewriter TAB, because it first backs up to the beginning of the current column before advancing to the next. In this way you can always tell what column you’re tabbing to, by counting the number of &’s; that’s handy, because variable-width type otherwise makes it difficult to know whether you’ve passed a tab position or not. Thus, on the last line of our example, three &’s were typed in order to get to column 4, even though the text had already extended into column 2 and perhaps into column 3. (3) You can say ‘\cr’ before you have specified a complete set of columns, if the remaining columns are blank. (4) The &’s are different from tabs in another way,

232

Chapter 22: Alignment

too: TEX ignores spaces after ‘&’, hence you can conveniently finish a column by typing ‘&’ at the end of a line in your input file, without worrying that an extra blank space will be introduced there. (The second-last line of the example ends with ‘&’, and there is an implicit blank space following that symbol; if TEX hadn’t ignored that space, the words ‘the fourth’ wouldn’t have started exactly at the beginning of the fourth column.) Incidentally, plain TEX also ignores spaces after ‘\+’, so that the first column is treated like the others. (5) The ‘\it’ in the last line of the example causes only the first column to be italicized, even though no braces were used to confine the range of italics, because TEX implicitly inserts braces around each individual entry of an alignment. Ä

Once you have issued a \settabs command, the tabs remain set until you reset them, even though you go ahead and type ordinary paragraphs as usual. But if you enclose \settabs in {...}, the tabs defined inside a group don’t affect the tabs outside; ‘\global\settabs’ is not permitted.

Ä

Tabbed lines usually are used between paragraphs, in the same places where you would type \line or \centerline to get lines with a special format. But it’s also useful to put \+ lines inside a \vbox; this makes it convenient to specify displays that contain aligned material. For example, if you type $$\vbox{\settabs 3 \columns \+This is&a strange&example\cr \+of displayed&three-column&format.\cr}$$ you get the following display: This is of displayed

a strange three-column

example format.

In this case the first column doesn’t appear flush left, because TEX centers a box that is being displayed. Columns that end with \cr in a \+ line are put into a box with their natural width; so the first and second columns here are one-third of the \hsize, but the third column is only as wide as the word ‘example’. We have used $$in this construction even though no mathematics is involved, because$$ does other useful things; for example, it centers the box, and it inserts space above and below.

People don’t always want tabs to be equally spaced, so there’s another way to set them, by typing ‘\+hsample linei\cr’ immediately after ‘\settabs’. In this case tabs are placed at the positions of the &’s in the sample line, and the sample line itself does not appear in the output. For example, \settabs\+\indent&Horizontal lists\quad&\cr % sample line \+&Horizontal lists&Chapter 14\cr \+&Vertical lists&Chapter 15\cr \+&Math lists&Chapter 17\cr causes TEX to typeset the following three lines of material: Horizontal lists Chapter 14 Vertical lists Chapter 15 Math lists Chapter 17

Chapter 22: Alignment

The \settabs command in this example makes column 1 as wide as a paragraph indentation; and column 2 is as wide as ‘Horizontal lists’ plus one quad of space. Only two tabs are set in this case, because only two &’s appear in the sample line. (A sample line might as well end with &, because the text following the last tab isn’t used for anything.) The first line of a table can’t always be used as a sample line, because it won’t necessarily give the correct tab positions. In a large table you have to look ahead and figure out the biggest entry in each column; the sample line is then constructed by typing the widest first column, the widest second column, etc., omitting the last column. Be sure to include some extra space between columns in the sample line, so that the columns won’t touch each other. x EXERCISE 22.1 Explain how to typeset the following table [from Beck, Bertholle, and Child, Mastering the Art of French Cooking (New York: Knopf, 1961)]: Weight

Servings

Approximate Cooking Time*

8 lbs. 9 lbs. 9 1/2 lbs. 10 1/2 lbs.

6 7 to 8 8 to 9 9 to 10

1 hour and 50 to 55 minutes About 2 hours 2 hours and 10 to 15 minutes 2 hours and 15 to 20 minutes

* For a stuffed goose, add 20 to 40 minutes to the times given. Ä

If you want to put something flush right in its column, just type ‘\hfill’ before it; and be sure to type ‘&’ after it, so that TEX will be sure to move the information all the way until it touches the next tab. Similarly, if you want to center something in its column, type ‘\hfill’ before it and ‘\hfill&’ after it. For example, \settabs 2 \columns \+\hfill This material is set flush right& \hfill This material is centered\hfill&\cr \+\hfill in the first half of the line.& \hfill in the second half of the line.\hfill&\cr

produces the following little table: This material is set flush right in the first half of the line.

Ä

This material is centered in the second half of the line.

The \+ macro in Appendix B works by putting the htexti for each column that’s followed by & into an hbox as follows: \hbox to hcolumn widthi{htexti\hss}

The \hss means that the text is normally flush left, and that it can extend to the right of its box. Since \hfill is “more infinite” than \hss in its ability to stretch, it has the effect of right-justifying or centering as stated above. Note that \hfill doesn’t shrink, but \hss does; if the text doesn’t fit in its column, it will stick out at the right. You could cancel the shrinkability of \hss by adding \hfilneg; then an oversize text would produce an overfull box. You could also center some text by putting ‘\hss’ before it and

233

234

Chapter 22: Alignment

just ‘&’ after it; in that case the text would be allowed to extend to the left and right of its column. The last column of a \+ line (i.e., the column entry that is followed by \cr) is treated differently: The htexti is simply put into an hbox with its natural width.

Ä

Computer programs present difficulties of a different kind, since some people like to adopt a style in which the tab positions change from line to line. For example, consider the following program fragment: if n < r then n := n + 1 else begin print totals; n := 0; end; while p > 0 do begin q := link (p); free node(p); p := q; end; Special tabs have been set up so that ‘then’ and ‘else’ appear one above the other, and so do ‘begin’ and ‘end’. It’s possible to achieve this by setting up a new sample line whenever a new tab position is needed; but that’s a tedious job, so plain TEX makes it a little simpler. Whenever you type & to the right of all existing tabs, the effect is to set a new tab there, in such a way that the column just completed will have its natural width. Furthermore, there’s an operation ‘\cleartabs’ that resets all tab positions to the right of the current column. Therefore the computer program above can be TEXified as follows:

Ä Ä

\vbox{\+\bf if n −∞.) Let tk be the natural width of the tabskip glue between columns k and k + 1, for 1 ≤ k < n. Now the final width wj of column j is determined by the formula wj = max (wij − 1≤i≤j P i≤k-20000 \else\dosupereject\fi} \def\doubleformat{\shipout\vbox{\makeheadline \fullline{\box\leftcolumn\hfil\columnbox} \makefootline} \advancepageno} \def\columnbox{\leftline{\pagebody}} The \columnbox macro uses \leftline in order to ensure that it produces a box whose width is \hsize. The width of \box255 is usually, but not always, equal to \hsize at the beginning of an output routine; any other width would louse up the format. Ä Ä When double-column setting ends, there’s a 50-50 chance that the final column has fallen at the left, so it will not yet have been output. The code \supereject \if R\lr \null\vfill\eject\fi supplies an empty right-hand column in this case, ensuring that all of the accumulated material will be printed. It’s possible to do fancier column balancing on the last page, but the details are tricky if footnotes and other insertions need to be accommodated as well. Appendix E includes the macros that were used to balance the columns at the end of the index in Appendix I, and to start two-column format in mid-page. Ä Äx EXERCISE 23.4 How should the example above be modified if you want three-column output? 257 258 Chapter 23: Output Routines Ä Ä Since TEX’s output routine lags behind its page-construction activity, you can get erroneous results if you change the \headline or the \footline in an uncontrolled way. For example, suppose that you are typesetting a book, and that the format you are using allows chapters to start in the middle of a page; then it would be a mistake to change the running headline at the moment you begin a new chapter, since the next actual page of output might not yet include anything from the new chapter. Consider also the task of typesetting a dictionary or a membership roster; a well-designed reference book displays the current range of entries at the top of each page or pair of pages, so that it is easy for readers to thumb through the book when they are searching for isolated words or names. But TEX’s asynchronous output mechanism makes it difficult, if not impossible, to determine just what range of entries is actually present on a page. Ä Ä Therefore TEX provides a way to put “marks” into a list; these marks inform the output routine about the range of information on each page. The general idea is that you can say \mark{hmark texti} in the midst of the information you are typesetting, where the hmark texti is a token list that is expanded as in the commands \edef, \message, etc. TEX puts an internal representation of the mark text into the list it is building; then later on, when a completed page is packed into \box255, TEX allows the output routine to refer to the first and last mark texts on that page. Ä Ä The best way to think of this is probably to imagine that TEX generates an arbitrarily long vertical list of boxes, glue, and other items such as penalties and marks. Somehow that long vertical list gets divided up into pages, and the pages are made available to the output routine, one at a time. Whenever a page is put in \box255, TEX sets up the value of three quantities that act essentially like macros: \botmark is the mark text most recently encountered on the page that was just boxed; \firstmark is the mark text that was first encountered on the page that was just boxed; \topmark has the value that \botmark had just before the current page was boxed. Before the first page, all three of these are null, i.e., they expand to nothing. When there is no mark on a page, all three are equal to the previous \botmark. Ä Ä For example, suppose that your manuscript includes exactly four marks, and that the pages are broken in such a way that \mark{α} happens to fall on page 2, \mark{β} and \mark{γ} on page 4, and \mark{δ} on page 5. Then On page 1 2 3 4 5 6 \topmark is null null α α γ δ \firstmark is null α α β δ δ \botmark is null α α γ δ δ Chapter 23: Output Routines Ä Ä When you use a \mark command in vertical mode, TEX puts a mark into the main vertical list. When you use a \mark command in horizontal mode, TEX treats it as vertical mode material like \vadjust and \insert; i.e., after the paragraph has been broken into lines, each mark will go into the main vertical list just after the box for the line where that mark originally appeared. If you use \mark in restricted horizontal mode, the mark may migrate out to the enclosing vertical list in the same way that \insert and \vadjust items do (see Chapter 24); but a mark that is locked too deeply inside a box will not migrate, so it will never appear as a \firstmark or \botmark. Similarly, a \mark that occurs in internal vertical mode goes into a vbox, and it is not accessible in the main vertical list. Ä Ä Chapter 15 discusses the \vsplit command, which allows you to break up vertical lists by yourself. This operation sometimes provides a useful alternative to TEX’s ordinary page-building mechanism. For example, if you simply want to typeset some material in two columns of equal height, you can put that material into a vbox, then \vsplit the box into two pieces; no output routine is needed at all. The \vsplit operation sets up the values of two macro-like quantities that were not mentioned in Chapter 15: \splitfirstmark and \splitbotmark expand to the mark texts of the first and last marks that appear in the vertical list that was split off by the most recent \vsplit command. Both quantities are null if there were no such marks. The values of \topmark, \firstmark, \botmark, \splitfirstmark, and \splitbotmark are global; i.e., they are not affected by TEX’s grouping mechanism. Ä Ä Most dictionaries use the equivalent of \firstmark and \botmark to give guide words at the top of each pair of facing pages. For example, if the definition of the word ‘type’ starts on page 1387 and continues onto page 1388, the guide word on page 1387 (a right-hand page) will be ‘type’; but the guide word at the top of page 1388 (a left-hand page) will be the next word in the dictionary (e.g., ‘typecast’) even though the top of page 1388 is about ‘type’. Ä Ä The dictionary scheme works fine for dictionaries, since a reader should start reading each dictionary entry at its beginning. But a different scheme is appropriate for a technical book like the author’s Art of Computer Programming, where Section 1.2.8 (for example) starts in the middle of page 78, but the top of page 78 contains exercises 19–24 of Section 1.2.7. The headline at the top of page 78 refers to ‘1.2.7’, because that will help somebody who is searching for exercise 1.2.7–22. Notice that the dictionary convention would put ‘1.2.8’ at the top of page 78, but that would be appropriate only if Section 1.2.8 had begun exactly at the top of that page. Ä Ä Continuing this example from The Art of Computer Programming, let’s suppose that the TEX manuscript for Section 1.2.8 begins with a macro call like \beginsection 1.2.8. Fibonacci Numbers. How should \beginsection be defined? Here is one attempt: \def\beginsection #1. #2. {\sectionbreak \leftline{\sectionfont #1. #2} \mark{#1} \nobreak\smallskip\noindent} 259 260 Chapter 23: Output Routines The \sectionbreak macro should encourage TEX either to break the page at the current position, or to leave a goodly amount of blank space; e.g., \sectionbreak might be an abbreviation for ‘\penalty-200 \vskip18pt plus4pt minus6pt’. The \beginsection macro ends with commands that suppress indentation of the first paragraph in the section. But the thing that concerns us with respect to output routines is the \mark command that follows \leftline. In the example we have been considering, the beginning of Section 1.2.8 would insert ‘\mark{1.2.8}’ into the main vertical list just after the box containing the title of that section. Ä Ä Is such a \mark adequate? Unfortunately, no, not even if we assume for simplicity that at most one section begins on each page. The page that contains the beginning of Section 1.2.8 will then have \topmark=1.2.7 and \firstmark=1.2.8, regardless of whether or not the section starts at the very top of the page. What we want in this application is a cross between \topmark and \firstmark: something that will reflect the mark text that represents the state of affairs just after the first line of the page. And TEX doesn’t provide that. Ä Ä The solution is to emit the \mark just before the \sectionbreak, instead of just after the \leftline. Then \topmark will always reflect the truth about the section that is current at the top line. (Think about it.) Ä Ä However, the format for The Art of Computer Programming is more complex than this. On left-hand pages, the section number in the headline is supposed to reflect the situation at the top of the page, as we have just discussed, but on right-hand pages it is supposed to refer to the bottom of the page. Our solution to the previous problem made \topmark correct for the top, but it can make \botmark incorrect at the bottom. In order to satisfy both requirements, it is necessary to pack more information into the marks. Here’s one way to solve the problem: \def\beginsection #1. #2. {\mark{\currentsection \noexpand\else #1} \sectionbreak \leftline{\sectionfont #1. #2} \mark{#1\noexpand\else #1} \def\currentsection{#1} \nobreak\smallskip\noindent} \def\currentsection{} % the current section number The idea is to introduce two marks, one just before the section break and one just after the section has begun. Furthermore each mark has two parts; the mark just before the potential break between Sections 1.2.7 and 1.2.8 is ‘1.2.7\else 1.2.8’, while the one just after that potential break is ‘1.2.8\else 1.2.8’. It follows that the section number corresponding to the bottom of a page is the left component of \botmark; the section number corresponding to the top of a page is the right component of \topmark. The \rightheadline macro can make use of ‘\iftrue\botmark\fi’ to read the left component, and the \leftheadline macro can say ‘\expandafter\iffalse\topmark\fi’ to read the right component. Ä Äx EXERCISE 23.5 B. C. Dull used a construction very much like the one above, but he put the second \mark just before the \leftline instead of just after it. What went wrong? Chapter 23: Output Routines Ä Äx EXERCISE 23.6 The marks in the previous construction have the form ‘α\else β’, where α and β are two independent pieces of information. The ‘\else’ makes it possible to select either α or β by means of \iftrue and \iffalse. Generalize this idea: Suppose that you have an application in which marks are supposed to carry five independent pieces of information, and that each mark has the form ‘α0 \or α1 \or α2 \or α3 \or α4 ’. Explain how to select any one of the five α’s from such a mark. Ä Ä Let’s conclude our discussion of output routines by considering an application to indexes, such as the index to this manual that appears in Appendix I. The most complicated entries in such an index will look something like this: Main entry, 4, 6, 8–10, 12, 14–16, 18–22, 24–28, 30. first subsidiary entry, 1–3, 6, 10–11, 15, 21, 24, 28. second subsidiary entry, 1, 3, 6–7, 10, 15, 21, 25, 28, 31. Main entries and subsidiary entries are typeset ragged-right, with two ems of hanging indentation after the first line; subsidiary entries are indented one em on the first line. Our goal will be to typeset such material from input that looks like this: \beginindex ... Main entry, 4, 6, 8--10, 12, 14--16, 18--22, 24--28, 30. \sub first subsidiary entry, 1--3, 6, 10--11, 15, 21, 24, 28. \sub second subsidiary entry, 1, 3, 6--7, 10, 15, 21, 25, % 28, 31. ... \endindex where ‘...’ stands for other entries. Each line of input normally specifies one main entry or one subsidiary entry; if an entry is so long that it doesn’t fit on a single input line, ‘Ã%’ is typed at the end of the line so that it merges with the following one. Ä Ä The interesting thing about this index problem is that it is desirable to set up a system of marks so that the output routine can insert special lines of text when an entry has been broken between columns or pages. For example, if a page break occurs between any of the six lines of typeset output shown above, the output routine should emit the special line Main entry (continued ): and if a page break occurs within a subsidiary entry, an additional special line subsidiary entry (continued ): should also appear. The solution below produces marks so that \botmark will be null if a break occurs between main entries; it will be ‘Main entry’ if a break occurs after lines 1, 2, or 4 of the six example output lines; it will be ‘Main entry\sub first subsidiary entry’ if a break occurs after line 3 (within the first subsidiary entry); and it will be ‘Main entry\sub second subsidiary entry’ if a break occurs after line 5. 261 262 Chapter 23: Output Routines Ä Ä The reader may wish to try solving this problem before looking at the solution, because it will then be easier to appreciate the subtler issues that are involved. (Go ahead: Try to define a macro \beginindex that does the ragged-right setting and produces the specified marks. Turn back to the previous page to study the problem carefully, before peeking at the answer.) \def\beginindex{\begingroup \parindent=1em \maxdepth=\maxdimen \def\par{\endgraf \futurelet\next\inxentry} \obeylines \everypar={\hangindent 2\parindent} \exhyphenpenalty=10000 \raggedright} \def\inxentry{\ifx\next\sub \let\next=\subentry \else\ifx\next\endindex \let\next=\vfill \else\let\next=\mainentry \fi\fi \next} \def\endindex{\mark{}\break\endgroup} \let\sub=\indent \newtoks\maintoks \newtoks\subtoks \def\mainentry#1,{\mark{}\noindent \maintoks={#1}\mark{\the\maintoks}#1,} \def\subentry\sub#1,{\mark{\the\maintoks}\indent \subtoks={#1}\mark{\the\maintoks\sub\the\subtoks}#1,} Even if you have read this solution, you probably want an explanation of what it does, because it uses “TEXtics” that have not appeared before in this manual. 1) The \beginindex macro uses \begingroup to keep other changes local; thus, it won’t be necessary to restore \parindent and \maxdepth, etc., to their former values when the index is finished. The \maxdepth parameter is set to \maxdimen, which is essentially infinite, so that \box255 will have the true depth of the last box that it contains; we will use this fact below. (It is safe to disable \maxdepth in this way, since the entries in an index can be assumed to have reasonably small depth.) Notice that \obeylines is used, so that \par will effectively be inserted at the end of every line of input. The meaning of \par is changed so that it does more than usual: First it does \endgraf, which is TEX’s ordinary \par operation; then it sets \next to the first token of the next line, after which the macro \inxentry will be expanded. 2) When \inxentry comes into play it looks at \next to decide what to do. There are three cases: If \next is ‘\sub’, the line will be treated as a subsidiary entry; if \next is ‘\endindex’, the next commands executed will be ‘\vfill\mark{}\break \endgroup’; otherwise the line will be treated as a main entry. 3) The text of a main entry is put into parameter #1 of \mainentry; this parameter is delimited by a comma. The first thing that \mainentry does is ‘\mark{}’, which clears the mark in case of a break between entries. Then comes ‘\noindent’, which causes TEX to go into horizontal mode and to emit \parskip glue. (The \parskip glue will be a legal breakpoint between lines; it will later be followed by interline glue, when the first line of the main entry has been typeset by TEX’s paragraphing routine.) Then another \mark is put into the paragraph itself; this one contains the text of the main entry, and a \toks register called \maintoks is used to inhibit expansion of the mark text. When the paragraph is completed and broken into lines, this particular mark will immediately follow the box for the paragraph’s first line, so it will be the \botmark if a page break occurs anywhere within the paragraph. Chapter 23: Output Routines 4) A similar construction is used for \subentry, but the mark is more complicated. The \maintoks register will still contain the main entry. The text for the subsidiary entry is added using another token list register, \subtoks. Since \sub has been defined to equal \indent, it will not be expanded in this \mark. Ä Ä The macros just defined will typeset entries that contain the necessary marks; now we must construct an output routine that uses these marks in the desired way, to insert new lines that say ‘(continued )’ as mentioned above. Again, the reader is advised to try solving this problem before looking at the following solution. \output={\dimen0=\dp255 \normaloutput \expandafter\inxcheck\botmark\sub\end} \def\inxcheck#1\sub#2\end{\def\next{#1}% \ifx\next\empty % do nothing if \botmark is null \else\noindent #1\continued % ‘Main entry (continued):’ \def\next{#2}% \ifx\next\empty % nothing more if \botmark has no \sub \else\let\sub=\continued \indent #2\fi \advance\dimen0 by-\prevdepth \kern\dimen0 \fi} \def\continued{ ({\it continued}\thinspace):\endgraf} This coding is a bit more subtle than usual. It assumes that \normaloutput takes care of shipping out \box255 (possibly putting it into multicolumn format) and advancing the page number; then comes new stuff, which is performed by \inxcheck. The \inxcheck macro is invoked in an interesting way that allows \botmark to be separated into its components. If \botmark is null, argument #1 to \inxcheck will be null; hence \next will be found equivalent to \empty. (Plain TEX says ‘\def\empty{}’ in order to accommodate situations like this.) If \botmark doesn’t contain the token \sub, argument #1 will be the contents of \botmark while #2 will be null. Otherwise, if \botmark has the form α\sub β, argument #1 will be α and #2 will be ‘β\sub’. Ä Ä If \botmark isn’t null, the \inxcheck macro produces one or more lines of text that will be contributed to TEX’s main vertical list at the position of the page break. And here’s where the most subtle point arises: There will be interline glue at the page break, computed on the basis of the depth of the box that preceded the break. That depth is known to the output routine, since it’s the depth of \box255. (The value of \maxdepth was made infinite for precisely this reason.) Therefore the \inxcheck macro can insert a \kern to compensate for the difference in depth between the old box and the one that will be inserted before the interline glue that has already been computed. Without this \kern, the spacing would be wrong. The reader should study this example carefully, to understand the reasoning behind the \kern command, before designing an output routine that inserts new boxes between random lines of output. Ä Äx EXERCISE 23.7 Modify this construction so that continuation lines are inserted only in the left columns of even-numbered pages, assuming two-column format. Ä Äx EXERCISE 23.8 True or false: The \inxcheck macro in this example contributes at most two lines of output to the main vertical list. 263 264 Chapter 23: Output Routines Ä Ä When TEX sees an \end command, it terminates the job only if the main vertical list has been entirely output and if \deadcycles=0. Otherwise it inserts the equivalent of \line{} \vfill \penalty-’10000000000 into the main vertical list, and prepares to read the ‘\end’ token again. This has the effect of invoking the output routine repeatedly until everything has been shipped out. In particular, the last column of two-column format will not be lost. Ä Ä It is possible to devise output routines that always leave a residue on the main vertical list, yet they never allow \deadcycles to increase. In such a case TEX will never come to an end! An output routine can recognize that it is being invoked by TEX’s endgame, because of the highly negative \outputpenalty caused by the special \penalty-’10000000000. At such times the output routine should modify its behavior, if necessary, so that a happy ending will ensue. Chapter 23: Output Routines I think you will like them, when you shall see them on a beautiful quarto page, where a neat rivulet of text shall meander through a meadow of margin. ’Fore Gad they will be the most elegant things of their kind! — RICHARD BRINSLEY SHERIDAN, The School for Scandal (1777) The influence of technical changes upon outputs through variation in the general investment level is so small that actually it could have been neglected. — WASSILY W. LEONTIEF, The Structure of American Economy, 1919–1929 (1941) 265 (page 266) 24 Summary of Vertical Mode Chapter 24: Summary of Vertical Mode The whole TEX language has been presented in the previous chapters; we have finally reached the end of our journey into previously uncharted territory. Hurray! Victory! Now it is time to take a more systematic look at what we have encountered: to consider the facts in an orderly manner, rather than to mix them up with informal examples and applications as we have been doing. A child learns to speak a language before learning formal rules of grammar, but the rules of grammar come in handy later on when the child reaches adulthood. The purpose of this chapter—and of the two chapters that follow—is to present a precise and concise summary of the language that TEX understands, so that mature users will be able to communicate as effectively as possible with the machine. We will be concerned in these chapters solely with TEX’s primitive operations, rather than with the higher-level features of plain TEX format that most people deal with. Therefore novice users should put off reading Chapters 24–26 until they feel a need to know what goes on inside the computer. Appendix B contains a summary of plain TEX, together with a ready-reference guide to the things that most people want to know about TEX usage. The best way to get an overview of TEX from a high level is to turn to the opening pages of Appendix B. Our purpose here, however, is to survey the low-level parts of TEX on which higher-level superstructures have been built, in order to provide a detailed reference for people who do need to know the details. The remainder of this chapter is set in small type, like that of the present paragraph, since it is analogous to material that is marked “doubly dangerous” in other chapters. Instead of using dangerous bend signs repeatedly, let us simply agree that Chapters 24–26 are dangerous by definition. TEX actually has a few features that didn’t seem to be worth mentioning in previous chapters, so they will be introduced here as part of our complete survey. If there is any disagreement between something that was said previously and something that will be said below, the facts in the present chapter and its successors should be regarded as better approximations to the truth. We shall study TEX’s digestive processes, i.e., what TEX does with the lists of tokens that arrive in its “stomach.” Chapter 7 has described the process by which input files are converted to lists of tokens in TEX’s “mouth,” and Chapter 20 explained how expandable tokens are converted to unexpandable ones in TEX’s “gullet” by a process similar to regurgitation. When unexpandable tokens finally reach TEX’s gastrointestinal tract, the real activity of typesetting begins, and that is what we are going to survey in these summary chapters. Each token that arrives in TEX’s tummy is considered to be a command that the computer will obey. For example, the letter ‘L’ is a command to typeset an ‘L’ in the current font; ‘\par’ tells TEX to finish a paragraph. TEX is always in one of six modes, as described in Chapter 13, and a command sometimes means different things in different modes. The present chapter is about vertical mode (and internal vertical mode, which is almost the same): We shall discuss TEX’s response to every primitive command, when that command occurs in vertical mode. Chapters 25 and 26 characterize horizontal mode and math mode in a similar way, but those chapters are shorter than this one because many commands have the same behavior in all modes; the rules for such commands will not be repeated thrice, they will appear only once. 267 268 Chapter 24: Summary of Vertical Mode Some commands have arguments. In other words, one or more of the tokens that follow a command might be used to modify that command’s behavior, and those tokens are not considered to be commands themselves. For example, when TEX processes the sequence of tokens that corresponds to ‘\dimen2=2.5pt’, it considers only the first token ‘\dimen’ to be a command; the next tokens are swept up as part of the operation, because TEX needs to know what \dimen register is to be set equal to what hdimeni value. We shall define TEX’s parts of speech by using a modified form of the grammatical notation that was introduced about 1960 by John Backus and Peter Naur for the definition of computer languages. Quantities in angle brackets will either be explained in words or they will be defined by syntax rules that show exactly how they are formed from other quantities. For example, hunit of measurei −→ hoptional spacesihinternal uniti | hoptional trueihphysical uniti defines a hunit of measurei to be either an occurrence of hoptional spacesi followed by an hinternal uniti, or hoptional truei followed by hphysical uniti. The symbol ‘ −→ ’ in a syntax rule means “is defined to be,” and ‘ | ’ means “or.” Sometimes a syntax rule is recursive, in the sense that the right-hand side of the definition involves the quantity being defined. For example, the rule hoptional spacesi −→ hemptyi | hspace tokenihoptional spacesi defines the grammatical quantity called hoptional spacesi to be either hemptyi, or a hspace tokeni followed by hoptional spacesi. The quantity hemptyi stands for “nothing,” i.e., for no tokens at all; hence the syntax rule just given is a formalized way of saying that hoptional spacesi stands for a sequence of zero or more spaces. The alternatives on the right-hand side of a syntax rule need not consist entirely of quantities in angle brackets. Explicit tokens can be used as well. For example, the rule hplus or minusi −→ +12 | -12 says that hplus or minusi stands for a character token that is either a plus sign or a minus sign, with category code 12. We shall use a special convention for keywords, since the actual syntax of a keyword is somewhat technical. Letters in typewriter type like ‘ pt ’ will stand for hoptional spacesihp or Piht or Ti, where hp or Pi denotes any non-active character token for either p or P (independent of the category code), and where ht or Ti is similar. When a control sequence like ‘\dimen’ is used in the syntax rules below, it stands for any token whose current meaning is the same as the meaning that \dimen had when TEX started up. Other tokens can be given this same meaning, using \let or \futurelet, and the meaning of the control sequence \dimen itself may be redefined by the user, but the syntax rules take no note of this; they just use ‘\dimen’ as a way of referring to a particular primitive command of TEX. (This notation is to be distinguished from ‘ dimen ’, which stands for the control sequence token whose actual name is dimen; see Chapter 7.) Chapter 24: Summary of Vertical Mode Control sequences sometimes masquerade as characters, if their meaning has been assigned by \let or \futurelet. For example, Appendix B says \let\bgroup={ \let\egroup=} and these commands make \bgroup and \egroup act somewhat like left and right curly braces. Such control sequences are called “implicit characters”; they are interpreted in the same way as characters, when TEX acts on them as commands, but not always when they appear in arguments to commands. For example, the command ‘\let\plus=+’ does not make \plus an acceptable substitute for the character token ‘+ 12 ’ in the syntax rule for hplus or minusi given above, nor does the command ‘\let\p=p’ make \p acceptable as part of the keyword pt . When TEX’s syntax allows both explicit and implicit characters, the rules below will be careful to say so, explicitly. The quantity hspace tokeni, which was used in the syntax of hoptional spacesi above, stands for an explicit or implicit space. In other words, it denotes either a character token of category 10, or a control sequence or active character whose current meaning has been made equal to such a token by \let or \futurelet. It will be convenient to use the symbols ‘{’, ‘}’, and ‘’ to stand for any explicit or implicit character tokens of the respective categories 1, 2, and 3, whether or not the actual character codes are braces or dollar signs. Thus, for example, plain TEX’s \bgroup is an example of a ‘{’, and so are the tokens ‘{1 ’ and ‘(1 ’; but ‘{12 ’ is not. The last few paragraphs can be summarized by saying that the alternatives on the right-hand sides of TEX’s formal syntax rules are made from one or more of the following things: (1) syntactic quantities like hoptional spacesi; (2) explicit character tokens like +12 ; (3) keywords like pt ; (4) control sequence names like \dimen; or (5) the special symbols {, }, . Let us begin our study of TEX’s syntax by discussing the precise meanings of quantities like hnumberi, hdimeni, and hgluei that occur frequently as arguments to commands. The most important of these is hnumberi, which specifies an integer value. Here’s exactly what a hnumberi is: hnumberi −→ hoptional signsihunsigned numberi hoptional signsi −→ hoptional spacesi | hoptional signsihplus or minusihoptional spacesi hunsigned numberi −→ hnormal integeri | hcoerced integeri hnormal integeri −→ hinternal integeri | hinteger constantihone optional spacei | ’12 hoctal constantihone optional spacei | "12 hhexadecimal constantihone optional spacei | ‘12 hcharacter tokenihone optional spacei hinteger constanti −→ hdigiti | hdigitihinteger constanti hoctal constanti −→ hoctal digiti | hoctal digitihoctal constanti hhexadecimal constanti −→ hhex digiti | hhex digitihhexadecimal constanti hoctal digiti −→ 012 | 112 | 212 | 312 | 412 | 512 | 612 | 712 hdigiti −→ hoctal digiti | 812 | 912 hhex digiti −→ hdigiti | A11 | B11 | C11 | D11 | E11 | F11 | A12 | B12 | C12 | D12 | E12 | F12 hone optional spacei −→ hspace tokeni | hemptyi hcoerced integeri −→ hinternal dimeni | hinternal gluei 269 270 Chapter 24: Summary of Vertical Mode The value of a hnumberi is the value of the corresponding hunsigned numberi, times −1 for every minus sign in the hoptional signsi. An alphabetic constant denotes the character code in a hcharacter tokeni; TEX does not expand this token, which should either be a (character code, category code) pair, or an active character, or a control sequence whose name consists of a single character. (See Chapter 20 for a complete list of all situations in which TEX does not expand tokens.) An hinteger constanti must not be immediately followed by a hdigiti; in other words, if several digits appear consecutively, they are all considered to be part of the same hinteger constanti. A similar remark applies to the quantities hoctal constanti and hhexadecimal constanti. The quantity hone optional spacei is hemptyi only if it has to be; i.e., TEX looks for hone optional spacei by reading a token and backing up if a hspace tokeni wasn’t there. Ä Äx EXERCISE 24.1 Can you think of a reason why you might want ‘A12 ’ to be a hhex digiti even though the letter A has category 11? (Don’t worry if your answer is “no.” ) The definition of hnumberi is now complete except for the three quantities called hinternal integeri, hinternal dimeni, and hinternal gluei, which will be explained later; they represent things like parameters and registers. For example, \count1 and \tolerance and \hyphenchar\tenrm are internal integers; \dimen10 and \hsize and \fontdimen6\tenrm are internal dimensions; \skip100 and \baselineskip and \lastskip are internal glue values. An internal dimension can be “coerced” to be an integer by assuming units of scaled points. For example, if \hsize=100pt and if \hsize is used in the context of a hnumberi, it denotes the integer value 6553600. Similarly, an internal glue value can be coerced to be an integer by first coercing it to be a dimension (omitting the stretchability and shrinkability), then coercing that dimension. Let’s turn now to the syntax for hdimeni, and for hmudimeni its cousin: hdimeni −→ hoptional signsihunsigned dimeni hunsigned dimeni −→ hnormal dimeni | hcoerced dimeni hcoerced dimeni −→ hinternal gluei hnormal dimeni −→ hinternal dimeni | hfactorihunit of measurei hfactori −→ hnormal integeri | hdecimal constanti hdecimal constanti −→ .12 | ,12 | hdigitihdecimal constanti | hdecimal constantihdigiti hunit of measurei −→ hoptional spacesihinternal uniti | hoptional trueihphysical unitihone optional spacei hinternal uniti −→ em hone optional spacei | ex hone optional spacei | hinternal integeri | hinternal dimeni | hinternal gluei hoptional truei −→ true | hemptyi hphysical uniti −→ pt | pc | in | bp | cm | mm | dd | cc | sp hmudimeni −→ hoptional signsihunsigned mudimeni hunsigned mudimeni −→ hnormal mudimeni | hcoerced mudimeni hcoerced mudimeni −→ hinternal mugluei hnormal mudimeni −→ hfactorihmu uniti hmu uniti −→ hoptional spacesihinternal mugluei | mu hone optional spacei When ‘true’ is present, the factor is multiplied by 1000 and divided by the \mag parameter. Physical units are defined in Chapter 10; mu is explained in Chapter 18. Chapter 24: Summary of Vertical Mode Encouraged by our success in mastering the precise syntax of the quantities hnumberi, hdimeni, and hmudimeni, let’s tackle hgluei and hmugluei: hgluei −→ hoptional signsihinternal gluei | hdimenihstretchihshrinki hstretchi −→ plus hdimeni | plus hfil dimeni | hoptional spacesi hshrinki −→ minus hdimeni | minus hfil dimeni | hoptional spacesi hfil dimeni −→ hoptional signsihfactorihfil unitihoptional spacesi hfil uniti −→ fil | hfil uniti l hmugluei −→ hoptional signsihinternal mugluei | hmudimenihmustretchihmushrinki hmustretchi −→ plus hmudimeni | plus hfil dimeni | hoptional spacesi hmushrinki −→ minus hmudimeni | minus hfil dimeni | hoptional spacesi TEX makes a large number of internal quantities accessible so that a format designer can influence TEX’s behavior. Here is a list of all these quantities, except for the parameters (which will be listed later). hinternal integeri −→ hinteger parameteri | hspecial integeri | \lastpenalty | hcountdef tokeni | \counth8-bit numberi | hcodenameih8-bit numberi | hchardef tokeni | hmathchardef tokeni | \parshape | \inputlineno | \hyphencharhfonti | \skewcharhfonti | \badness hspecial integeri −→ \spacefactor | \prevgraf | \deadcycles | \insertpenalties hcodenamei −→ \catcode | \mathcode | \lccode | \uccode | \sfcode | \delcode hfonti −→ hfontdef tokeni | \font | hfamily memberi hfamily memberi −→ hfont rangeih4-bit numberi hfont rangei −→ \textfont | \scriptfont | \scriptscriptfont hinternal dimeni −→ hdimen parameteri | hspecial dimeni | \lastkern | hdimendef tokeni | \dimenh8-bit numberi | hbox dimensionih8-bit numberi | \fontdimenhnumberihfonti hspecial dimeni −→ \prevdepth | \pagegoal | \pagetotal | \pagestretch | \pagefilstretch | \pagefillstretch | \pagefilllstretch | \pageshrink | \pagedepth hbox dimensioni −→ \ht | \wd | \dp hinternal gluei −→ hglue parameteri | \lastskip | hskipdef tokeni | \skiph8-bit numberi hinternal mugluei −→ hmuglue parameteri | \lastskip | hmuskipdef tokeni | \muskiph8-bit numberi A hcountdef tokeni is a control sequence token in which the control sequence’s current meaning has been defined by \countdef; the other quantities hdimendef tokeni, etc., are defined similarly. A hfontdef tokeni refers to a definition by \font, or it can be the predefined font identifier called \nullfont. When a hcountdef tokeni is used as an internal integer, it denotes the value of the corresponding \count register, and similar statements hold for hdimendef tokeni, hskipdef tokeni, hmuskipdef tokeni. When a hchardef tokeni or hmathchardef tokeni is used as an internal integer, it denotes the value in the \chardef or \mathchardef itself. An h8-bit numberi is a hnumberi whose value is between 0 and 28 − 1 = 255; a h4-bit numberi is similar. 271 272 Chapter 24: Summary of Vertical Mode TEX allows \spacefactor to be an internal integer only in horizontal modes; \prevdepth can be an internal dimension only in vertical modes; \lastskip can be hinternal mugluei only in math mode when the current math list ends with a muglue item; and \lastskip cannot be hinternal gluei in such a case. When \parshape is used as an internal integer, it denotes only the number of controlled lines, not their sizes or indentations. The seven special dimensions \pagetotal, \pagestretch, and so on are all zero when the current page contains no boxes, and \pagegoal is \maxdimen at such times (see Chapter 15). From the syntax rules just given, it’s possible to deduce exactly what happens to spaces when they are in the vicinity of numerical quantities: TEX allows a hnumberi or hdimeni to be preceded by arbitrarily many spaces, and to be followed by at most one space; however, there is no optional space after a hnumberi or hdimeni that ends with an unexpandable control sequence. For example, if TEX sees ‘\space\space24\space\space’ when it is looking for a hnumberi, it gobbles up the first three spaces, but the fourth one survives; similarly, one space remains when ‘24pt\space\space’ and ‘\dimen24\space\space’ and ‘\pagegoal\space’ are treated as hdimeni values. Ä Äx EXERCISE 24.2 Is ‘24\space\space pt’ a legal hdimeni? Ä Äx EXERCISE 24.3 Is there any difference between ‘+\baselineskip’, ‘- -\baselineskip’, and ‘1\baselineskip’, when TEX reads them as hgluei? Ä Äx EXERCISE 24.4 What hgluei results from "DD DDPLUS2,5 \spacefactor\space, assuming the conventions of plain TEX, when \spacefactor equals 1000? Let’s turn now to TEX’s parameters, which the previous chapters have introduced one at a time; it will be convenient to assemble them all together. An hinteger parameteri is one of the following tokens: \pretolerance (badness tolerance before hyphenation) \tolerance (badness tolerance after hyphenation) \hbadness (badness above which bad hboxes will be shown) \vbadness (badness above which bad vboxes will be shown) \linepenalty (amount added to badness of every line in a paragraph) \hyphenpenalty (penalty for line break after discretionary hyphen) \exhyphenpenalty (penalty for line break after explicit hyphen) \binoppenalty (penalty for line break after binary operation) \relpenalty (penalty for line break after math relation) \clubpenalty (penalty for creating a club line at bottom of page) \widowpenalty (penalty for creating a widow line at top of page) \displaywidowpenalty (ditto, before a display) \brokenpenalty (penalty for page break after a hyphenated line) \predisplaypenalty (penalty for page break just before a display) \postdisplaypenalty (penalty for page break just after a display) \interlinepenalty (additional penalty for page break between lines) \floatingpenalty (penalty for insertions that are split) Chapter 24: Summary of Vertical Mode \outputpenalty (penalty at the current page break) \doublehyphendemerits (demerits for consecutive broken lines) \finalhyphendemerits (demerits for a penultimate broken line) \adjdemerits (demerits for adjacent incompatible lines) \looseness (change to the number of lines in a paragraph) \pausing (positive if pausing after each line is read from a file) \holdinginserts (positive if insertions remain dormant in output box) \tracingonline (positive if showing diagnostic info on the terminal) \tracingmacros (positive if showing macros as they are expanded) \tracingstats (positive if showing statistics about memory usage) \tracingparagraphs (positive if showing line-break calculations) \tracingpages (positive if showing page-break calculations) \tracingoutput (positive if showing boxes that are shipped out) \tracinglostchars (positive if showing characters not in the font) \tracingcommands (positive if showing commands before they are executed) \tracingrestores (positive if showing deassignments when groups end) \language (the current set of hyphenation rules) \uchyph (positive if hyphenating words beginning with capital letters) \lefthyphenmin (smallest fragment at beginning of hyphenated word) \righthyphenmin (smallest fragment at end of hyphenated word) \globaldefs (nonzero if overriding \global specifications) \defaulthyphenchar (\hyphenchar value when a font is loaded) \defaultskewchar (\skewchar value when a font is loaded) \escapechar (escape character in the output of control sequence tokens) \endlinechar (character placed at the right end of an input line) \newlinechar (character that starts a new output line) \maxdeadcycles (upper bound on \deadcycles) \hangafter (hanging indentation changes after this many lines) \fam (the current family number) \mag (magnification ratio, times 1000) \delimiterfactor (ratio for variable delimiters, times 1000) \time (current time of day in minutes since midnight) \day (current day of the month) \month (current month of the year) \year (current year of our Lord) \showboxbreadth (maximum items per level when boxes are shown) \showboxdepth (maximum level when boxes are shown) \errorcontextlines (maximum extra context shown when errors occur) The first few of these parameters have values in units of “badness” and “penalties” that affect line breaking and page breaking. Then come demerit-oriented parameters; demerits are essentially given in units of “badness squared,” so those parameters tend to have larger values. By contrast, the next few parameters (\looseness, \pausing, etc.) generally have quite small values (either −1 or 0 or 1 or 2). Miscellaneous parameters complete the set. TEX computes the date and time when it begins a job, if the operating system provides such information; but afterwards the clock does not keep ticking: The user can change \time just like any ordinary parameter. Chapter 10 points out that \mag must not be changed after TEX is committed to a particular magnification. 273 274 Chapter 24: Summary of Vertical Mode A hdimen parameteri is one of the following: \hfuzz (maximum overrun before overfull hbox messages occur) \vfuzz (maximum overrun before overfull vbox messages occur) \overfullrule (width of rules appended to overfull boxes) \emergencystretch (reduces badnesses on final pass of line-breaking) \hsize (line width in horizontal mode) \vsize (page height in vertical mode) \maxdepth (maximum depth of boxes on main pages) \splitmaxdepth (maximum depth of boxes on split pages) \boxmaxdepth (maximum depth of boxes on explicit pages) \lineskiplimit (threshold where \baselineskip changes to \lineskip) \delimitershortfall (maximum space not covered by a delimiter) \nulldelimiterspace (width of a null delimiter) \scriptspace (extra space after subscript or superscript) \mathsurround (kerning before and after math in text) \predisplaysize (length of text preceding a display) \displaywidth (length of line for displayed equation) \displayindent (indentation of line for displayed equation) \parindent (width of \indent) \hangindent (amount of hanging indentation) \hoffset (horizontal offset in \shipout) \voffset (vertical offset in \shipout) And the possibilities for hglue parameteri are: \baselineskip (desired glue between baselines) \lineskip (interline glue if \baselineskip isn’t feasible) \parskip (extra glue just above paragraphs) \abovedisplayskip (extra glue just above displays) \abovedisplayshortskip (ditto, following short lines) \belowdisplayskip (extra glue just below displays) \belowdisplayshortskip (ditto, following short lines) \leftskip (glue at left of justified lines) \rightskip (glue at right of justified lines) \topskip (glue at top of main pages) \splittopskip (glue at top of split pages) \tabskip (glue between aligned entries) \spaceskip (glue between words, if nonzero) \xspaceskip (glue between sentences, if nonzero) \parfillskip (additional \rightskip at end of paragraphs) Finally, there are three permissible hmuglue parameteri tokens: \thinmuskip (thin space in math formulas) \medmuskip (medium space in math formulas) \thickmuskip (thick space in math formulas) All of these quantities are explained in more detail somewhere else in this book, and you can use Appendix I to find out where. Chapter 24: Summary of Vertical Mode TEX also has parameters that are token lists. Such parameters do not enter into the definitions of hnumberi and such things, but we might as well list them now so that our tabulation of parameters is complete. A htoken parameteri is any of: \output (the user’s output routine) \everypar (tokens to insert when a paragraph begins) \everymath (tokens to insert when math in text begins) \everydisplay (tokens to insert when display math begins) \everyhbox (tokens to insert when an hbox begins) \everyvbox (tokens to insert when a vbox begins) \everyjob (tokens to insert when the job begins) \everycr (tokens to insert after every \cr or nonredundant \crcr) \errhelp (tokens that supplement an \errmessage) That makes a total of 103 parameters of all five kinds. Ä Äx EXERCISE 24.5 Explain how \everyjob can be non-null when a job begins. It’s time now to return to our original goal, namely to study the commands that are obeyed by TEX’s digestive organs. Many commands are carried out in the same way regardless of the current mode. The most important commands of this type are called assignments, since they assign new values to the meaning of control sequences or to TEX’s internal quantities. For example, ‘\def\a{a}’ and ‘\parshape=1 5pt 100pt’ and ‘\advance\count20 by-1’ and ‘\font\ff = cmff at 20pt’ are all assignments, and they all have the same effect in all modes. Assignment commands often include an = sign, but in all cases this sign is optional; you can leave it out if you don’t mind the fact that the resulting TEX code might not look quite like an assignment. hassignmenti −→ hnon-macro assignmenti | hmacro assignmenti hnon-macro assignmenti −→ hsimple assignmenti | \globalhnon-macro assignmenti hmacro assignmenti −→ hdefinitioni | hprefixihmacro assignmenti hprefixi −→ \global | \long | \outer hequalsi −→ hoptional spacesi | hoptional spacesi =12 This syntax shows that every assignment can be prefixed by \global, but only macrodefinition assignments are allowed to be prefixed by \long or \outer. Incidentally, if the \globaldefs parameter is positive at the time of the assignment, a prefix of \global is automatically implied; but if \globaldefs is negative at the time of the assignment, a prefix of \global is ignored. If \globaldefs is zero (which it usually is), the appearance or nonappearance of \global determines whether or not a global assignment is made. hdefinitioni −→ hdefihcontrol sequenceihdefinition texti hdefi −→ \def | \gdef | \edef | \xdef hdefinition texti −→ hparameter textihleft braceihbalanced textihright bracei Here hcontrol sequencei denotes a token that is either a control sequence or an active character; hleft bracei and hright bracei are explicit character tokens whose category codes are respectively of types 1 and 2. The hparameter texti contains no hleft bracei or hright bracei tokens, and it obeys the rules of Chapter 20. All occurrences of 275 276 Chapter 24: Summary of Vertical Mode hleft bracei and hright bracei tokens within the hbalanced texti must be properly nested like parentheses. A \gdef command is equivalent to \global\def, and \xdef is equivalent to \global\edef. TEX reads the hcontrol sequencei and hparameter texti tokens and the opening hleft bracei without expanding them; it expands the hbalanced texti hright bracei tokens only in the case of \edef and \xdef. Several commands that we will study below have a syntax somewhat like that of a definition, but the hparameter texti is replaced by an arbitrary sequence of spaces and ‘\relax’ commands, and the hleft bracei token can be implicit: hfilleri −→ hoptional spacesi | hfilleri\relaxhoptional spacesi hgeneral texti −→ hfilleri{hbalanced textihright bracei The main purpose of a hgeneral texti is to specify the hbalanced texti inside. Many different kinds of assignments are possible, but they fall into comparatively few patterns, as indicated by the following syntax rules: hsimple assignmenti −→ hvariable assignmenti | harithmetici | hcode assignmenti | hlet assignmenti | hshorthand definitioni | hfontdef tokeni | hfamily assignmenti | hshape assignmenti | \readhnumberi to hoptional spacesihcontrol sequencei | \setboxh8-bit numberihequalsihfillerihboxi | \fonthcontrol sequenceihequalsihfile nameihat clausei | hglobal assignmenti hvariable assignmenti −→ hinteger variableihequalsihnumberi | hdimen variableihequalsihdimeni | hglue variableihequalsihgluei | hmuglue variableihequalsihmugluei | htoken variableihequalsihgeneral texti | htoken variableihequalsihfillerihtoken variablei harithmetici −→ \advancehinteger variableihoptional byihnumberi | \advancehdimen variableihoptional byihdimeni | \advancehglue variableihoptional byihgluei | \advancehmuglue variableihoptional byihmugluei | \multiplyhnumeric variableihoptional byihnumberi | \dividehnumeric variableihoptional byihnumberi hoptional byi −→ by | hoptional spacesi hinteger variablei −→ hinteger parameteri | hcountdef tokeni | \counth8-bit numberi hdimen variablei −→ hdimen parameteri | hdimendef tokeni | \dimenh8-bit numberi hglue variablei −→ hglue parameteri | hskipdef tokeni | \skiph8-bit numberi hmuglue variablei −→ hmuglue parameteri | hmuskipdef tokeni | \muskiph8-bit numberi htoken variablei −→ htoken parameteri | htoksdef tokeni | \toksh8-bit numberi hnumeric variablei −→ hinteger variablei | hdimen variablei | hglue variablei | hmuglue variablei Chapter 24: Summary of Vertical Mode hcode assignmenti −→ hcode nameih8-bit numberihequalsihnumberi hlet assignmenti −→ \futurelethcontrol sequenceihtokenihtokeni | \lethcontrol sequenceihequalsihone optional spaceihtokeni hshorthand definitioni −→ \chardefhcontrol sequenceihequalsih8-bit numberi | \mathchardefhcontrol sequenceihequalsih15-bit numberi | hregisterdefihcontrol sequenceihequalsih8-bit numberi hregisterdefi −→ \countdef | \dimendef | \skipdef | \muskipdef | \toksdef hfamily assignmenti −→ hfamily memberihequalsihfonti hshape assignmenti −→ \parshapehequalsihnumberihshape dimensionsi The hnumberi at the end of a hcode assignmenti must not be negative, except in the case that a \delcode is being assigned. Furthermore, that hnumberi should be at most 15 for \catcode, 32768 for \mathcode, 255 for \lccode or \uccode, 32767 for \sfcode, and 224 − 1 for \delcode. In a hshape assignmenti for which the hnumberi is n, the hshape dimensionsi are hemptyi if n ≤ 0, otherwise they consist of 2n consecutive occurrences of hdimeni. TEX does not expand tokens when it scans the arguments of \let and \futurelet. Ä Äx EXERCISE 24.6 We discussed the distinction between explicit and implicit character tokens earlier in this chapter. Explain how you can make the control sequence \cs into an implicit space, using (a) \futurelet, (b) \let. All of the assignments mentioned so far will obey TEX’s grouping structure; i.e., the changed quantities will be restored to their former values when the current group ends, unless the change was global. The remaining assignments are different, since they affect TEX’s global font tables or hyphenation tables, or they affect certain control variables of such an intimate nature that grouping would be inappropriate. In all of the following cases, the presence or absence of \global as a prefix has no effect. hglobal assignmenti −→ hfont assignmenti | hhyphenation assignmenti | hbox size assignmenti | hinteraction mode assignmenti | hintimate assignmenti hfont assignmenti −→ \fontdimenhnumberihfontihequalsihdimeni | \hyphencharhfontihequalsihnumberi | \skewcharhfontihequalsihnumberi hat clausei −→ at hdimeni | scaled hnumberi | hoptional spacesi hhyphenation assignmenti −→ \hyphenationhgeneral texti | \patternshgeneral texti hbox size assignmenti −→ hbox dimensionih8-bit numberihequalsihdimeni hinteraction mode assignmenti −→ \errorstopmode | \scrollmode | \nonstopmode | \batchmode hintimate assignmenti −→ hspecial integerihequalsihnumberi | hspecial dimenihequalsihdimeni When a \fontdimen value is assigned, the hnumberi must be positive and not greater than the number of parameters in the font’s metric information file, unless that font information has just been loaded into TEX’s memory; in the latter case, you are allowed 277 278 Chapter 24: Summary of Vertical Mode to increase the number of parameters (see Appendix F). The hspecial integeri and hspecial dimeni quantities were listed above when we discussed internal integers and dimensions. When \prevgraf is set to a hnumberi, the number must not be negative. The syntax for hfile namei is not standard in TEX, because different operating systems have different conventions. You should ask your local system wizards for details on just how they have decided to implement file names. However, the following principles should hold universally: A hfile namei should consist of hoptional spacesi followed by explicit character tokens (after expansion). A sequence of six or fewer ordinary letters and/or digits followed by a space should be a file name that works in essentially the same way on all installations of TEX. Uppercase letters are not considered equivalent to their lowercase counterparts in file names; for example, if you refer to fonts cmr10 and CMR10, TEX will not notice any similarity between them, although it might input the same font metric file for both fonts. TEX takes precautions so that constructions like ‘\chardef\cs=10\cs’ and ‘\font\cs=name\cs’ won’t expand the second \cs until the assignments are done. Our discussion of assignments is complete except that the \setbox assignment involves a quantity called hboxi that has not yet been defined. Here is its syntax: hboxi −→ \boxh8-bit numberi | \copyh8-bit numberi | \lastbox | \vsplith8-bit numberi to hdimeni | \hboxhbox specificationi{hhorizontal mode materiali} | \vboxhbox specificationi{hvertical mode materiali} | \vtophbox specificationi{hvertical mode materiali} hbox specificationi −→ to hdimenihfilleri | spread hdimenihfilleri | hfilleri The \lastbox operation is not permitted in math modes, nor is it allowed in vertical mode when the main vertical list has been entirely contributed to the current page. But it is allowed in horizontal modes and in internal vertical mode; in such modes it refers to (and removes) the last item of the current list, provided that the last item is an hbox or vbox. The three last alternatives for a hboxi present us with a new situation: The hhorizontal mode materiali in an \hbox and the hvertical mode materiali in a \vbox can’t simply be swallowed up in one command like an h8-bit numberi or a hdimeni; thousands of commands may have to be executed before that box is constructed and before the \setbox command can be completed. Here’s what really happens: A command like \setboxhnumberi=\hbox tohdimeni{hhorizontal mode materiali} causes TEX to evaluate the hnumberi and the hdimeni, and to put those values on a “stack” for safe keeping. Then TEX reads the ‘{’ (which stands for an explicit or implicit begin-group character, as explained earlier), and this initiates a new level of grouping. At this point TEX enters restricted horizontal mode and proceeds to execute commands in that mode. An arbitrarily complex box can now be constructed; the fact that this box is eventually destined for a \setbox command has no effect on TEX’s behavior while the box is being built. Eventually, when the matching ‘}’ appears, TEX restores values that were changed by assignments in the group just ended; then it packages the hbox (using the size that was saved on the stack), and completes the \setbox command, returning to the mode it was in at the time of the \setbox. Chapter 24: Summary of Vertical Mode Let us now consider other commands that, like assignments, are obeyed in basically the same way regardless of TEX’s current mode. \relax. This is an easy one: TEX does nothing. }. This one is harder, because it depends on the current group. TEX should now be working on a group that began with {; and it knows why it started that group. So it does the appropriate finishing actions, undoes the effects of non-global assignments, and leaves the group. At this point TEX might leave its current mode and return to a mode that was previously in effect. \begingroup. When TEX sees this command, it enters a group that must be terminated by \endgroup, not by }. The mode doesn’t change. \endgroup. TEX should currently be processing a group that began with \begingroup. Quantities that were changed by non-global assignments in that group are restored to their former values. TEX leaves the group, but stays in the same mode. \show htokeni, \showbox h8-bit numberi, \showlists, \showthehinternal quantityi. These commands are intended to help you figure out what TEX thinks it is doing. The tokens following \showthe should be anything that can follow \the, as explained in Chapter 20. Ä Äx EXERCISE 24.7 Review the rules for what can follow \the in Chapter 20, and construct a formal syntax that defines hinternal quantityi in a way that fits with the other syntax rules we have been discussing. \shipouthboxi. After the hboxi is formed—possibly by constructing it explicitly and changing modes during the construction, as explained for \hbox earlier—its contents are sent to the dvi file (see Chapter 23). \ignorespaces hoptional spacesi. TEX reads (and expands) tokens, doing nothing until reaching one that is not a hspace tokeni. \afterassignmenthtokeni. The htokeni is saved in a special place; it will be inserted back into the input just after the next assignment command has been performed. An assignment need not follow immediately; if another \afterassignment is performed before the next assignment, the second one overrides the first. If the next assignment is a \setbox, and if the assigned hboxi is \hbox or \vbox or \vtop, the htokeni will be inserted just after the { in the box construction, not after the }; it will also come just before any tokens inserted by \everyhbox or \everyvbox. \aftergrouphtokeni. The htokeni is saved on TEX’s stack; it will be inserted back into the input just after the current group has been completed and its local assignments have been undone. If several \aftergroup commands occur in the same group, the corresponding commands will be scanned in the same order; for example, ‘{\aftergroup\a\aftergroup\b}’ yields ‘\a\b’. \uppercasehgeneral texti, \lowercasehgeneral texti. The hbalanced texti in the general text is converted to uppercase form or to lowercase form using the \uccode or \lccode table, as explained in Chapter 7; no expansion is done. Then TEX will read that hbalanced texti again. \messagehgeneral texti, \errmessagehgeneral texti. The balanced text (with expansion) is written on the user’s terminal, using the format of error messages in the 279 280 Chapter 24: Summary of Vertical Mode case of \errmessage. In the latter case the \errhelp tokens will be shown if they are nonempty and if the user asks for help. \openin h4-bit numberi hequalsi hfilenamei, \closein h4-bit numberi. These commands open or close the specified input stream, for use in \read assignments as explained in Chapter 20. \immediate\openouth4-bit numberihequalsihfilenamei, \immediate\closeout h4-bit numberi. The specified output stream is opened or closed, for use in \write commands, as explained in Chapter 21. \immediate\writehnumberihgeneral texti. The balanced text is written on the file that corresponds to the specified stream number, provided that such a file is open. Otherwise it is written on the user’s terminal and on the log file. (See Chapter 21; the terminal is omitted if the hnumberi is negative.) That completes the list of mode-independent commands, i.e., the commands that do not directly affect the lists that TEX is building. When TEX is in vertical mode or internal vertical mode, it is constructing a vertical list; when TEX is in horizontal mode or restricted horizontal mode, it is constructing a horizontal list; when TEX is in math mode or display math mode, it is constructing—guess what—a math list. In each of these cases we can speak of the “current list”; and there are some commands that operate in essentially the same way, regardless of the mode, except that they deal with different sorts of lists: \openouth4-bit numberihequalsihfilenamei, \closeouth4-bit numberi, \write hnumberihgeneral texti. These commands are recorded into a “whatsit” item, which is appended to the current list. The command will be performed later, during any \shipout that applies to this list, unless the list is part of a box inside leaders. \specialhgeneral texti. The balanced text is expanded and put into a “whatsit” item, which is appended to the current list. The text will eventually appear in the dvi file as an instruction to subsequent software (see Chapter 21). \penaltyhnumberi. A penalty item carrying the specified number is appended to the current list. In vertical mode, TEX also exercises the page builder (see below). \kernhdimeni, \mkernhmudimeni. A kern item carrying the specified dimension is appended to the current list. In vertical modes this denotes a vertical space; otherwise it denotes a horizontal space. An \mkern is allowed only in math modes. \unpenalty, \unkern, \unskip. If the last item on the current list is respectively of type penalty, kern, or glue (possibly including leaders), that item is removed from the list. However, like \lastbox, these commands are not permitted in vertical mode if the main vertical list-so-far has been entirely contributed to the current page, since TEX never removes items from the current page. \markhgeneral texti. The balanced text is expanded and put into a mark item, which is appended to the current list. The text may eventually become the replacement text for \topmark, \firstmark, \botmark, \splitfirstmark, and/or \splitbotmark, if this mark item ever gets into a vertical list. (Mark items can appear in horizontal lists and math lists, but they have no effect until they “migrate” out of their list. The migration process is discussed below and in Chapter 25.) \inserth8-bit numberihfilleri{hvertical mode materiali}; the h8-bit numberi must not be 255. The ‘{’ causes TEX to enter internal vertical mode and a new Chapter 24: Summary of Vertical Mode level of grouping. When the matching ‘}’ is sensed, the vertical list is put into an insertion item that is appended to the current list using the values of \splittopskip, \splitmaxdepth, and \floatingpenalty that were current in the group just ended. (See Chapter 15.) This insertion item leads ultimately to a page insertion only if it appears in TEX’s main vertical list, so it will have to “migrate” there if it starts out in a horizontal list or a math list. TEX also exercises the page builder (see below), after an \insert has been appended in vertical mode. \vadjusthfilleri{hvertical mode materiali}. This is similar to \insert; the constructed vertical list goes into an adjustment item that is appended to the current list. However, \vadjust is not allowed in vertical modes. When an adjustment item migrates from a horizontal list to a vertical list, the vertical list inside the adjustment item is “unwrapped” and put directly into the enclosing list. ∗ Almost everything we have discussed so far in this chapter could equally well have appeared in a chapter entitled “Summary of Horizontal Mode” or a chapter entitled “Summary of Math Mode,” because TEX treats all of the commands considered so far in essentially the same way regardless of the current mode. Chapters 25 and 26 are going to be a lot shorter than the present one, since it will be unnecessary to repeat all of the mode-independent rules. But now we come to commands that are mode-dependent; we shall conclude this chapter by discussing what TEX does with the remaining commands, when in vertical mode or internal vertical mode. One of the things characteristic of vertical mode is the page-building operation described in Chapter 15. TEX periodically takes material that has been put on the main vertical list and moves it from the “contribution list” to the “current page.” At such times the output routine might be invoked. We shall say that TEX exercises the page builder whenever it tries to empty the current contribution list. The concept of contribution list exists only in the outermost vertical mode, so nothing happens when TEX exercises the page builder in internal vertical mode. Another thing characteristic of vertical modes is the interline glue that is inserted before boxes, based on the values of \prevdepth and \baselineskip and \lineskip and \lineskiplimit as explained in Chapter 12. If a command changes \prevdepth, that fact is specifically mentioned below. The \prevdepth is initially set to −1000 pt, a special value that inhibits interline glue, whenever TEX begins to form a vertical list, except in the case of \halign and \noalign when the interline glue conventions of the outer list continue inside the inner one. \vskiphgluei, \vfil, \vfill, \vss, \vfilneg. A glue item is appended to the current vertical list. hleadersihbox or ruleihvertical skipi. Here hvertical skipi refers to one of the five glue-appending commands just mentioned. The formal syntax for hleadersi and for hbox or rulei is hleadersi −→ \leaders | \cleaders | \xleaders hbox or rulei −→ hboxi | hvertical rulei | hhorizontal rulei hvertical rulei −→ \vrulehrule specificationi hhorizontal rulei −→ \hrulehrule specificationi 281 282 Chapter 24: Summary of Vertical Mode hrule specificationi −→ hoptional spacesi | hrule dimensionihrule specificationi hrule dimensioni −→ width hdimeni | height hdimeni | depth hdimeni A glue item that produces leaders is appended to the current list. hspace tokeni. Spaces have no effect in vertical modes. hboxi. The box is constructed, and if the result is void nothing happens. Otherwise the current vertical list receives (1) interline glue, followed by (2) the new box, followed by (3) vertical material that migrates out of the new box (if the hboxi was an \hbox command). Then \prevdepth is set to the new box’s depth, and TEX exercises the page builder. \movelefthdimenihboxi, \moverighthdimenihboxi. This acts exactly like an ordinary hboxi command, but the new box that is appended to the vertical list is also shifted left or right by the specified amount. \unvboxh8-bit numberi, \unvcopyh8-bit numberi. If the specified box register is void, nothing happens. Otherwise that register must contain a vbox. The vertical list inside that box is appended to the current vertical list, without changing it in any way. The value of \prevdepth is not affected. The box register becomes void after \unvbox, but it remains unchanged by \unvcopy. hhorizontal rulei. The specified rule is appended to the current list. Then \prevdepth is set to −1000 pt; this will prohibit interline glue when the next box is appended to the list. \halignhbox specificationi{halignment materiali}. The halignment materiali consists of a preamble followed by zero or more lines to be aligned; see Chapter 22. TEX enters a new level of grouping, represented by the ‘{’ and ‘}’, within which changes to \tabskip will be confined. The alignment material can also contain optional occurrences of ‘\noalignhfilleri{hvertical mode materiali}’ between lines; this adds another level of grouping. TEX operates in internal vertical mode while it works on the material in \noalign groups and when it appends lines of the alignment; the resulting internal vertical list will be appended to the enclosing vertical list after the alignment is completed, and the page builder will be exercised. The value of \prevdepth at the time of the \halign is used at the beginning of the internal vertical list, and the final value of \prevdepth is carried to the enclosing vertical list when the alignment is completed, so that the interline glue is calculated properly at the beginning and end of the alignment. TEX also enters an additional level of grouping when it works on each individual entry of the alignment, during which time it acts in restricted horizontal mode; the individual entries will be hboxed as part of the final alignment, and their vertical material will migrate to the enclosing vertical list. The commands \noalign, \omit, \span, \cr, \crcr, and & (where & denotes an explicit or implicit character of category 4) are intercepted by the alignment process, enroute to TEX’s stomach, so they will not appear as commands in the stomach unless TEX has lost track of what alignment they belong to. \indent. The \parskip glue is appended to the current list, unless TEX is in internal vertical mode and the current list is empty. Then TEX enters unrestricted horizontal mode, starting the horizontal list with an empty hbox whose width is \parindent. The \everypar tokens are inserted into TEX’s input. The page builder is exercised. When the paragraph is eventually completed, horizontal mode will come to an end as described in Chapter 25. Chapter 24: Summary of Vertical Mode \noindent. This is exactly like \indent, except that TEX starts out in horizontal mode with an empty list instead of with an indentation. \par. The primitive \par command has no effect when TEX is in vertical mode, except that the page builder is exercised in case something is present on the contribution list, and the paragraph shape parameters are cleared. {. A character token of category 1, or a control sequence like \bgroup that has been \let equal to such a character token, causes TEX to start a new level of grouping. When such a group ends—with ‘}’—TEX will undo the effects of non-global assignments without leaving whatever mode it is in at that time. Some commands are incompatible with vertical mode because they are intrinsically horizontal. When the following commands appear in vertical modes they cause TEX to begin a new paragraph: hhorizontal commandi −→ hletteri | hotherchari | \char | hchardef tokeni | \noboundary | \unhbox | \unhcopy | \valign | \vrule | \hskip | \hfil | \hfill | \hss | \hfilneg | \accent | \discretionary | \- | \Ã |  Here hletteri and hotherchari stand for explicit or implicit character tokens of categories 11 and 12. If any of these tokens occurs as a command in vertical mode or internal vertical mode, TEX automatically performs an \indent command as explained above. This leads into horizontal mode with the \everypar tokens in the input, after which TEX will see the hhorizontal commandi again. \end. This command is not allowed in internal vertical mode. In regular vertical mode it terminates TEX if the main vertical list is empty and \deadcycles=0. Otherwise TEX backs up the \end command so that it can be read again; then it exercises the page builder, after appending a box/glue/penalty combination that will force the output routine to act. (See the end of Chapter 23.) \dump. (Allowed only in INITEX, not in production versions of TEX.) This command is treated exactly like \end, but it must not appear inside a group. It outputs a format file that can be loaded into TEX’s memory at comparatively high speed to restore the current status. None of the above: If any other primitive command of TEX occurs in vertical mode, an error message will be given, and TEX will try to recover in a reasonable way. For example, if a superscript or subscript symbol appears, or if any other inherently mathematical command is given, TEX will try to insert a ‘’ (which will start a paragraph and enter math mode). On the other hand if a totally misplaced token like \endcsname or \omit or \eqno or # appears in vertical mode, TEX will simply ignore it, after reporting the error. You might enjoy trying to type some really stupid input, just to see what happens. (Say ‘\tracingall’ first, as explained in Chapter 27, in order to get maximum information.) The first and most striking feature is the Verticality of composition, as opposed to the Horizontality of all anterior structural modes. — COCKBURN MUIR, Pagan or Christian? (1860) Sometimes when I have finished a book I give a summary of the whole of it. — ROBERT WILLIAM DALE, Nine Lectures on Preaching (1878) 283 (page 284) 25 Summary of Horizontal Mode Chapter 25: Summary of Horizontal Mode Continuing the survey that was begun in Chapter 24, let us investigate exactly what TEX’s digestive processes can do, when TEX is building lists in horizontal mode or in restricted horizontal mode. ∗ Three asterisks, just like those that appear here, can be found near the end of Chapter 24. Everything preceding the three asterisks in that chapter applies to horizontal mode as well as to vertical mode, so we need not repeat all those rules. In particular, Chapter 24 explains assignment commands, and it tells how kerns, penalties, marks, insertions, adjustments, and “whatsits” are put into horizontal lists. Our present goal is to consider the commands that have an intrinsically horizontal flavor, in the sense that they behave differently in horizontal mode than they do in vertical or math modes. One of the things characteristic of horizontal mode is the “space factor,” which modifies the width of spaces as described in Chapter 12. If a command changes the value of \spacefactor, that fact is specifically noted here. The space factor is initially set to 1000, when TEX begins to form a horizontal list, except in the case of \valign and \noalign when the space factor of the outer list continues inside the inner one. \hskiphgluei, \hfil, \hfill, \hss, \hfilneg. A glue item is appended to the current horizontal list. hleadersihbox or ruleihhorizontal skipi. Here hhorizontal skipi refers to one of the five glue-appending commands just mentioned; the formal syntax for hleadersi and for hbox or rulei is given in Chapter 24. A glue item that produces leaders is appended. hspace tokeni. Spaces append glue to the current list; the exact amount of glue depends on \spacefactor, the current font, and the \spaceskip and \xspaceskip parameters, as described in Chapter 12. \Ã. A control-space command appends glue to the current list, using the same amount that a hspace tokeni inserts when the space factor is 1000. hboxi. The box is constructed, and if the result is void nothing happens. Otherwise the new box is appended to the current list, and the space factor is set to 1000. \raisehdimenihboxi, \lowerhdimenihboxi. This acts exactly like an ordinary hboxi command, but the new box that is appended to the horizontal list is also shifted up or down by the specified amount. \unhboxh8-bit numberi, \unhcopyh8-bit numberi. If the specified box register is void, nothing happens. Otherwise that register must contain an hbox. The horizontal list inside that box is appended to the current horizontal list, without changing it in any way. The value of \spacefactor is not affected. The box register becomes void after \unhbox, but it remains unchanged by \unhcopy. hvertical rulei. The specified rule is appended to the current list, and the \spacefactor is set to 1000. \valignhbox specificationi{halignment materiali}. The halignment materiali consists of a preamble followed by zero or more columns to be aligned; see Chapter 22. TEX enters a new level of grouping, represented by the ‘{’ and ‘}’, within which changes to \tabskip will be confined. The alignment material can also contain optional occurrences of ‘\noalignhfilleri{hhorizontal mode materiali}’ between columns; this adds another level of grouping. TEX operates in restricted horizontal mode while it works on the material in \noalign groups and when it appends columns of the 285 286 Chapter 25: Summary of Horizontal Mode alignment; the resulting internal horizontal list will be appended to the enclosing horizontal list after the alignment is completed. The value of \spacefactor at the time of the \valign is used at the beginning of the internal horizontal list, and the final value of \spacefactor is carried to the enclosing horizontal list when the alignment is completed. The space factor is set to 1000 after each column; hence it affects the results only in \noalign groups. TEX also enters an additional level of grouping when it works on each individual entry of the alignment, during which time it acts in internal vertical mode; the individual entries will be vboxed as part of the final alignment. \indent. An empty box of width \parindent is appended to the current list, and the space factor is set to 1000. \noindent. This command has no effect in horizontal modes. \par. The primitive \par command, also called \endgraf in plain TEX, does nothing in restricted horizontal mode. But it terminates horizontal mode: The current list is finished off by doing \unskip \penalty10000 \hskip\parfillskip, then it is broken into lines as explained in Chapter 14, and TEX returns to the enclosing vertical or internal vertical mode. The lines of the paragraph are appended to the enclosing vertical list, interspersed with interline glue and interline penalties, and with the migration of vertical material that was in the horizontal list. Then TEX exercises the page builder. {. A character token of category 1, or a control sequence like \bgroup that has been \let equal to such a character token, causes TEX to start a new level of grouping. When such a group ends—with ‘}’—TEX will undo the effects of non-global assignments without leaving whatever mode it is in at that time. Some commands are incompatible with horizontal mode because they are intrinsically vertical. When the following commands appear in unrestricted horizontal mode, they cause TEX to conclude the current paragraph: hvertical commandi −→ \unvbox | \unvcopy | \halign | \hrule | \vskip | \vfil | \vfill | \vss | \vfilneg | \end | \dump The appearance of a hvertical commandi in restricted horizontal mode is forbidden, but in regular horizontal mode it causes TEX to insert the token par into the input; after reading and expanding this par token, TEX will see the hvertical commandi token again. (The current meaning of the control sequence \par will be used; par might no longer stand for TEX’s \par primitive.) hletteri, hotherchari, \charh8-bit numberi, hchardef tokeni, \noboundary. The most common commands of all are the character commands that tell TEX to append a character to the current horizontal list, using the current font. If two or more commands of this type occur in succession, TEX processes them all as a unit, converting to ligatures and/or inserting kerns as directed by the font information. (Ligatures and kerns may be influenced by invisible “boundary” characters at the left and right, unless \noboundary appears.) Each character command adjusts \spacefactor, using the \sfcode table as described in Chapter 12. In unrestricted horizontal mode, a ‘\discretionary{}{}{}’ item is appended after a character whose code is the \hyphenchar of its font, or after a ligature formed from a sequence that ends with such a character. \accenth8-bit numberihoptional assignmentsi. Here hoptional assignmentsi stands for zero or more hassignmenti commands. If the assignments are not followed by a hcharacteri, where hcharacteri stands for any of the commands just discussed in Chapter 25: Summary of Horizontal Mode the previous paragraph, TEX treats \accent as if it were \char, except that the space factor is set to 1000. Otherwise the character that follows the assignment is accented by the character that corresponds to the h8-bit numberi. (The purpose of the intervening assignments is to allow the accenter and accentee to be in different fonts.) If the accent must be moved up or down, it is put into an hbox that is raised or lowered. Then the accent is effectively superposed on the character by means of kerns, in such a way that the width of the accent does not influence the width of the resulting horizontal list. Finally, TEX sets \spacefactor=1000. \/. If the last item on the current list is a character or ligature, an explicit kern for its italic correction is appended. \discretionaryhgeneral textihgeneral textihgeneral texti. The three general texts are processed in restricted horizontal mode. They should contain only fixed-width things; hence they aren’t really very general in this case. More precisely, the horizontal list formed by each discretionary general text must consist only of characters, ligatures, kerns, boxes, and rules; there should be no glue or penalty items, etc. This command appends a discretionary item to the current list; see Chapter 14 for the meaning of a discretionary item. The space factor is not changed. \-. This “discretionary hyphen” command is defined in Appendix H. \setlanguagehnumberi. See the conclusion of Appendix H. . A “math shift” character causes TEX to enter math mode or display math mode in the following way: TEX looks at the following token without expanding it. If that token is a  and if TEX is currently in unrestricted horizontal mode, then TEX breaks the current paragraph into lines as explained above (unless the current list is empty), returns to the enclosing vertical mode or internal vertical mode, calculates values like \prevgraf and \displaywidth and \predisplaysize, enters a new level of grouping, inserts the \everydisplay tokens into the input, exercises the page builder, processes ‘hmath mode materiali’ in display math mode, puts the display into the enclosing vertical list as explained in Chapter 19 (letting vertical material migrate), exercises the page builder again, increases \prevgraf by 3, and resumes horizontal mode again, with an empty list and with the space factor equal to 1000. (You got that?) Otherwise TEX puts the looked-at token back into the input, enters a new level of grouping, inserts the \everymath tokens, and processes ‘hmath mode materiali’; the math mode material is converted to a horizontal list and appended to the current list, surrounded by “math-on” and “math-off” items, and the space factor is set to 1000. One consequence of these rules is that ‘’ in restricted horizontal mode simply yields an empty math formula. None of the above: If any other primitive command of TEX occurs in horizontal mode, an error message will be given, and TEX will try to recover in a reasonable way. For example, if a superscript or subscript symbol appears, or if any other inherently mathematical command is given, TEX will try to insert a ‘’ just before the offending token; this will enter math mode. Otherwise. You may reduce all Verticals into Horizontals. — JOSEPH MOXON, A Tutor to Astronomie and Geographie (1659) ! You can’t use ‘\moveleft’ in horizontal mode. — TEX (1982) 287 (page 288) 26 Summary of Math Mode Chapter 26: Summary of Math Mode To conclude the survey that was begun in Chapter 24, let us investigate exactly what TEX’s digestive processes can do when TEX is building lists in math mode or in display math mode. ∗ Three asterisks, just like those that appear here, can be found near the end of Chapter 24. Everything preceding the three asterisks in that chapter applies to math mode as well as to vertical mode, so we need not repeat all those rules. In particular, Chapter 24 explains assignment commands, and it tells how kerns, penalties, marks, insertions, adjustments, and “whatsits” are put into math lists. Our present goal is to consider the commands that have an intrinsically mathematical flavor, in the sense that they behave differently in math mode than they do in vertical or horizontal modes. Math lists are somewhat different from TEX’s other lists because they contain three-pronged “atoms” (see Chapter 17). Atoms come in thirteen flavors: Ord, Op, Bin, Rel, Open, Close, Punct, Inner, Over, Under, Acc, Rad, and Vcent. Each atom contains three “fields” called its nucleus, superscript, and subscript; and each field is either empty or is filled with a math symbol, a box, or a subsidiary math list. Math symbols, in turn, have two components: a family number and a position number. It’s convenient to introduce a few more rules of syntax, in order to specify what goes into a math list: hcharacteri −→ hletteri | hotherchari | \charh8-bit numberi | hchardef tokeni hmath characteri −→ \mathcharh15-bit numberi | hmathchardef tokeni | \delimiterh27-bit numberi hmath symboli −→ hcharacteri | hmath characteri hmath fieldi −→ hmath symboli | hfilleri{hmath mode materiali} hdelimi −→ hfilleri\delimiterh27-bit numberi | hfillerihletteri | hfillerihotherchari We have already seen the concept of hcharacteri in Chapter 25. Indeed, characters are TEX’s staple food: The vast majority of all commands that reach TEX’s digestive processes in horizontal mode are instances of the hcharacteri command, which specifies a number between 0 and 255 that causes TEX to typeset the corresponding character in the current font. When TEX is in math mode or display math mode, a hcharacteri command takes on added significance: It specifies a number between 0 and 32767 = 215 − 1. This is done by replacing the character number by its \mathcode value. If the \mathcode value turns out to be 32768 = ˝8000, however, the hcharacteri is replaced by an active character token having the original character code (0 to 255); TEX forgets the original hcharacteri and expands this active character according to the rules of Chapter 20. A hmath characteri defines a 15-bit number either by specifying it directly with \mathchar or in a previous \mathchardef, or by specifying a 27-bit \delimiter value; in the latter case, the least significant 12 bits are discarded. It follows that every hmath symboli, as defined by the syntax above, specifies a 15-bit number, i.e., a number between 0 and 32767. Such a number can be represented in the form 4096c + 256f + a, where 0 ≤ c < 8, 0 ≤ f < 16, and 0 ≤ a < 256. If c = 7, TEX changes c to 0; and in this case if the current value of \fam is between 0 and 15, TEX also replaces f by \fam. This procedure yields, in all cases, a class 289 290 Chapter 26: Summary of Math Mode number c between 0 and 6, a family number f between 0 and 15, and a position number a between 0 and 255. (TEX initializes the value of \fam by implicitly putting the assignment ‘\fam=-1’ at the very beginning of \everymath and \everydisplay. Thus, the substitution of \fam for f will occur only if the user has explicitly changed \fam within the formula.) A hmath fieldi is used to specify the nucleus, superscript, or subscript of an atom. When a hmath fieldi is a hmath symboli, the f and a numbers of that symbol go into the atomic field. Otherwise the hmath fieldi begins with a ‘{’, which causes TEX to enter a new level of grouping and to begin a new math list; the ensuing hmath mode materiali is terminated by a ‘}’, at which point the group ends and the resulting math list goes into the atomic field. If the math list turns out to be simply a single Ord atom without subscripts or superscripts, or an Acc whose nucleus is an Ord, the enclosing braces are effectively removed. A hdelimi is used to define both a “small character” a in family f and a “large character” b in family g, where 0 ≤ a, b ≤ 255 and 0 ≤ f, g ≤ 15; these character codes are used to construct variable-size delimiters, as explained in Appendix G. If the hdelimi is given explicitly in terms of a 27-bit number, the desired codes are obtained by interpreting that number as c · 224 + f · 220 + a · 212 + g · 28 + b, ignoring the value of c. Otherwise the delimiter is specified as a hletteri or hotherchari token, and the 24-bit \delcode value of that character is interpreted as f · 220 + a · 212 + g · 28 + b. Now let’s study the individual commands as TEX obeys them in math mode, considering first the ones that have analogs in vertical and/or horizontal mode: \hskiphgluei, \hfil, \hfill, \hss, \hfilneg, \mskiphmugluei. A glue item is appended to the current math list. hleadersihbox or ruleihmathematical skipi. Here hmathematical skipi refers to one of the six glue-appending commands just mentioned; the formal syntax for hleadersi and for hbox or rulei is given in Chapter 24. A glue item that produces leaders is appended to the current list. \nonscript. A special glue item of width zero is appended; it will have the effect of cancelling the following item on the list, if that item is glue and if the \nonscript is eventually typeset in “script style” or in “scriptscript style.” \noboundary. This command is redundant and therefore has no effect; boundary ligatures are automatically disabled in math modes. hspace tokeni. Spaces have no effect in math modes. \Ã. A control-space command appends glue to the current list, using the same amount that a hspace tokeni inserts in horizontal mode when the space factor is 1000. hboxi. The box is constructed, and if the result is void nothing happens. Otherwise a new Ord atom is appended to the current math list, and the box becomes its nucleus. \raisehdimenihboxi, \lowerhdimenihboxi. This acts exactly like an ordinary hboxi command, but the new box that is put into the nucleus is also shifted up or down by the specified amount. \vcenterhbox specificationi{hvertical mode materiali}. A vbox is formed as if ‘\vcenter’ had been ‘\vbox’. Then a new Vcent atom is appended to the current math list, and the box becomes its nucleus. Chapter 26: Summary of Math Mode hvertical rulei. A rule is appended to the current list (not as an atom). \halignhbox specificationi{halignment materiali}. This command is allowed only in display math mode, and only when the current math list is empty. The alignment is carried out exactly as if it were done in the enclosing vertical mode (see Chapter 24), except that the lines are shifted right by the \displayindent. The closing ‘}’ may be followed by optional hassignmenti commands, after which ‘’ must conclude the display. TEX will insert the \abovedisplayskip and \belowdisplayskip glue before and after the result of the alignment. \indent. An empty box of width \parindent is appended to the current list, as the nucleus of a new Ord atom. \noindent. This command has no effect in math modes. {hmath mode materiali}. A character token of category 1, or a control sequence like \bgroup that has been \let equal to such a character token, causes TEX to start a new level of grouping and also to begin work on a new math list. When such a group ends—with ‘}’—TEX uses the resulting math list as the nucleus of a new Ord atom that is appended to the current list. If the resulting math list is a single Acc atom, however (i.e., an accented quantity), that atom itself is appended. hmath symboli. (This is the most common command in math mode; see the syntax near the beginning of this chapter.) A math symbol determines three values, c, f , and a, as explained earlier. TEX appends an atom to the current list, where the atom is of type Ord, Op, Bin, Rel, Open, Close, or Punct, according as the value of c is 0, 1, 2, 3, 4, 5, or 6. The nucleus of this atom is the math symbol defined by f and a. hmath atomihmath fieldi. A hmath atomi command is any of the following: \mathord | \mathop | \mathbin | \mathrel | \mathopen | \mathclose | \mathpunct | \mathinner | \underline | \overline TEX processes the hmath fieldi, then appends a new atom of the specified type to the current list; the nucleus of this atom contains the specified field. \mathaccenth15-bit numberihmath fieldi. TEX converts the h15-bit numberi into c, f , and a as it does with any \mathchar. Then it processes the hmath fieldi and appends a new Acc atom to the current list. The nucleus of this atom contains the specified field; the accent character in this atom contains (a, f ). \radicalh27-bit numberihmath fieldi. TEX converts the h27-bit numberi into a, f , b, and g as it does with any \delimiter. Then it processes the hmath fieldi and appends a new Rad atom to the current list. The nucleus of this atom contains the specified field; the delimiter field in this atom contains (a, f ) and (b, g). hsuperscriptihmath fieldi. A hsuperscripti command is an explicit or implicit character token of category 7. If the current list does not end with an atom, a new Ord atom with all fields empty is appended; thus the current list will end with an atom, in all cases. The superscript field of this atom should be empty; it is made nonempty by changing it to the result of the specified hmath fieldi. hsubscriptihmath fieldi. A hsubscripti command is an explicit or implicit character token of category 8. It acts just like a hsuperscripti command, except, of course, that it affects the subscript field instead of the superscript field. 291 292 Chapter 26: Summary of Math Mode \displaylimits, \limits, \nolimits. These commands are allowed only if the current list ends with an Op atom. They modify a special field in that Op atom, specifying what conventions should be used with respect to limits. The normal value of that field is \displaylimits. \/. A kern of width zero is appended to the current list. (This will have the effect of adding the italic correction to the previous character, if the italic correction wouldn’t normally have been added.) \discretionaryhgeneral textihgeneral textihgeneral texti. This command is treated just as in horizontal mode (see Chapter 25), but the third hgeneral texti must produce an empty list. \-. This command is usually equivalent to ‘\discretionary{-}{}{}’; the ‘-’ is therefore interpreted as a hyphen, not as a minus sign. (See Appendix H.) \mathchoicehgeneral textihgeneral textihgeneral textihgeneral texti. The four general texts are each treated as subformulas (i.e., like the second alternative in the definition of hmath fieldi). The four math lists defined in this way are recorded in a “choice item” that is appended to the current list. \displaystyle, \textstyle, \scriptstyle, \scriptscriptstyle. A stylechange item that corresponds to the specified style is appended to the current list. \lefthdelimihmath mode materiali\righthdelimi. TEX begins a new group, and processes the hmath mode materiali by starting out with a new math list that begins with a left boundary item containing the first delimiter. This group must be terminated by ‘\right’, at which time the internal math list is completed with a right boundary item containing the second delimiter. Then TEX appends an Inner atom to the current list; the nucleus of this atom contains the internal math list. hgeneralized fraction commandi. This command takes one of six forms: \over | \atop | \abovehdimeni | \overwithdelimshdelimihdelimi | \atopwithdelimshdelimihdelimi | \abovewithdelimshdelimihdelimihdimeni (See Chapter 17.) When TEX sees a hgeneralized fraction commandi it takes the entire current list and puts it into the numerator field of a generalized fraction item. The denominator field of this new item is temporarily empty; the left and right delimiter fields are set equal to the specified delimiter codes. TEX saves this generalized fraction item in a special place associated with the current level of math mode processing. (There should be no other generalized fraction item in that special place, because constructions like ‘a\over b\over c’ are illegal.) Then TEX makes the current list empty and continues to process commands in math mode. Later on, when the current level of math mode is completed (either by coming to a ‘’ or a ‘}’ or a \right, depending on the nature of the current group), the current list will be moved into the denominator field of the generalized fraction item that was saved; then that item, all by itself, will take the place of the entire list. However, in the special case that the current list began with \left and will end with \right, the boundary items will be extracted from the numerator and denominator of the generalized fraction, and the final list will consist of three items: left boundary, generalized fraction, right boundary. (If you

Chapter 26: Summary of Math Mode

want to watch the process by which math lists are built, you might find it helpful to type ‘\showlists’ while TEX is processing the denominator of a generalized fraction.) heqnoihmath mode materiali$. Here heqnoi stands for either \eqno or \leqno; these commands are allowed only in display math mode. Upon reading heqnoi, TEX enters a new level of grouping, inserts the \everymath tokens, and enters non-display math mode to put the hmath mode materiali into a math list. When that math list is completed, TEX converts it to a horizontal list and puts the result into a box that will be used as the equation number of the current display. The closing$ token will be put back into the input, where it will terminate the display. $. If TEX is in display math mode, it reads one more token, which must also be$. In either case, the math-shift command terminates the current level of math mode processing and ends the current group, which should have begun with either $or heqnoi. Once the math list is finished, it is converted into a horizontal list as explained in Appendix G. None of the above: If any other primitive command of TEX occurs in math mode, an error message will be given, and TEX will try to recover in a reasonable way. For example, if a \par command appears, or if any other inherently non-mathematical command is given, TEX will try to insert a ‘$’ just before the offending token; this will lead out of math mode. On the other hand if a totally misplaced token like \endcsname or \omit or # appears in math mode, TEX will simply ignore it, after reporting the error. You might enjoy trying to type some really stupid input, just to see what happens. (Say ‘\tracingall’ first, as explained in Chapter 27, in order to get maximum information.)

Ä Äx EXERCISE 26.1

Powers of ten: The whole TEX language has now been summarized completely. To demonstrate how much you know, name all of the ways you can think of in which the numbers 10, 100, 1000, 10000, and 100000 have special significance to TEX.

Ä Äx EXERCISE 26.2

Powers of two: Name all of the ways you can think of in which the numbers 8, 16, 32, 64, 128, 256, . . . have special significance to TEX.

Mathematics is known in the trade as difficult, or penalty, copy because it is slower, more difficult, and more expensive to set in type than any other kind of copy normally occurring in books and journals. — UNIVERSITY OF CHICAGO PRESS, A Manual of Style (1969) The tale of Math is a complex one, and it resists both a simple plot summary and a concise statement of its meaning. — PATRICK K. FORD, The Mabinogi (1977)

293

(page 294)

27 Recovery from Errors

Chapter 27: Recovery from Errors

OK, everything you need to know about TEX has been explained—unless you happen to be fallible. If you don’t plan to make any errors, don’t bother to read this chapter. Otherwise you might find it helpful to make use of some of the ways that TEX tries to pinpoint bugs in your manuscript. In the trial runs you did when reading Chapter 6, you learned the general form of error messages, and you also learned the various ways in which you can respond to TEX’s complaints. With practice, you will be able to correct most errors “online,” as soon as TEX has detected them, by inserting and deleting a few things. The right way to go about this is to be in a mellow mood when you approach TEX, and to regard the error messages that you get as amusing puzzles—“Why did the machine do that?”—rather than as personal insults. TEX knows how to issue more than a hundred different sorts of error messages, and you probably never will encounter all of them, because some types of mistakes are very hard to make. We discussed the “undefined control sequence” error in Chapter 6; let’s take a look at a few of the others now. If you misspell the name of some unit of measure—for example, if you type ‘\hsize=4im’ instead of ‘\hsize=4in’—you’ll get an error message that looks something like this: ! Illegal unit of measure (pt inserted).

i

m \hsize=4im \input story ? TEX needs to see a legal unit before it can proceed; so in this case it has implicitly inserted ‘pt’ at the current place in the input, and it has set \hsize=4pt. What’s the best way to recover from such an error? Well, you should always type ‘H’ or ‘h’ to see the help message, if you aren’t sure what the error message means. Then you can look at the lines of context and see that TEX will read ‘i’ and then ‘m’ and then ‘ \input story ’ if you simply hit hreturni and carry on. Unfortunately, this easy solution isn’t very good, because the ‘i’ and ‘m’ will be typeset as part of the text of a new paragraph. A much more graceful recovery is possible in this case, by first typing ‘2’. This tells TEX to discard the next two tokens that it reads; and after TEX has done so, it will stop again in order to give you a chance to look over the new situation. Here is what you will see: m \hsize=4im \input story ?

295

296

Chapter 27: Recovery from Errors

Good; the ‘i’ and ‘m’ are read and gone. But if you hit hreturni now, TEX will ‘\input story’ and try to typeset the story.tex file with \hsize=4pt; that won’t be an especially exciting experiment, because it will simply produce dozens of overfull boxes, one for every syllable of the story. Once again there’s a better way: You can insert the command that you had originally intended, by typing I\hsize=4in now. This instructs TEX to change \hsize to the correct value, after which it will \input story and you’ll be on your way. x EXERCISE 27.1 Ben User typed ‘8’, not ‘2’, in response to the error message just considered; his idea was to delete ‘i’, ‘m’, ‘\input’, and the five letters of ‘story’. But TEX’s response was \hsize=4im \input stor y Explain what happened. TEX usually tries to recover from errors either by ignoring a command that it doesn’t understand, or by inserting something that will keep it happy. For example, we saw in Chapter 6 that TEX ignores an undefined control sequence; and we just observed that TEX inserts ‘pt’ when it needs a physical unit of measure. Here’s another example where TEX puts something in: ! Missing $inserted.$

^ l.11 the fact that 32768=2^ {15} wasn’t interesting ? H I’ve inserted a begin-math/end-math symbol since I think you left one out. Proceed, with fingers crossed. (The user has forgotten to enclose a formula in $signs, and TEX has tried to recover by inserting one.) In this case the hinserted texti is explicitly shown, and it has not yet been read; by contrast, our previous example illustrated a case where TEX had already internalized the ‘pt’ that it had inserted. Thus the user has a chance here to remove the inserted ‘$’ before TEX really sees it. What should be done? The error in this example occurred before TEX noticed anything wrong; the characters ‘32768=2’ have already been typeset in horizontal mode. There’s no way to go back and cancel the past, so the lack of proper spacing around the ‘=’ cannot be fixed. Our goal of error recovery in this case is therefore not to produce perfect output; we want rather to proceed in some

Chapter 27: Recovery from Errors

way so that TEX will pass by the present error and detect subsequent ones. If we were simply to hit hreturni now, our aim would not be achieved, because TEX would typeset the ensuing text as a math formula: ‘15 wasn0 tinteresting . . .’ ; another error would be detected when the paragraph is found to end before any closing ‘$’ has appeared. On the other hand, there’s a more elaborate way to recover, namely to type ‘6’ and then ‘I$^{15}$’; this deletes ‘$^{15}’ and inserts a correct partial formula. But that’s more complicated than necessary. The best solution in this case is to type just ‘2’ and then go on; TEX will typeset the incorrect equation ‘32768=215’, but the important thing is that you will be able to check out the rest of the document as if this error hadn’t occurred. Ä

x EXERCISE 27.2

Here’s a case in which a backslash was inadvertently omitted:

! Missing control sequence inserted.

\inaccessible

m l.10 \def m acro{replacement} TEX needs to see a control sequence after ‘\def’, so it has inserted one that will allow the processing to continue. (This control sequence is shown as ‘\inaccessible’, but it has no relation to any control sequence that you can actually specify in an error-free manuscript.) If you simply hit hreturni at this point, TEX will define the inaccessible control sequence, but that won’t do you much good; later references to \macro will be undefined. Explain how to recover from this error so that the effect will be the same as if line 10 of the input file had said ‘\def\macro{replacement}’.

Ä

x EXERCISE 27.3

When you use the ‘I’ option to respond to an error message, the rules of Chapter 8 imply that TEX removes all spaces from the right-hand end of the line. Explain how you can use the ‘I’ option to insert a space, in spite of this fact.

Some of the toughest errors to deal with are those in which you make a mistake on line 20 (say), but TEX cannot tell that anything is amiss until it reaches line 25 or so. For example, if you forget a ‘}’ that completes the argument to some macro, TEX won’t notice any problem until reaching the end of the next paragraph. In such cases you probably have lost the whole paragraph; but TEX will usually be able to get straightened out in time to do the subsequent paragraphs as if nothing had happened. A “runaway argument” will be displayed, and by looking at the beginning of that text you should be able to figure out where the missing ‘}’ belongs. It’s wise to remember that the first error in your document may well spawn spurious “errors” later on, because anomalous commands can inflict serious injury on TEX’s ability to cope with the subsequent material. But most of the time you will find that a single run through the machine will locate all of the places in which your input conflicts with TEX’s rules.

297

298

Chapter 27: Recovery from Errors

When your error is due to misunderstanding rather than mistyping, the situation is even more serious: TEX’s error messages will probably not be very helpful, even if you ask TEX for help. If you have unknowingly redefined an important control sequence—for example, if you have said ‘\def\box{...}’—all sorts of strange disasters might occur. Computers aren’t clairvoyant, and TEX can only explain what looks wrong from its own viewpoint; such an explanation is bound to be mysterious unless you can understand the machine’s attitude. The solution to this problem is, of course, to seek human counsel and advice; or, as a last resort, to read the instructions in Chapters 2, 3, . . . , 26. Ä

x EXERCISE 27.4

J. H. Quick (a student) once defined the following set of macros: \newcount\serialnumber \def\firstnumber{\serialnumber=0 } \def\nextnumber{\advance \serialnumber by 1 \number\serialnumber)\nobreak\hskip.2em }

Thus he could type, for example, \firstnumber \nextnumber xx, \nextnumber yy, and \nextnumber zz and TEX would typeset ‘1) xx, 2) yy, and 3) zz’. Well, this worked fine, and he showed the macros to his buddies. But several months later he received a frantic phone call; one of his friends had just encountered a really weird error message: ! Missing number, treated as zero.

c l.107 \nextnumber minusc ule chances of error ? Explain what happened, and advise Quick what to do.

Sooner or later—hopefully sooner—you’ll get TEX to process your whole file without stopping once to complain. But maybe the output still won’t be right; the mere fact that TEX didn’t stop doesn’t mean that you can avoid proofreading. At this stage it’s usually easy to see how to fix typographic errors by correcting the input. Errors of layout can be overcome by using methods we have discussed before: Overfull boxes can be cured as described in Chapter 6; bad breaks can be avoided by using ties or \hbox commands as discussed in Chapter 14; math formulas can be improved by applying the principles of Chapters 16–19. But your output may contain seemingly inexplicable errors. For example, if you have specified a font at some magnification that is not supported by your printing software, TEX will not know that there is any problem, but the program that converts your dvi file to hardcopy might not tell you that it has substituted an “approximate” font for the real one; the resultant spacing may look quite horrible.

Chapter 27: Recovery from Errors

If you can’t find out what went wrong, try the old trick of simplifying your program: Remove all the things that do work, until you obtain the shortest possible input file that fails in the same way as the original. The shorter the file, the easier it will be for you or somebody else to pinpoint the problem. Perhaps you’ll wonder why TEX didn’t put a blank space in some position where you think you typed a space. Remember that TEX ignores spaces that follow control words, when it reads your file. (TEX also ignores a space after a hnumberi or a hunit of measurei that appears as an argument to a primitive command; but if you are using properly designed macros, such rules will not concern you, because you will probably not be using primitive commands directly.) Ä Ä On the other hand, if you are designing macros, the task of troubleshooting

can be a lot more complicated. For example, you may discover that TEX has emitted three blank spaces when it processed some long sequence of complicated code, consisting of several dozen commands. How can you find out where those spaces crept in? The answer is to set ‘\tracingcommands=1’, as mentioned in Chapter 13. This tells TEX to put an entry in your log file whenever it begins to execute a primitive command; you’ll be able to see when the command is ‘blank space’.

Ä

Most implementations of TEX allow you to interrupt the program in some way. This makes it possible to diagnose the causes of infinite loops. TEX switches to \errorstopmode when interrupted; hence you have a chance to insert commands into the input: You can abort the run, or you can \show or change the current contents of control sequences, registers, etc. You can also get a feeling for where TEX is spending most of its time, if you happen to be using an inefficient macro, since random interrupts will tend to occur in whatever place TEX visits most often.

Ä

Sometimes an error is so bad that TEX is forced to quit prematurely. For example, if you are running in \batchmode or \nonstopmode, TEX makes an “emergency stop” if it needs input from the terminal; this happens when a necessary file cannot be opened, or when no \end command was found in the input document. Here are some of the messages you might get just before TEX gives up the ghost: Fatal format file error; I’m stymied. This means that the preloaded format you have specified cannot be used, because it was prepared for a different version of TEX. That makes 100 errors; please try again. TEX has scrolled past 100 errors since the last paragraph ended, so it’s probably in an endless loop. Interwoven alignment preambles are not allowed. If you have been so devious as to get this message, you will understand it, and you will deserve no sympathy. I can’t go on meeting you like this. A previous error has gotten TEX out of whack. Fix it and try again. This can’t happen. Something is wrong with the TEX you are using. Complain fiercely.

299

300

Chapter 27: Recovery from Errors

Ä

There’s also a dreadful message that TEX issues only with great reluctance. But it can happen: TeX capacity exceeded, sorry.

This, alas, means that you have tried to stretch TEX too far. The message will tell you what part of TEX’s memory has become overloaded; one of the following fourteen things will be mentioned: number of strings (names of control sequences and files) pool size (the characters in such names) main memory size (boxes, glue, breakpoints, token lists, characters, etc.) hash size (control sequence names) font memory (font metric data) exception dictionary (hyphenation exceptions) input stack size (simultaneous input sources) semantic nest size (unfinished lists being constructed) parameter stack size (macro parameters) buffer size (characters in lines being read from files) save size (values to restore at group ends) text input levels (\input files and error insertions) grouping levels (unfinished groups) pattern memory (hyphenation pattern data) The current amount of memory available will also be shown.

Ä

If you have a job that doesn’t overflow TEX’s capacity, yet you want to see just how closely you have approached the limits, just set \tracingstats to a positive value before the end of your job. The log file will then conclude with a report on your actual usage of the first eleven things named above (i.e., the number of strings, . . . , the save size), in that order. Furthermore, if you set \tracingstats equal to 2 or more, TEX will show its current memory usage whenever it does a \shipout command. Such statistics are broken into two parts; ‘490&5950’ means, for example, that 490 words are being used for “large” things like boxes, glue, and breakpoints, while 5950 words are being used for “small” things like tokens and characters.

Ä

What can be done if TEX’s capacity is exceeded? All of the above-listed components of the capacity can be increased, provided that your computer is large enough; in fact, the space necessary to increase one component can usually be obtained by decreasing some other component, without increasing the total size of TEX. If you have an especially important application, you may be able to convince your local system people to provide you with a special TEX whose capacities have been hand-tailored to your needs. But before taking such a drastic step, be sure that you are using TEX properly. If you have specified a gigantic paragraph or a gigantic alignment that spans more than one page, you should change your approach, because TEX has to read all the way to the end before it can complete the line-breaking or the alignment calculations; this consumes huge amounts of memory space. If you have built up an enormous macro library, you should remember that TEX has to remember all of the replacement texts that you define; therefore if memory space is in short supply, you should load only the macros that you need. (See Appendices B and D, for ideas on how to make macros more compact.)

Chapter 27: Recovery from Errors

Ä

Some erroneous TEX programs will overflow any finite memory capacity. For example, after ‘\def\recurse{(\recurse)}’, the use of \recurse will immediately bomb out: ! TeX capacity exceeded, sorry [input stack size=80]. \recurse ->(\recurse ) \recurse ->(\recurse ) ... The same sort of error will obviously occur no matter how much you increase TEX’s input stack size.

Ä Ä The special case of “save size” capacity exceeded is one of the most trou-

blesome errors to correct, especially if you run into the error only on long jobs. TEX generally uses up two words of save size whenever it performs a non-global assignment to some quantity whose previous value was not assigned at the same level of grouping. When macros are written properly, there will rarely be a need for more than 100 or so things on the “save stack”; but it’s possible to make save stack usage grow without limit if you make both local and global assignments to the same variable. You can figure out what TEX puts on the save stack by setting \tracingrestores=1; then your log file will record information about whatever is removed from the stack at the end of a group. For example, let \a stand for the command ‘\advance\day by 1’; let \g stand for ‘\global\advance\day by 1’; and consider the following commands: \day=1 {\a\g\a\g\a} The first \a sets \day=2 and remembers the old value \day=1 by putting it on the save stack. The first \g sets \day=3, globally; nothing needs to go on the save stack at the time of a global assignment. The next \a sets \day=4 and remembers the old value \day=3 on the save stack. Then \g sets \day=5; then \a sets \day=6 and remembers \day=5. Finally the ‘}’ causes TEX to go back through the save stack; if \tracingrestores=1 at this point, the log file will get the following data: {restoring \day=5} {retaining \day=5} {retaining \day=5} Explanation: The \day parameter is first restored to its global value 5. Since this value is global, it will be retained, so the other saved values (\day=3 and \day=1) are essentially ignored. Moral: If you find TEX retaining a lot of values, you have a set of macros that could cause the save stack to overflow in large enough jobs. To prevent this, it’s usually wise to be consistent in your assignments to each variable that you use; the assignments should either be global always or local always.

Ä Ä TEX provides several other kinds of tracing in addition to \tracingstats and

\tracingrestores: We have already discussed \tracingcommands in Chapters 13 and 20, \tracingparagraphs in Chapter 14, \tracingpages in Chapter 15, and \tracingmacros in Chapter 20. There is also \tracinglostchars, which (if positive) causes TEX to record each time a character has been dropped because it does not appear in the current font; and \tracingoutput, which (if positive) causes TEX to

301

302

Chapter 27: Recovery from Errors

display in symbolic form the contents of every box that is being shipped out to the dvi file. The latter allows you to see if things have been typeset properly, if you’re trying to decide whether some anomaly was caused by TEX or by some other software that acts on TEX’s output.

Ä

When TEX displays a box as part of diagnostic output, the amount of data is controlled by two parameters called \showboxbreadth and \showboxdepth. The first of these, which plain TEX sets equal to 5, tells the maximum number of items shown per level; the second, which plain TEX sets to 3, tells the deepest level. For example, a small box whose full contents are \hbox(4.30554+1.94444)x21.0, glue set 0.5 .\hbox(4.30554+1.94444)x5.0 ..\tenrm g .\glue 5.0 plus 2.0 .\tenrm | (ligature ---) will be abbreviated as follows when \showboxbreadth=1 and \showboxdepth=1: \hbox(4.30554+1.94444)x21.0, glue set 0.5 .\hbox(4.30554+1.94444)x5.0 [] .etc. And if you set \showboxdepth=0, you get only the top level: \hbox(4.30554+1.94444)x21.0, glue set 0.5 [] (Notice how ‘[]’ and ‘etc.’ indicate that the data has been truncated.)

Ä

A nonempty hbox is considered “overfull” if its glue cannot shrink to achieve the specified size, provided that \hbadness is less than 100 or that the excess width (after shrinking by the maximum amount) is more than \hfuzz. It is “tight” if its glue shrinks and the badness exceeds \hbadness; it is “loose” if its glue stretches and the badness exceeds \hbadness but is not greater than 100; it is “underfull” if its glue stretches and the badness is greater than \hbadness and greater than 100. Similar remarks apply to nonempty vboxes. TEX prints a warning message and displays the offending box, whenever such anomalies are discovered. Empty boxes are never considered to be anomalous.

Ä Ä When an alignment is “overfull” or “tight” or “loose” or “underfull,” you don’t

get a warning message for every aligned line; you get only one message, and TEX displays a prototype row (or, with \valign, a prototype column). For example, suppose you say ‘\tabskip=0pt plus10pt \halign to200pt{&#\hfil\cr...\cr}’, and suppose that the aligned material turns out to make two columns of widths 50 pt and 60 pt, respectively. Then you get the following message: Underfull \hbox (badness 2698) in alignment at lines 11--18 [] [] \hbox(0.0+0.0)x200.0, glue set 3.0 .\glue(\tabskip) 0.0 plus 10.0 .\unsetbox(0.0+0.0)x50.0 .\glue(\tabskip) 0.0 plus 10.0 .\unsetbox(0.0+0.0)x60.0 .\glue(\tabskip) 0.0 plus 10.0

Chapter 27: Recovery from Errors

The “unset boxes” in a prototype row show the individual column widths. In this case the tabskip glue has to stretch 3.0 times its stretchability, in order to reach the 200 pt goal, so the box is underfull. (According to the formula in Chapter 14, the badness of this situation is 2700; TEX actually uses a similar but more efficient formula, so it computes a badness of 2698.) Every line of the alignment will be underfull, but only the prototype row will be displayed in a warning message. “Overfull rules” are never appended to the lines of overfull alignments.

Ä Ä The \tracing... commands put all of their output into your log file, unless

the \tracingonline parameter is positive; in the latter case, all diagnostic information goes to the terminal as well as to the log file. Plain TEX has a \tracingall macro that turns on the maximum amount of tracing of all kinds. It not only sets up \tracingcommands, \tracingrestores, \tracingparagraphs, and so on, it also sets \tracingonline=1, and it sets \showboxbreadth and \showboxdepth to extremely high values, so that the entire contents of all boxes will be displayed.

Ä Ä Some production versions of TEX have been streamlined for speed. These im-

plementations don’t look at the values of the parameters \tracingparagraphs, \tracingpages, \tracingstats, and \tracingrestores, because TEX runs faster when it doesn’t have to maintain statistics or keep tabs on whether tracing is required. If you want all of TEX’s diagnostic tools, you should be sure to use the right version.

Ä Ä If you set \pausing=1, TEX will give you a chance to edit each line of input as it is read from the file. In this way you can make temporary patches (e.g., you can insert \show... commands) while you’re troubleshooting, without changing the actual contents of the file, and you can keep TEX running at human speed.

Final hint: When working on a long manuscript, it’s best to prepare only a few pages at a time. Set up a “galley” file and a “book” file, and enter your text on the galley file. (Put control information that sets up your basic format at the beginning of this file; an example of galley.tex appears in Appendix E.) After the galleys come out looking right, you can append them to the book file; then you can run the book file through TEX occasionally, in order to see how the pages really fit together. For example, when the author prepared this manual, he did one chapter at a time, and the longer chapters were split into subchapters. Ä Äx EXERCISE 27.5

Final exercise: Find all of the lies in this manual, and all of the jokes.

Final exhortation: GO FORTH now and create masterpieces of the publishing art!

Who can understand his errors? — Psalm 19 : 12 (c. 1000 B.C.) It is one thing, to shew a Man that he is in an Error, and another, to put him in possession of Truth. — JOHN LOCKE, An Essay Concerning Humane Understanding (1690)

303

(page 304)

A Answers to All the Exercises

Appendix A: Answers to All the Exercises

305

306

Appendix A: Answers to All the Exercises

4.4. Control word names are made of letters, not digits. 4.5. Say \def\sl{\it} at the beginning, and delete other definitions of \sl that might be present in your format file (e.g., there might be one inside a \tenpoint macro). 4.6. \font\squinttenrm=cmr10 at 5pt \font\squinttenrm=cmr10 scaled 500 5.1. {shelf}ful or shelf{}ful, etc.; or even shelf\/ful, which yields a shelfful instead of a shelfful. In fact, the latter idea—to insert an italic correction—is preferable because TEX will reinsert the ff ligature by itself after hyphenating shelf{}ful. (Appendix H points out that ligatures are put into a hyphenated word that contains no “explicit kerns,” and an italic correction is an explicit kern.) But the italic correction may be too much (especially in an italic font); shelf{\kern0pt}ful is often best. 5.2. ‘Ã{Ã}Ã’ or ‘Ã{}Ã{}Ã’, etc. Plain TEX also has a \space macro, so you can type \space\space\space. (These aren’t strictly equivalent to ‘\Ã\Ã\Ã’, since they adjust the spaces by the current “space factor,” as explained later.) 5.3. In the first case, you get the same result as if the innermost braces had not appeared at all, because you haven’t used the grouping to change fonts or to control spacing or anything. TEX doesn’t mind if you want to waste your time making groups for no particular reason. But in the second case, the necessary braces were forgotten. You get the letter ‘S’ centered on a line by itself, followed by a paragraph that begins with ‘o should this.’ on the next line. 5.4. You get the same result as if another pair of braces were present around ‘\it centered’, except that the period is typeset from the italic font. (Both periods look about the same.) The \it font will not remain in force after the \centerline, but this is something of a coincidence: TEX uses the braces to determine what text is to be centered, but then it removes the braces. The \centerline operation, as defined in Appendix B, puts the resulting braceless text inside another group; and that’s why \it disappears after \centerline. (If you don’t understand this, just don’t risk leaving out braces in tricky situations, and you’ll be OK.) 5.5. \def\ital#1{{\it#1\/}}. Pro: Users might find this easier to learn, because it works more like \centerline and they don’t have to remember to make the italic correction. Con: To avoid the italic correction just before a comma or period, users should probably be taught another control sequence; for example, with \def\nocorr{\kern0pt } a user could type ‘\ital{comma} or \ital{period\nocorr},’. The alternative of putting a period or comma in italics, to avoid the italic correction, doesn’t look as good. A long sequence of italics would be inefficient for TEX, since the entire text for the argument to \ital must be read into memory only to be scanned again. 5.6. {1 {2 3 4 5} 4 6} 4. 5.7. \def\beginthe#1{\begingroup\def\blockname{#1}} \def\endthe#1{\def\test{#1}% \ifx\test\blockname\endgroup \else\errmessage{You should have said \string\endthe{\blockname}}\fi}

Appendix A: Answers to All the Exercises

6.1. Laziness and/or obstinacy. 6.2. There’s an unwanted space after ‘called—’, because (as the book says) TEX treats the end of a line as if it were a blank space. That blank space is usually what you want, except when a line ends with a hyphen or a dash; so you should WATCH OUT for lines that end with hyphens or dashes. 6.3. It represents the heavy bar that shows up in your output. (This bar wouldn’t be present if \overfullrule had been set to 0pt, nor is it present in an underfull box.) 6.4. This is the \parfillskip space that ends the paragraph. In plain TEX the parfillskip is zero when the last line of the paragraph is full; hence no space actually appears before the rule in the output of Experiment 3. But all hskips show up as spaces in an overfull box message, even if they’re zero. 6.5. Run TEX with \hsize=1.5in \tolerance=10000 \raggedright \hbadness=-1 and then \input story. TEX will report the badness of all lines (except the final lines of paragraphs, where fill glue makes the badness zero). 6.6. \def\extraspace{\nobreak \hskip 0pt plus .15em\relax} \def\dash{\unskip\extraspace---\extraspace} (If you try this with the story at 2-inch and 1.5-inch sizes, you will notice a substantial improvement. The \unskip allows people to leave a space before typing \dash. TEX will try to hyphenate before \dash, but not before ‘---’; cf. Appendix H. The \relax at the end of \extraspace is a precaution in case the next word is ‘minus’.) 6.7. TEX would have deleted five tokens: 1, i, n, Ã, \centerline. (The space was at the end of line 2, the \centerline at the beginning of line 3.) 6.8. A control sequence like \centerline might well define a control sequence like \ERROR before telling TEX to look at #1. Therefore TEX doesn’t interpret control sequences when it scans an argument. 7.1. Three forbidden characters were used. One should type Procter \& Gamble’s ... \$2, a 10\% gain. (Also the facts are wrong.) 7.2. Reverse slashes (backslashes) are fairly uncommon in formulas or text, and \\ is very easy to type; it was therefore felt best not to reserve \\ for such limited use. Typists can define \\ to be whatever they want (including \backslash). 7.3. 1, 2, 3, 4, 6, 7, 8, 10, 11, 12, 13. Active characters (type 13) are somewhat special; they behave like control sequences in most cases (e.g., when you say ‘\let\x=~’ or ‘\ifx\x~’), but they behave like character tokens when they appear in the token list of \uppercase or \lowercase, and when unexpanded after \if or \ifcat. 7.4. It ends with either > or } or any character of category 2; then the effects of all \catcode definitions within the group are wiped out, except those that were \global. TEX doesn’t have any built-in knowledge about how to pair up particular kinds of grouping characters. New category codes take effect as soon as a \catcode assignment has been digested. For example, {\catcode‘\>=2 > 307 308 Appendix A: Answers to All the Exercises is a complete group. But without the space after ‘2’ it would not be complete, since TEX would have read the ‘>’ and converted it to a token before knowing what category code was being specified; TEX always reads the token following a constant before evaluating that constant. 7.5. If you type ‘\message{\string~}’ and ‘\message{\string\~}’, TEX responds with ‘~’ and ‘\~’, respectively. To get \12 from \string you therefore need to make backslash an active character. One way to do this is {\catcode‘/=0 \catcode‘\\=13 /message{/string\}} (The “null control sequence” that you get when there are no tokens between \csname and \endcsname is not a solution to this exercise, because \string converts it to ‘\csname\endcsname’. There is, however, another solution: If TEX’s \escapechar parameter—which will be explained in one of the next dangerous bends—is negative or greater than 255, then ‘\string\\’ works.) 7.6. \12 a12 \12 Ã10 b12 . 7.7. \def\ifundefined#1{\expandafter\ifx\csname#1\endcsname\relax} Note that a control sequence like this must be used with care; it cannot be included in conditional text, because the \ifx will not be seen when \ifundefined isn’t expanded. 7.8. First \uppercase produces ‘A\lowercase{BC}’; then you get ‘Abc’. 7.9. ‘ \copyright\ \uppercase\expandafter{\romannumeral\year} ’. (This is admittedly tricky; the ‘\expandafter’ expands the token after the ‘{’, not the token after the group.) 7.10. (We assume that parameter #2 is not simply an active character, and that \escapechar is between 0 and 255.) \def\gobble#1{} % remove one token \def\appendroman#1#2#3{\edef#1{\csname \expandafter\gobble\string#2\romannumeral#3\endcsname}} 8.1. The % would be treated as a comment character, because its category code is 14; thus, no % token or } token would get through to the gullet of TEX where numbers are treated. When a character is of category 0, 5, 9, 14, or 15, the extra \ must be used; and the \ doesn’t hurt, so you can always use it to be safe. 8.2. (a) Both characters terminate the current line; but a character of category 5 might be converted into Ã10 or a par token, while a character of category 14 never produces a token. (b) They produce character tokens stamped with different category numbers. For example,$3 is not the same token as $4 , so TEX’s digestive processes will treat them differently. (c) Same as (b), plus the fact that control sequence names treat letters differently. (d) No. (e) Yes; characters of category 10 are ignored at the beginning of every line, since every line starts in state N . (f) No. 8.3. TEX had just read the control sequence \vship, so it was in state S, and it was just ready to read the space before ‘1in’. Afterwards it ignored that space, since it was in state S; but if you had typed I\obeyspaces in response to that error message, you would have seen the space. Incidentally, when TEX prints the context of an error message, the bottom pair of lines comes from a text file, but the other pairs of lines Appendix A: Answers to All the Exercises are portions of token lists that TEX is reading (unless they begin with ‘’, when they represent text inserted during error recovery). 8.4.$3 x11 ^7 212 $3 ~13 Ã10 TeX b12 v12 Ã10 . The final space comes from the hreturni placed at the end of the line. Code ^^6 yields v only when not followed by 0–9 or a–f. The initial space is ignored, because state N governs the beginning of the line. 8.5. H11 i11 !12 Ã10 par par . The ‘Ã’ comes from the hreturni at the end of the first line; the second and third lines each contribute a par . 8.6. The two ^^B’s are not recognized as consecutive superscript characters, since the first ^^B is converted to code 2 which doesn’t equal the following character ^. Hence the result is seven tokens: ^^B7 ^^B7 M11 ^^B Ã10 ^^M11 M^^M . The last of these is a control word whose name has two letters. The hspacei after \M is deleted before TEX inserts the hreturni token. 8.7. Both alternatives work fine in text; in particular, they combine as in \lq\lq to form ligatures. But the definition in Appendix B works also in connection with constants; e.g., \char\lq\% and \char\rq140 are valid. (Incidentally, the construction \let\lq=‘ would not work with constants, since the quotes in a hnumberi must come from character tokens of category 12; after \let\lq=‘ the control sequence token \lq will not expand into a character token, nor is it a character token!) 9.1. na\"\i ve or na{\"\i}ve or na\"{\i}ve. 9.2. Beloved prot´eg´e; rˆ ole co¨ ordinator; souffl´es, crˆepes, pˆ at´es, etc. 9.3. \AE sop’s \OE uvres en fran\c cais. 9.4. {\sl Commentarii Academi\ae\ scientiarum imperialis petropolitan\ae\/} is now {\sl Akademi\t\i a Nauk SSSR, Doklady}. 9.5. Ernesto Ces\‘aro, P\’al Erd\H os, \O ystein Ore, Stanis\l aw \’Swier% czkowski, Serge\u\i\ \t Iur’ev, Mu\d hammad ibn M\^us\^a al-Khw\^arizm\^\i. 9.6. The proper umlaut is \H, which isn’t available in \tt, so it’s necessary to borrow the accent from another font. For example, {\tt P\’al Erd{\bf\H{\tt o}}s} uses a bold accent, which is suitably dark. 9.7. {\it Europe on {\sl\$}15.00 a day\/} 9.8. The extra braces keep font changes local. An argument makes the use of \’ more consistent with the use of other accents like \d, which are manufactured from other characters without using the \accent primitive. 10.1. Exactly 7227 pt. 10.2. −.013837 in, 0. mm, +42.1 dd, 3 in, 29 pc, 123456789 sp. (The lines of text in this manual are 29 picas wide.) 10.3. The first is not allowed, since octal notation cannot be used with a decimal point. The second is, however, legal, since a hnumberi can be hexadecimal according to the rule mentioned in Chapter 8; it means 12 cc, which is 144 dd ≈ 154.08124 pt. The third is also accepted, since a hdigit stringi can be empty; it is a complicated way to say 0 sp.

309

310

Appendix A: Answers to All the Exercises

10.4. \def\tick#1{\vrule height 0pt depth #1pt} \def\\{\hbox to 1cm{\hfil\tick4\hfil\tick8}} \vbox{\hrule\hbox{\tick8\\\\\\\\\\\\\\\\\\\\}} (You might also try putting ticks at every millimeter, in order to see how good your system is; some output devices can’t handle 101 rules all at once.) 10.5. For example, say ‘\magnification=\magstep1 \input story \end’ to get magnification 1200; \magstep2 and \magstep3 are 1440 and 1728. Three separate runs are needed, since there can be at most one magnification per job. The output may look funny if the fonts don’t exist at the stated magnifications. 10.6. Magnification is by a factor of 1.2. Since font \first is cmr10 at 12 pt, it will be cmr10 at 14.4 pt after magnification; font \second will be cmr10 at 12 pt. (TEX changes ‘12truept’ into ‘10pt’, and the final output magnifies it back to 12 pt.) 11.1. This E is inside a box that’s inside a box. 11.2. The idea is to construct a box and to look inside. For example, \setbox0=\hbox{\sl g\/} \showbox0 reveals that \/ is implemented by placing a kern after the character. Further experiment shows that this kern is inserted even when the italic correction is zero. 11.3. The height, depth, and width of the enclosing box should be just large enough to enclose all of the contents, so the result is: \hbox(8.98608+0.0)x24.44484 .\tenrm T .\kern 1.66702 .\hbox(6.83331+0.0)x6.80557, shifted -2.15277 ..\tenrm E .\kern 1.25 .\tenrm X (You probably predicted a height of 8.9861; TEX’s internal calculations are in sp, not pt/100000, so the rounding in the fifth decimal place is not readily predictable.) 11.4. No applications of such symmetrical boxes to English-language printing were apparent; it seemed pointless to carry extra generality as useless baggage that would rarely if ever be used, merely for the sake of symmetry. In other words, the author wore a computer science cap instead of a mathematician’s mantle on the day that TEX’s boxes were born. Time will tell whether or not this was a fundamental error! 11.5. The following solution is based on a general \makeblankbox macro that prints the edges of a box using rules of given thickness outside and inside that box; the box dimensions are those of \box0. \def\dolist{\afterassignment\dodolist\let\next= } \def\dodolist{\ifx\next\endlist \let\next\relax \else \\\let\next\dolist \fi \next} \def\endlist{\endlist}

Appendix A: Answers to All the Exercises

\def\hidehrule#1#2{\kern-#1% \hrule height#1 depth#2 \kern-#2 } \def\hidevrule#1#2{\kern-#1{\dimen0=#1 \advance\dimen0 by#2\vrule width\dimen0}\kern-#2 } \def\makeblankbox#1#2{\hbox{\lower\dp0\vbox{\hidehrule{#1}{#2}% \kern-#1 % overlap the rules at the corners \hbox to \wd0{\hidevrule{#1}{#2}% \raise\ht0\vbox to #1{}% set the vrule height \lower\dp0\vtop to #1{}% set the vrule depth \hfil\hidevrule{#2}{#1}}% \kern-#1\hidehrule{#2}{#1}}}} \def\maketypebox{\makeblankbox{0pt}{1pt}} \def\makelightbox{\makeblankbox{.2pt}{.2pt}} \def\\{\expandafter\if\space\next\ \else \setbox0=\hbox{\next}\maketypebox\fi} \def\demobox#1{\setbox0=\hbox{\dolist#1\endlist}% \copy0\kern-\wd0\makelightbox} 11.6. \def\frac#1/#2{\leavevmode\kern.1em \raise.5ex\hbox{\the\scriptfont0 #1}\kern-.1em /\kern-.15em\lower.25ex\hbox{\the\scriptfont0 #2}} 12.1. 9 + 16 units, 9 + 32 units, 12 + 0 units. (But TEX would consider so much stretching to be “infinitely bad.”) 12.2. ‘What happens now?’ is placed in a line of width \hsize, with twice as much space at the left as at the right; ‘and now?’ is put flush right on the following line. 12.3. The first two give an “overfull box” if the argument doesn’t fit on a line; the third allows the argument to stick out into the margins instead. (Plain TEX’s \centerline is \centerlinec; the stickout effect shows up in the narrow-column experiment of Chapter 6.) If the argument contains no infinite glue, \centerlinea and \centerlineb produce the same effect; but \centerlineb will center an argument that contains ‘fil’ glue. 12.4. Mr.~\& Mrs.~User were married by Rev.~Drofnats, who preached on Matt.~19\thinspace:\thinspace3--9. (Such thin spaces are traditional for Biblical references to chapter and verse, but you weren’t really expected to know that. Plain TEX defines \thinspace to be a kern, not glue; hence no break between lines will occur at a thinspace.) 12.5. Donald~E.\ Knuth, ‘‘Mathematical typography,’’ {\sl Bull.\ Amer.\ Math.\ Soc.\ \bf1} (1979), 337--372. (But the ‘\’ after ‘E.’ isn’t necessary, because of a rule you will learn if you venture around the next dangerous bend.) 12.6. There are several ways; perhaps the easiest are to type ‘\hbox{NASA}.’ or ‘NASA\null.’ (The \null macro is an abbreviation for ‘\hbox{}’.) 12.7. 1000, except: 999 after B, S, D, and J; 1250 after the comma; 3000 after the exclamation point, the double-right-quote, and the periods. If a period had come right after the B (i.e., if the text had said ‘B. Sally’), the space factor after that period would have been 1000, not 3000.

311

312

Appendix A: Answers to All the Exercises

12.8. \box3 is 2 pt high, 4 pt deep, 3 pt wide. Starting at the reference point of \box3, go right .75 pt and down 3 pt to reach the reference point of \box1; or go right 1 pt to reach the reference point of \box2. 12.9. The stretch and shrink components of \baselineskip and \lineskip should be equal, and the \lineskiplimit should equal the normal \lineskip spacing, to guarantee continuity. 12.10. Yes it did, but only because none of his boxes had a negative height or depth. He would have been safer if he had set \baselineskip=-1000pt, \lineskip=0pt, and \lineskiplimit=16383pt. (Plain TEX’s \offinterlineskip macro does this.) 12.11. The interline glue will be zero, and the natural height is 1 + 1 − 3 + 2 = 1 pt (because the depth of \box2 isn’t included in the natural height); so the glue will ultimately become \vskip-1pt when it’s set. Thus, \box3 is 3 pt high, 2 pt deep, 4 pt wide. Its reference point coincides with that of \box2; to get to the reference point of \box1 you go up 2 pt and right 3 pt. 12.12. The interline glue will be 6 pt minus 3 fil; the final depth will be zero, since \box2 is followed by glue; the natural height is 12 pt; and the shrinkability is 5 fil. So \box4 will be 4 pt high, 0 pt deep, 1 pt wide, and it will contain five items: \vskip -1.6pt, \box1, \vskip1.2pt, \moveleft4pt\box2, \vskip-1.6pt. Starting at the reference point of \box4, you get to the reference point of \box1 by going up 4.6 pt, or to the reference point of \box2 by going up .4 pt and left 4 pt. (For example, you go up 4 pt to get to the upper left corner of \box4; then down −1.6 pt, i.e., up 1.6 pt, to get to the upper left corner of \box1; then down 1 pt to reach its reference point. This problem is clearly academic, since it’s rather ridiculous to include infinite shrinkability in the baselineskip.) 12.13. Now \box4 will be 4 pt high, −4 pt deep, 1 pt wide, and it will contain \vskip -2.4pt, \box1, \vskip-1.2pt, \moveleft4pt\box2, \vskip-2.4pt. From the baseline of \box4, go up exactly 5.4 pt to reach the baseline of \box1, or exactly 3.6 pt to reach the baseline of \box2. 12.14. \vbox to x{} produces height x; \vtop to x{} produces depth x; the other dimensions are zero. (This holds even when x is negative.) 12.15. There are several possibilities: \def\nullbox#1#2#3{\vbox to#1{\vss\hrule height-#2depth#2width#3}} works because the rule will be of zero thickness. Less tricky is \def\nullbox#1#2#3{\vbox to#1{\vss\vtop to#2{\vss\hbox to#3{}}}} Both of these are valid with negative height and/or depth, but they do not produce negative width. If the width might be negative, but not the height or depth, you can use, e.g., \def\nullbox#1#2#3{\hbox to#3{\hss\raise#1\null\lower#2\null}}. It’s impossible for \hbox to construct a box whose height or depth is negative; it’s impossible for \vbox or \vtop to construct a box whose width is negative. However, there’s actually a trivial solution to the general problem, based on features that will be discussed later: \def\nullbox#1#2#3{\setbox0=\null \ht0=#1 \dp0=#2 \wd0=#3 \box0 }

Appendix A: Answers to All the Exercises

12.16. \def\llap#1{\hbox to 0pt{\hss#1}} 12.17. You get ‘A’ at the extreme left and ‘puzzle.’ at the extreme right, because the space between words has the only stretchability that is finite; the infinite stretchability cancels out. (In this case, TEX’s rule about infinite glue differs from what you would get in the limit if the value of 1 fil were finite but getting larger and larger. The true limiting behavior would stretch the text ‘A puzzle.’ in the same way, but it would also move that text infinitely far away beyond the right edge of the page.) 13.1. Simply saying \hbox{...} won’t work, since that box will just continue the previous vertical list without switching modes. You need to start the paragraph explicitly, and the straightforward way to do that is to say \indent\hbox{...}. But suppose you want to define a macro that expands to an hbox, where this macro is to be used in the midst of a paragraph as well as at the beginning; then you don’t want to force users to type \indent before calling your macro at the beginning of a paragraph, nor do you want to say \indent in the macro itself (since that might insert unwanted indentations). One solution to this more general problem is to say ‘\Ã\unskip\hbox{...}’, since \Ã makes the mode horizontal while \unskip removes the unwanted space. Plain TEX provides a \leavevmode macro, which solves this problem in what is probably the most efficient way: \leavevmode is an abbreviation for ‘\unhbox\voidbox’, where \voidbox is a permanently empty box register. 13.2. The output of \tracingcommands shows that four blank space tokens were digested; these originated at the ends of lines 2, 3, 4, and 5. Only the first had any effect, since blank spaces are ignored in math formulas and in vertical modes. 13.3. The end-group character finishes the paragraph and the \vbox, and \bye stands for ‘\vfill...’, so the next three commands are {math mode: math shift character $} {restricted horizontal mode: end-group character }} {vertical mode: \vfill} 13.4. It contains only mixtures of vertical glue and horizontal rules whose reference points appear at the left of the page; there’s no text. 13.5. Vertical mode can occur only as the outermost mode; horizontal mode and display math mode can occur only when immediately enclosed by vertical or internal vertical mode; ordinary math mode cannot be immediately enclosed by vertical or internal vertical mode; all other cases are possible. 14.1. (cf.~Chapter~12). Chapters 12 and~21. line~16 of Chapter~6’s {\tt story} lines 7 to~11 lines 2,~3, 4, and~5. (2)~a big black bar All 256~characters are initially of category~12, letter~{\tt x} in family~1. the factor~$f$, where$n$~is 1000~times~$f$. 14.2. ‘for all$n$~greater than~$n_0$’ avoids distracting breaks. 313 314 Appendix A: Answers to All the Exercises 14.3. ‘exercise \hbox{4.3.2--15}’ guarantees that there is no break after the endash. But this precaution is rarely necessary, so ‘exercise 4.3.2--15’ is an acceptable answer. No ~ is needed; ‘4.3.2–15’ is so long that it causes no offense at the beginning of a line. 14.4. The space you get from ~ will stretch or shrink with the other spaces in the same line, but the space inside an hbox has a fixed width since that glue has already been set once and for all. Furthermore the first alternative permits the word Chapter to be hyphenated. 14.5. ‘\hbox{$x=0$}’ is unbreakable, and we will see later that ‘${x=0}$’ cannot be broken. Both of these solutions set the glue surrounding the equals sign to some fixed value, but such glue normally wants to stretch; furthermore, the \hbox solution might include undesirable blank space at the beginning or end of a line, if \mathsurround is nonzero. A third solution ‘$x=\nobreak0$’ avoids both defects. 14.6. \exhyphenpenalty=10000 prohibits all such breaks, according to the rules found later in this chapter. Similarly, \hyphenpenalty=10000 prevents breaks after implicit (discretionary) hyphens. 14.7. The second and fourth lines are indented by an additional “quad” of space, i.e., by one extra em in the current type style. (The control sequence \quad does an \hskip; when TEX is in vertical mode, \hskip begins a new paragraph and puts glue after the indentation.) If \indent had been used instead, those lines wouldn’t have been indented any more than the first and third, because \indent is implicit at the beginning of every paragraph. Double indentation on the second and fourth lines could have been achieved by ‘\indent\indent’. 14.8. ba\ck en and Be\ttt uch, where the macros \ck and \ttt are defined by \def\ck{\discretionary{k-}{k}{ck}} \def\ttt{tt\discretionary{-}{t}{}} The English word ‘eighteen’ might deserve similar treatment. TEX’s hyphenation algorithm will not make such spelling changes automatically. 14.9. \def\break{\penalty-10000 } 14.10. You get a forced break as if \nobreak were not present, because \break cannot be cancelled by another penalty. In general if you have two penalties in a row, their combined effect is the same as a single penalty whose value is the minimum of the two original values, unless both of those values force breaks. (You get two breaks from \break\break; the second one creates an empty line.) 14.11. Breaks are forced when p ≤ −10000, so there’s no point in subtracting a large constant whose effect on the total demerits is known a priori, especially when that might cause arithmetic overflow. 14.12. (10 + 131)2 + 02 + 10000 = 29881 and (10 + 1)2 + 502 + 10000 = 12621. In both cases the \adjdemerits were added because the lines were visually incompatible (decent, then very loose, then decent); plain TEX’s values for \linepenalty and \adjdemerits were used. Appendix A: Answers to All the Exercises 14.13. Because TEX discards a glue item that occurs just before \par. Ben should have said, e.g., ‘\hfilneg\ \par’. 14.14. Just say \parfillskip=\parindent. Of course, TEX will not be able to find appropriate line breaks unless each paragraph is sufficiently long or sufficiently lucky; but with an appropriate text, your output will be immaculately symmetrical. 14.15. Assuming that the author is deceased and/or set in his or her ways, the remedy is to insert ‘{\parfillskip=0pt\par\parskip=0pt\noindent}’ in random places, after each 50 lines or so of text. (Every space between words is usually a feasible breakpoint, when you get sufficiently far from the beginning of a paragraph.) 14.16. {\leftskip=-1pt \rightskip=1pt htexti \par} (This applies to a full paragraph; if you want to correct only isolated lines, you have to do it by hand.) 14.17. ‘\def\line#1{\hbox to\hsize{\hskip\leftskip#1\hskip\rightskip}}’ is the only change needed. (Incidentally, displayed equations don’t take account of \leftskip and \rightskip either; it’s more difficult to change that, because so many variations are possible.) 14.18. The author’s best solution is based on a variable \dimen register \x: \setbox1=\hbox{I} \setbox0=\vbox{\parshape=11 -0\x0\x -1\x2\x -2\x4\x -3\x6\x -4\x8\x -5\x10\x -6\x12\x -7\x14\x -8\x16\x -9\x18\x -10\x20\x \ifdim \x>2em \rightskip=-\wd1 \else \frenchspacing \rightskip=-\wd1 plus1pt minus1pt \leftskip=0pt plus 1pt minus1pt \fi \parfillskip=0pt \tolerance=1000 \noindent I turn, ... hand.} \centerline{\hbox to \wd1{\box0\hss}} Satisfactory results are obtained with font cmr10 when \x is set to 8.9 pt, 13.4 pt, 18.1 pt, 22.6 pt, 32.6 pt, and 47.2 pt, yielding triangles that are respectively 11, 9, 8, 7, 6, and 5 lines tall. 14.19. \item{} at the beginning of each paragraph that wants hanging indentation. 14.20. \item{$\bullet$} 14.21. Either change \hsize or \rightskip. The trick is to change it back again at the end of a paragraph. Here’s one way, without grouping: \let\endgraf=\par \edef\restorehsize{\hsize=\the\hsize} \def\par{\endgraf \restorehsize \let\par=\endgraf} \advance\hsize by-\parindent 14.22. \dimen0=\hsize \advance\dimen0 by 2em \parshape=3 0pt\hsize 0pt\hsize -2em\dimen0 14.23. The three paragraphs can be combined into a single paragraph, if you use ‘\hfil\vadjust{\vskip\parskip}\break\indent’ instead of ‘\par’ after the first two. Then of course you say, e.g., \hangindent=-50pt \hangafter=-15. (The same idea can be applied in connection with \looseness, if you want TEX to make one of three 315 316 Appendix A: Answers to All the Exercises paragraphs looser but if you don’t want to choose which one it will be. However, long paragraphs fill TEX’s memory; please use restraint.) See also the next exercise. 14.24. Use \hangcarryover between paragraphs, defined as follows: \def\hangcarryover{\edef\next{\hangafter=\the\hangafter \hangindent=\the\hangindent} \par\next \edef\next{\prevgraf=\the\prevgraf} \indent\next} 14.25. It will set the current paragraph in the minimum number of lines that can be achieved without violating the tolerance; and, given that number of lines, it will break them optimally. (However, nonzero looseness makes TEX work harder, so this is not recommended if you don’t want to pay for the extra computation. You can achieve almost the same result much more efficiently by setting \linepenalty=100, say.) 14.26. 150, 100, 0, 250. (When the total penalty is zero, as between lines 3 and 4 in this case, no penalty is actually inserted.) 14.27. \interlinepenalty plus \clubpenalty plus \widowpenalty (and also plus \brokenpenalty, if the first line ends with a discretionary break). 14.28. The tricky part is to avoid “opening up” the paragraph by adding anything to its height; yet this star is to be contributed after a line having an unknown depth, because the depth of the line depends on details of line breaking that aren’t known until afterwards. The following solution uses \strut, and assumes that the line containing the marginal star does not have depth exceeding \dp\strutbox, the depth of a \strut. \def\strutdepth{\dp\strutbox} \def\marginalstar{\strut\vadjust{\kern-\strutdepth\specialstar}} Here \specialstar is a box of height zero and depth \strutdepth, and it puts an asterisk in the left margin: \def\specialstar{\vtop to \strutdepth{ \baselineskip\strutdepth \vss\llap{* }\null}} 14.29. \def\insertbullets{\everypar={\llap{$\bullet\enspace}}} (A similar device can be used to insert hanging indentation, and/or to number the paragraphs automatically.) 14.30. First comes \parskip glue (but you might not see it on the current page if you say \showlists, since glue disappears at the top of each page). Then comes the result of \everypar, but let’s assume that \everypar doesn’t add anything to the horizontal list, so that you get an empty horizontal list; then there’s no partial paragraph before the display. The displayed equation follows the normal rules (it occupies lines 1–3 of the paragraph, and uses the indentation and length of line 2, if there’s a nonstandard shape). Nothing follows the display, since a blank space is ignored after a closing ‘$$’. Incidentally, the behavior is different if you start a paragraph with ‘$$’ instead of with \noindent$$, since TEX inserts a paragraph indentation that will appear on a line by itself (with \leftskip and \parfillskip and \rightskip glue). Appendix A: Answers to All the Exercises 14.31. A break at \penalty50 would cancel \hskip2em\nobreak\hfil, so the next line would be forced to start with the reviewer’s name flush left. (But \vadjust{} would actually be better than \hbox{}; it uses TEX more efficiently.) 14.32. Otherwise the line-breaking algorithm might prefer two final lines to one final line, simply in order to move a hyphen from the second-last line up to the third-last line where it doesn’t cause demerits. This in fact caused some surprises when the \signed macro was being tested; \tracingparagraphs=1 was used to diagnose the problem. 14.33. Distributing the extra space evenly would lead to three lines of the maximum badness (10000). It’s better to have just one bad line instead of three, since TEX doesn’t distinguish degrees of badness when lines are really awful. In this particular case the \tolerance was 200, so TEX didn’t try any line breaks that would stretch the first two lines; but even if the tolerance had been raised to 10000, the optimum setting would have had only one underfull line. If you really want to spread the space evenly you can do so by using \spaceskip to increase the amount of stretchability between words. 14.34. \def\raggedcenter{\leftskip=0pt plus4em \rightskip=\leftskip \parfillskip=0pt \spaceskip=.3333em \xspaceskip=.5em \pretolerance=9999 \tolerance=9999 \parindent=0pt \hyphenpenalty=9999 \exhyphenpenalty=9999 } 15.1. The last three page-break calculations would have been % t=503.0 plus 8.0 minus 4.0 g=528.0 b=3049 p=150 c=3199# % t=514.0 plus 8.0 minus 4.0 g=528.0 b=533 p=-100 c=433# % t=542.0 plus 11.0 minus 6.0 g=528.0 b=* p=0 c=* so the break would have occurred at the same place. The badness would have been 533, but the page would still have looked tolerable. (On the other hand if that paragraph had been two lines shorter instead of one, the first two lines of the next “dangerous bend” paragraph would have appeared on that page; the natural height t = 531 pt would have been able to shrink to g = 528 pt because the three “medskips” on the page would have had a total shrinkability of 6 pt. This would certainly have been preferable to a stretched-out page whose badness was 3049; but the author might have seen it and written another sentence or two, so that the paragraph would not have been broken up. After all, this manual is supposed to be an example of good practice.) 15.2. The next legal break after the beginning of a dangerous bend paragraph occurs 28 pt later, because there is 6 pt additional space for a \medskip, followed by two lines of 11 pt each. TEX does not allow breaking between those two lines; the \clubpenalty is set briefly to 10000 in Appendix E, since the dangerous bend symbol is two lines tall. 15.3. A page always contains at least one box, if there are no insertions, since the legal breakpoints are discarded otherwise. Statement (a) fails if the height of the topmost box exceeds 10 pt. Statement (b) fails if the depth of the bottommost box exceeds 2.2 pt, or if some glue or kern comes between the bottommost box and the page break (unless that glue or kern exactly cancels the depth of the box). 15.4. \topinsert\vskip2in\rightline{\vbox{\hsize ... artwork.}}\endinsert does the job. But it’s slightly more efficient to avoid \rightline by changing \leftskip as follows: ‘\leftskip=\hsize \advance\leftskip by-3in’. Then TEX doesn’t have to read the text of the caption twice. 317 318 Appendix A: Answers to All the Exercises 15.5. It would appear on page 25, since it does fit there. A \midinsert will jump ahead of other insertions only if it is not carried over to another page; for example, if the second 3-inch insertion were a \midinsert, it would not appear on page 26, because it is converted to a \topinsert as soon as the \midinsert macro notices that the insertion is too big for page 25. 15.6. Set \count1 to 50, then \dimen2 to 50 pt, then \count1 to 6, then \skip2 to −10 pt plus 6 fil minus 50 pt, then \skip2 to 60 pt plus −36 fil minus −300 pt, then \skip2 to 1 sp minus −6 sp, then \count6 to 1, then \skip1 to 25 pt plus 1 sp minus 1 fill, then \skip2 to 25 pt minus −150 pt, then \skip1 to 0 pt plus 1 sp minus 1 fill. 15.7. If \skip4 has infinite stretchability, \skip5 will be zero; otherwise it will be 0 pt plus 1 pt. 15.8. \advance\dimen2 by0.5\dimen3 \divide\dimen2 by\dimen3 \multiply\dimen2 by\dimen3 15.9. \count1 takes the values 5, then 2 (the old 5 is saved), then 4 (which is made global), then 8 (and 4 is saved); finally the value 4 is restored, and that is the answer. (For further remarks, see the discussion of \tracingrestores in Chapter 27.) 15.10. \hbox{\hbox{A}A}. After ‘\unhbox5’, \box5 is void; \unhcopy5 yields nothing. 15.11. \hbox{A}. But after ‘{\global\setbox3=\hbox{A}\setbox3=\box3}’, \box3 will be void. 15.12. \newcount\notenumber \def\clearnotenumber{\notenumber=0\relax} \def\note{\advance\notenumber by 1 \footnote{^{\the\notenumber}}} 15.13. Yes, in severe circumstances. (1) If there is no other legal breakpoint, TEX will take a break whose cost is ∞. (2) If \vadjust{\eject} occurs on the same line as a footnote, before that footnote, the reference will be forcibly detached. (3) Other \vadjust commands on that line could also interpose breakpoints before the insertion. 16.1. \gamma+\nu\in\Gamma. 16.2. \le, \ge, and \ne. (These are short for “less-or-equal,” “greater-or-equal,” and “not-equal.”) You can also use the names \leq, \geq, and \neq. (The fourth most common symbol is, perhaps, ‘∞’, which stands for “infinity” and is called ‘\infty’.) 16.3. In the former, the ‘_2’ applies to the plus sign (x +2 F3 ); but in the latter, it applies to an empty subformula (x + 2 F3 ). z 16.4. The results are ‘xy z ’ and ‘xy ’; the z in the first alternative is the same size as the y, but in the second it is smaller. Furthermore, the y and z in the first case aren’t quite at the same height. (Good typists never even think of the first construction, because mathematicians never want it.) 16.5. The second alternative doesn’t work properly when there’s a subscript at the same time as a prime. Furthermore, some mathematicians use \prime also in the subscript position; they write, for example, F 0 (w, z) = ∂F (w, z)/∂z and F0 (w, z) = ∂F (w, z)/∂w. Appendix A: Answers to All the Exercises 16.6. R_i{}^{jk}{}_l. 16.7. 10^{10}; 2^{n+1}; (n+1)^2; \sqrt{1-x^2}; \overline{w+\overline z}; p_1^{e_1}; a_{b_{c_{d_e}}}; \root3\of{h’’_n(\alpha x)}. (Of course, you should enclose these formulas in dollar signs so that TEX will process them in math mode. Superscripts and subscripts can be given in either order; for example, h’’_n and h_n’’ both work the same. You should not leave out any of the braces shown here; for example, ‘10^10’ would yield ‘101 0’. But it doesn’t hurt to insert additional braces around letters or numbers, as in ‘({n}+{1})^{2}’. The indicated blank spaces are necessary unless you use extra braces; otherwise TEX will complain about undefined control sequences \overlinez and \alphax.) 16.8. He got ‘Ifx = y . . .’ because he forgot to leave a space after ‘If’; spaces disappear between dollar signs. He should also have ended the sentence with ‘y.’; punctuation that belongs to a sentence should not be included in a formula, as we will see in Chapter 18. (But you aren’t expected to know that yet.) 16.9. Deleting an element from an n-tuple leaves an (n-1)-tuple. 16.10. Q, f, g, j, p, q, y. (The analogous Greek letters are β, γ, ζ, η, µ, ξ, ρ, φ, ϕ, χ, ψ.) 16.11. z^{*2} and h_*’(z). 16.12. 3{\cdot}1416. (One of the earlier examples in this chapter showed that \cdot is a binary operation; putting it in braces makes it act like an ordinary symbol.) If you have lots of constants like this, for example in a table, there’s a way to make ordinary periods act like \cdot symbols: Just define \mathcode‘. to be "0201, assuming that the fonts of plain TEX are being used. However, this could be dangerous, since ordinary periods are used frequently in displayed equations; the \mathcode change should be confined to places where every period is to be a \cdot. 16.13. e^{-x^2}, D\sim p^\alpha M+l, and \ghat\in(H^{\pi_1^{-1}})’. (If you are reading the dangerous bend sections, you know that the recommended way to define \ghat is ‘\def\ghat{{\hat g}}’.) 17.1. x + y 2/(k+1) (x+y^{2/(k+1)}). 17.2. ((a + 1)/(b + 1))x (((a+1)/(b+1))x). 17.3. He got the displayed formula x = (y 2 k + 1) because he forgot that an unconfined \over applies to everything. (He should probably have typed ‘$$x=\left(y^2\over k+1\right)$$’, using ideas that will be presented later in this chapter; this not only makes the parentheses larger, it keeps the ‘x =’ out of the fraction, because \left and \right introduce subformulas.) 17.4. ‘7{1\over2}\cents’ or ‘71\over2\cents’. used here was \def\cents{\hbox{\rm\rlap/c}}.) 0 (Incidentally, the definition 17.5. Style D 0 is used for the subformula pe2 , hence style S 0 is used for the superscript e0 and the subscript 2, and style SS 0 is used for the supersuperscript prime. The square root sign and the p appear in text size; the 2 and the e appear in script size; and the 0 is in scriptscript size. 319 320 Appendix A: Answers to All the Exercises 17.6.$${1\over2}{n\choose k}$$;$$\displaystyle{n\choose k}\over2$$. All of these braces are necessary. 17.7.$${p \choose 2} x^2 y^{p-2} - {1 \over 1-x}{1 \over 1-x^2}.$$17.8.$$\sum_{i=1}^p\sum_{j=1}^q\sum_{k=1}^ra_{ij}b_{jk}c_{ki}$$. 17.9.$$\sum_{{\scriptstyle 1\le i\le p \atop \scriptstyle 1\le j\le q} \atop \scriptstyle 1\le k\le r} a_{ij} b_{jk} c_{ki}$$. 17.10. \displaystyle\biggl({\partial^2\over\partial x^2}+ {\partial^2\over\partial y^2}\biggr)\bigl|\varphi(x+iy)\bigr|^2=0. 17.11. Formulas that are more than one line tall are usually two lines tall, not 1 21 or 2 12 lines tall. 17.12. \bigl(x+f(x)\bigr) \big/ \bigl(x-f(x)\bigr). (Notice especially the ‘\big/’; an ordinary slash would look too small between the \big parentheses. 17.13.$$\pi(n)=\sum_{k=2}^n\left\lfloor\phi(k)\over k-1\right\rfloor.$$17.14.$$\pi(n)=\sum_{m=2}^n\left\lfloor\biggl(\sum_{k=1}^{m-1}\bigl \lfloor(m/k)\big/\lceil m/k\rceil\bigr\rfloor\biggr)^{-1}\right\rfloor.$$17.15. A displayed formula equivalent to$${D}{{T}\over{T}^{{S}^{SS}}}. 17.16. \def\sqr#1#2{{\vcenter{\vbox{\hrule height.#2pt \hbox{\vrule width.#2pt height#1pt \kern#1pt \vrule width.#2pt} \hrule height.#2pt}}}} \def\square{\mathchoice\sqr34\sqr34\sqr{2.1}3\sqr{1.5}3} 17.17. \def\euler{\atopwithdelims}. 17.18. The \textfont0 that was current at the beginning of the formula will be used, because this redefinition is local to the braces. (It would be a different story if ‘\global\textfont’ had appeared instead; that would have changed the meaning of \textfont0 at all levels.) 17.19. "2208 and "220F. 17.20. \mathchardef\alpha="710B. Incidentally, {\rm\alpha} will then give a spurious result, because character position ˝0B of roman fonts does not contain an alpha; you should warn your users about what characters they are allowed to type under the influence of special conventions like \rm. 17.21. If \delcode‘{ were set to some nonnegative delimiter code, you would get no error message when you wrote something like ‘\left{’. This would be bad because strange effects would happen when certain subformulas were given as arguments to macros, or when they appeared in alignments. But it has an even worse defect, because a user who gets away with ‘\left{’ is likely to try also ‘\bigl{’, which fails miserably. 17.22. Since \bigl is defined as a macro with one parameter, it gets just ‘\delimiter’ as the argument. You have to write ‘\bigl{\delimiter"426830A}’ to make this work. On the other hand, \left will balk if the following character is a left brace. Therefore it’s best to have control sequence names for all delimiters. Appendix A: Answers to All the Exercises 18.1. R(n,t)=O(t^{n/2}), as t\to0^+. (N.B.: ‘O(’, not ‘0(’.) 18.2.p_1(n)=\lim_{m\to\infty}\sum_{\nu=0}^\infty \bigl(1-\cos^{2m}(\nu!^n\pi/n)\bigr).$$[Mathematicians may enjoy interpreting this formula; cf. G. H. Hardy, Messenger of Mathematics 35 (1906), 145–146.] 18.3. \def\limsup{\mathop{\overline{\rm lim}}} \def\liminf{\mathop{\underline{\rm lim}}} [Notice that the limits ‘n → ∞’ appear at different levels, in both of the displays, because ‘sup’ and the underbar descend below the baseline. It is possible to unify the limit positions by using phantoms, as explained later in this chapter. For example, \def\limsup{\mathop{\vphantom{\underline{}}\overline{\rm lim}}} would give lower limits in the same position as \liminf.] 18.4. x ≡ 0( (mod y)n ). He should have typed ‘x\equiv0\pmod{y^n}’. 18.5.$${n\choose k}\equiv{\lfloor n/p\rfloor\choose \lfloor k/p\rfloor}{n\bmod p\choose k\bmod p}\pmod p.$$18.6. \bf\bar x^{\rm T}Mx={\rm0}\iff x=0. (If you typed a space between \rm and 0, you wasted a keystroke; but don’t feel guilty about it.) 18.7. S\subseteq{\mit\Sigma}\iff S\in{\cal S}. In this case the braces are redundant and could be eliminated; but you shouldn’t try to do everything with fewest keystrokes, or you’ll outsmart yourself some day. 18.8.$${\it available}+\sum_{i=1}^n\max\bigl({\it full}(i), {\it reserved}(i)\bigr)={\it capacity}.$$[If \it had been used throughout the formula, the subscript i and superscript n would have caused error messages saying ‘\scriptfont 4 is undefined’, since plain TEX makes \it available only in text size.] 18.9. {\obeylines \sfcode‘;=3000 {\bf for j:=2 step 1 until n do} \quad {\bf begin} {\it accum}:=A[j]; k:=j-1; A[0]:=\it accum; \quad {\bf while A[k]>\it accum do} \qquad {\bf begin} A[k+1]:=A[k]; k:=k-1; \qquad {\bf end}; \quad A[k+1]:=\it accum; \quad {\bf end}.\par} [This is something like the “poetry” example in Chapter 14, but much more difficult. Some manuals of style say that punctuation should inherit the font of the preceding character, so that three kinds of semicolons should be typeset; e.g., these experts recommend ‘k := j − 1; A[0] := accum; end;’. The author heartily disagrees.] 18.10. Let H~be a Hilbert space, \ C~a closed bounded convex subset of~H, \ T~a nonexpansive self map of~C. Suppose that as n\to\infty, \ a_{n,k}\to0 for each~k, and \gamma_n=\sum_{k=0}^\infty(a_{n,k+1}- 321 322 Appendix A: Answers to All the Exercises a_{n,k})^+\to0. Then for each x~in~C, \ A_nx=\sum_{k=0}^\infty a_{n,k}T^kx converges weakly to a fixed point of~T. [If any mathematicians are reading this, they might either appreciate or resent the following attempt to edit the given paragraph into a more acceptable style: “Let C be a closed, bounded, convex subset of a Hilbert space H, and let T be a nonexpansive self map of C. Suppose that as n → ∞, we have an,k → 0 for each k, P∞ and γn = (an,k+1 − an,k )+ → 0. Then for each x in C, the infinite sum k=0 P∞ An x = k=0 an,k T k x converges weakly to a fixed point of T .”] 18.11.$$\int_0^\infty{t-ib\over t^2+b^2}e^{iat}\,dt= e^{ab}E_1(ab),\qquad a,b>0.$$18.12.$$\hbar=1.0545\times10^{-27}\rm\,erg\,sec.$$18.13. There are ten atoms (the first is f and last is y 2 ); their types, and the interatomic spacing, are respectively Ord Open Ord Punct \, Ord Close \; Rel \; Ord \> Bin \> Ord. 18.14. \left]-\infty,T\right[\times\left]-\infty,T\right[. (Or one could say \mathopen and \mathclose instead of \left and \right; then TEX would not choose the size of the delimiters, nor would it consider the subformulas to be of type Inner.) Open intervals are more clearly expressed in print by using parentheses instead of reversed brackets; for example, compare ‘(−∞, T ) × (−∞, T )’ to the given formula. 18.15. The first + will become a Bin atom, the second an Ord; hence the result is x, medium space, +, medium space, +, no space, 1. 18.16. x_1+x_1x_2+\cdots+x_1x_2\ldots x_n and (x_1,\ldots,x_n)\cdot(y_1,\ldots,y_n)=x_1y_1+\cdots+x_ny_n. 18.17. The commas belong to the sentence, not to the formula; his decision to put them into math mode meant that TEX didn’t put large enough spaces after them. Also, his formula ‘i = 1, 2, . . . , n’ allows no breaks between lines, except after the =, so he’s risking overfull box problems. But suppose the sentence had been more terse: Clearly ai < bi (i = 1, 2, . . . , n). Then his idea would be basically correct: Clearly a_i1}f(t)\,d\pi(t).$$ 18.41. $$\{\underbrace{\overbrace{\mathstrut a,\ldots,a} ^{k\;a\mathchar‘’\rm s}, \overbrace{\mathstrut b,\ldots,b} ^{l\;b\mathchar‘’\rm s}}_{k+l\rm\;elements}\}.$$ Notice how apostrophes (instead of primes) were obtained. 18.42. \pmatrix{\pmatrix{a&b\cr c&d\cr}& \pmatrix{e&f\cr g&h\cr}\cr \noalign{\smallskip} 0&\pmatrix{i&j\cr k&l\cr}\cr}. 18.43. $$\det\left|\,\matrix{ c_0&c_1\hfill&c_2\hfill&\ldots&c_n\hfill\cr c_1&c_2\hfill&c_3\hfill&\ldots&c_{n+1}\hfill\cr c_2&c_3\hfill&c_4\hfill&\ldots&c_{n+2}\hfill\cr \,\vdots\hfill&\,\vdots\hfill& \,\vdots\hfill&&\,\vdots\hfill\cr c_n&c_{n+1}\hfill&c_{n+2}\hfill&\ldots&c_{2n}\hfill\cr }\right|>0.$$ 18.44. $$\mathop{{\sum}’}_{x\in A}f(x)\mathrel{\mathop=^{\rm def}} \sum_{\scriptstyle x\in A\atop\scriptstyle x\ne0}f(x).$$ This works because {\sum} is type Ord (so its superscript is not set above), but \mathop{{\sum}’} is typePOp (so its subscript is set below). The limits are centered P0 on , however, not on . If you don’t like that, the remedy is more difficult; one solution is to use \sumprime_{x\in A} where \sumprime is defined as follows: \def\sumprime_#1{\setbox0=\hbox{\scriptstyle{#1}$} \setbox2=\hbox{$\displaystyle{\sum}$} \setbox4=\hbox{${}’\mathsurround=0pt} \dimen0=.5\wd0 \advance\dimen0 by-.5\wd2 \ifdim\dimen0>0pt Appendix A: Answers to All the Exercises \ifdim\dimen0>\wd4 \kern\wd4 \else\kern\dimen0\fi\fi \mathop{{\sum}’}_{\kern-\wd4 #1}} 18.45. $$2\uparrow\uparrow k\mathrel{\mathop=^{\rm def}} 2^{2^{2^{\cdot^{\cdot^{\cdot^2}}}}} \vbox{\hbox{\Big\}\scriptstyle k}\kern0pt}.$$ 18.46. If you have to do a lot of commutative diagrams, you will want to define some macros like those in the first few lines of this solution. The \matrix macro resets the baselines to \normalbaselines, because other commands like \openup might have changed them, so we redefine \normalbaselines in this solution. Some of the things shown here haven’t been explained yet, but Chapter 22 will reveal all. $$\def\normalbaselines{\baselineskip20pt \lineskip3pt \lineskiplimit3pt } \def\mapright#1{\smash{ \mathop{\longrightarrow}\limits^{#1}}} \def\mapdown#1{\Big\downarrow \rlap{\vcenter{\hbox{\scriptstyle#1}}}} \matrix{&&&&&&0\cr &&&&&&\mapdown{}\cr 0&\mapright{}&{\cal O}_C&\mapright\iota& \cal E&\mapright\rho&\cal L&\mapright{}&0\cr &&\Big\Vert&&\mapdown\phi&&\mapdown\psi\cr 0&\mapright{}&{\cal O}_C&\mapright{}& \pi_*{\cal O}_D&\mapright\delta& R^1f_*{\cal O}_V(-D)&\mapright{}&0\cr &&&&&&\mapdown{\theta_i\otimes\gamma^{-1}}\cr &&&&&&\hidewidth R^1f_*\bigl({\cal O} _V(-iM)\bigr)\otimes\gamma^{-1}\hidewidth\cr &&&&&&\mapdown{}\cr &&&&&&0\cr}$$ 19.1. \sum_{n=0}^\infty a_nz^n\qquad\hbox{converges if}\qquad |z|0 % something is being held over \line{}\kern-\topskip\nobreak\vfill\supereject\fi} \def\pagecontents{\ifvoid\topins\else\unvbox\topins\fi email protected]=\dp255 \unvbox255 \ifvoid\footins\else % footnote info is present \vskip\skip\footins \footnoterule \unvbox\footins\fi \[email protected] \kern-\[email protected] \vfil \fi} \def\footnoterule{\kern-3pt \hrule width 2truein \kern 2.6pt} % the \hrule is .4pt high 8. Hyphenation and everything else. The last part of plain.tex reads the hyphenation patterns and exceptions found on file hyphen.tex (see Appendix H); then it defines a few miscellaneous macros, sets up \rm type, and that’s all! \lefthyphenmin=2 \righthyphenmin=3 % disallow x- or -xx breaks \input hyphen % the hyphenation patterns and exceptions \def\magnification{\afterassignment\[email protected]\[email protected]} \def\[email protected]{\mag=\[email protected] \hsize6.5truein\vsize8.9truein\dimen\footins8truein} \def\tracingall{\tracingonline=1 \tracingcommands=2 \tracingstats=2 \tracingpages=1 \tracingoutput=1 \tracinglostchars=1 \tracingmacros=2 \tracingparagraphs=1 \tracingrestores=1 \showboxbreadth=\maxdimen \showboxdepth=\maxdimen \errorstopmode} \def\showhyphens#1{\setbox0=\vbox{\parfillskip0pt \hsize=\maxdimen \tenrm \pretolerance=-1 \tolerance=-1 \hbadness=0 \showboxdepth=0 \ #1}} \normalbaselines\rm % select roman font \nonfrenchspacing % punctuation affects the spacing \catcode‘@=12 % at signs are no longer letters \def\fmtname{plain}\def\fmtversion{3.0} % identifies the current format The format name and version number are recorded in control sequences, in order to help the people who might have to explain why something doesn’t work. Macro files like plain.tex should not be changed in any way, except with respect to preloaded fonts, unless the changes are authorized by the author of the macros. Appendix B: Basic Control Sequences The purpose of a programming system is to make a computer easy to use. To do this, it furnishes languages and various facilities that are in fact programs invoked and controlled by language features. But these facilities are bought at a price: the external description of a programming system is ten to twenty times as large as the external description of the computer system itself. The user finds it far easier to specify any particular function, but there are far more to choose from, and far more options and formats to remember. — FREDERICK P. BROOKS, JR., The Mythical Man Month (1975) When someone says, “I want a programming language in which I need only say what I wish done,” give him a lollipop. — ALAN PERLIS, Epigrams on Programming (1982) 365 (page 366) C Character Codes Appendix C: Character Codes Different computers tend to have different ways of representing the characters in files of text, but TEX gives the same results on all machines, because it converts everything to a standard internal code when it reads a file. TEX also converts back from its internal representation to the appropriate external code, when it writes a file of text; therefore most users need not be aware of the fact that the codes have actually switched back and forth inside the machine. The purpose of this appendix is to define TEX’s internal code, which has the same characteristics on all implementations of TEX. The existence of such a code is important, because it makes TEX constructions “portable.” For example, TEX allows alphabetic constants like ‘b to be used as numbers; the fact that ‘b always denotes the integer 98 means that we can write machine-independent macros that decide, for instance, whether a given character is a digit between 0 and 9. Furthermore the internal code of TEX also survives in its dvi output files, which can be printed by software that knows nothing about where the dvi data originated; essentially the same output will be obtained from all implementations of TEX, regardless of the host computer, because the dvi data is expressed in a machine-independent code. TEX’s internal code is based on the American Standard Code for Information Interchange, known popularly as “ASCII.” There are 128 codes, numbered 0 to 127; we conventionally express the numbers in octal notation, from ´000 to ´177 , or in hexadecimal notation, from ˝00 to ˝7F. Thus, the value of ‘b is normally called ´142 or ˝62, not 98. In the ASCII scheme, codes ´000 through ´040 and code ´177 are assigned to special functions; for example, code ´007 is called BEL, and it means “Ring the bell.” The other 94 codes are assigned to visible symbols. Here is a chart that shows ASCII codes in such a way that octal and hexadecimal equivalents can easily be read off: ´00x ´01x ´02x ´03x ´04x ´05x ´06x ´07x ´10x ´11x ´12x ´13x ´14x ´15x ´16x ´17x ´0 ´1 ´2 ´3 ´4 ´5 ´6 ´7 NUL BS DLE CAN SP ( 0 8 @ H P X ‘ h p x SOH HT DC1 EM ! ) 1 9 A I Q Y a i q y STX LF DC2 SUB " * 2 : B J R Z b j r z ETX VT DC3 ESC # + 3 ; C K S [ c k s { EOT FF DC4 FS , 4 < D L T \ d l t | ENQ CR NAK GS % 5 = E M U ] e m u } ACK SO SYN RS & . 6 > F N V ^ f n v ~ BEL SI ETB US ’ / 7 ? G O W _ g o w DEL ˝8 ˝9 ˝A ˝B ˝C ˝D ˝E ˝F ˝0x ˝1x ˝2x ˝3x ˝4x ˝5x ˝6x ˝7x 367 368 Appendix C: Character Codes Ever since ASCII was established in the early 1960s, people have had different ideas about what to do with positions ´000 –´037 and ´177 , because most of the functions assigned to those codes are appropriate only for special purposes like file transmission, not for applications to printing or to interactive computing. It turned out that manufacturers soon started producing line printers that were capable of generating 128 characters, 33 of which were tailored to the special needs of particular customers; part of the advantage of a standard code was therefore lost. On the other hand, the remaining 95 codes (including ´40 =SP, a blank space) have become widely adopted, and they are now implanted within most of today’s computer terminals. When an ASCII keyboard is available, you can specify each of the 128 codes to TEX in terms of the 95 standard characters, as follows: ´00x ´01x ´02x ´03x ´04x ´05x ´06x ´07x ´10x ´11x ´12x ´13x ´14x ´15x ´16x ´17x ´0 ´1 ´2 ´3 ´4 ´5 ´6 ´7 ^^@ ^^H ^^P ^^X Ã ( 0 8 @ H P X ‘ h p x ^^A ^^I ^^Q ^^Y ! ) 1 9 A I Q Y a i q y ^^B ^^J ^^R ^^Z " * 2 : B J R Z b j r z ^^C ^^K ^^S ^^[ # + 3 ; C K S [ c k s { ^^D ^^L ^^T ^^\ , 4 < D L T \ d l t | ^^E ^^M ^^U ^^] % 5 = E M U ] e m u } ^^F ^^N ^^V ^^^ & . 6 > F N V ^ f n v ~ ^^G ^^O ^^W ^^_ ’ / 7 ? G O W _ g o w ^^? ˝8 ˝9 ˝A ˝B ˝C ˝D ˝E ˝F ˝0x ˝1x ˝2x ˝3x ˝4x ˝5x ˝6x ˝7x (Here ‘^^’ doesn’t necessarily mean two circumflex characters; it means two identical characters whose current \catcode is 7. In such cases TEX simply adds or subtracts ´100 from the internal code of the character that immediately follows. For example, * can also be typed as ^^j; j can also be typed as ^^*.) An extended ASCII code intended for text editing and interactive computing was developed at several universities about 1965, and for many years there have been terminals in use at Stanford, MIT, Carnegie-Mellon, and elsewhere that have 120 or 121 symbols, not just 95. Aficionados of these keyboards (like the author of this book) are loath to give up their extra characters; it seems that such people make heavy use of about 5 of the extra 25, and occasional use of the other 20, although different people have different groups of five. For example, the author developed TEX on a keyboard that includes the symbols ←, ↓, ≠, ≤, and ≥, and he finds that this makes it much more Appendix C: Character Codes pleasant to type class notes, technical papers, and computer programs of the kind he likes to write; his logician friends make heavy use of the ∀ and ∃ keys; and so on. It is recommended that TEX implementations on systems with large character sets be consistent with the following codes: ´00x ´01x ´02x ´03x ´0 ´1 ´2 ´3 ´4 ´5 ´6 ´7 ⋅ λ ⊂ ← ( 0 8 @ H P X ‘ h p x ↓ γ ⊃ → ! ) 1 9 A I Q Y a i q y α δ ∩ ≠ " * 2 : B J R Z b j r z β ↑ ∪ ◊ # + 3 ; C K S [ c k s { ∧ ± ∀ ≤ , 4 < D L T \ d l t | ¬ ⊕ ∃ ≥ % − 5 = E M U ] e m u } ∈ ∞ ⊗ ≡ & . 6 > F N V ^ f n v ~ π ∂ ↔ ∨ ’ / 7 ? G O W _ g o w ∫ ˝8 ˝9 ˝A ˝B ˝C ˝D ˝E ˝F ´04x ´05x ´06x ´07x ´10x ´11x ´12x ´13x ´14x ´15x ´16x ´17x ˝0x ˝1x ˝2x ˝3x ˝4x ˝5x ˝6x ˝7x Of course, designers of TEX macro packages that are intended to be widely used should stick to the standard ASCII characters. Incidentally, the ASCII character ^ that appears in position ´136 is sometimes called a “caret,” but dictionaries of English tell us that a caret is a larger symbol, more like character ´004 in the extended set above. The correct name for ^ is “circumflex,” but this is quite a mouthful, so a shorter name like “hat” is preferable. It seems desirable to preserve the traditional distinction between caret and hat. The extended code shown above was developed at MIT; it is similar to, but slightly better than, the code implemented at Stanford. Seven of the codes are conventionally assigned to the standard ASCII control functions NUL (hnulli), HT (htabi), LF (hlinefeedi), FF (hformfeedi), CR (hreturni), ESC (hescapei), and DEL (hdeletei), and they appear in the standard ASCII positions; hence the corresponding seven characters ⋅ γ δ ± ⊕ ◊ ∫ do not actually appear on the keyboard. These seven “hidden” characters show up only on certain output devices. Modern keyboards allow 256 codes to be input, not just 128; so TEX represents characters internally as numbers in the range 0–255 (i.e., ´000 –´377 , or ˝00–˝FF). Implementations of TEX differ in which characters they will accept in input files and which they will transmit to output files; these subsets can be specified independently. A completely permissive version of TEX allows full 256-character input and output; other 369 370 Appendix C: Character Codes versions might ignore all but the visible characters of ASCII; still other versions might distinguish the tab character (code ´011 ) from a space on input, but might output each tab as a sequence of three characters ^^I. Many people, unfortunately, have the opposite problem: Instead of the 95 standard characters and some others, they have fewer than 95 symbols actually available. What can be done in such cases? Well, it’s possible to use TEX with fewer symbols, by invoking more control sequences; for example, plain TEX defines \lq, \rq, \lbrack, \rbrack, \sp, and \sb, so that you need not type ‘, ’, [, ], ^, and _, respectively. A person who implements TEX on computer systems that do not have 95 externally representable symbols should adhere to the following guidelines: (a) Stay as close as possible to the ASCII conventions. (b) Make sure that codes ´041 –´046 , ´060 –´071 , ´141 –´146 , and ´160 –´171 are present and that each unrepresentable internal code < ´200 leads to a representable code when ´100 is added or subtracted; then all 256 codes can be input and output. (c) Cooperate with everyone else who shares the same constraints, so that you all adopt the same policy. (See Appendix J for information about the TEX Users Group.) Very few conventions about character codes are hardwired into TEX: Almost everything can be changed by a format package that changes parameters like \escapechar and sets up the \catcode, \mathcode, \uccode, \lccode, \sfcode, and \delcode tables. Thus a TEX manuscript that has been written in Denmark, say, can be run in California, and vice versa, even though quite different conventions might be used in different countries. The only character codes that TEX actually “knows” are these: (1) INITEX initializes the code tables as described in Appendix B; the same initialization is done by all implementations of TEX. (2) TEX uses the character codes Ã+-.,‘’"0123456789ABCDEF in its syntax rules (Chapters 20, 24, and Appendix H), and it uses most of the uppercase and lowercase letters in its keywords pt, to, plus, etc. These same codes and keywords are used in all implementations of TEX. For example, when TEX is implemented for Cyrillic keyboards, the letter ‘Π’ should be assigned to code ´160 and ‘T’ to code ´164 , so that ‘ΠT’ still means ‘pt’; or else control sequences should be defined so that what TEX sees is equivalent to the keywords it needs. (3) The operations \number, \romannumeral, \the, and \meaning can generate letters, digits, spaces, decimal points, minus signs, double quotes, colons, and ‘>’ signs; these same codes are generated in all implementations of TEX. (4) The \hyphenation and \pattern commands described in Appendix H give special interpretation to the ten digits and to the characters ‘.’ and ‘-’. (5) The codes for the four characters . { } are inserted when TEX recovers from certain errors, and braces are inserted around an \output routine; appropriate catcodes are attached to these tokens, so it doesn’t matter if these symbols have their plain TEX meanings or not. (6) There is a special convention for representing characters 0–255 in the hexadecimal forms ^^00– ^^ff, explained in Chapter 8. This convention is always acceptable as input, when ^ is any character of catcode 7. Text output is produced with this convention only when representing characters of code ≥ 128 that a TEX installer has chosen not to output directly. Appendix C: Character Codes Code sets obtained by modifying the standard as shown above or by other replacements are nonstandard. — ASA SUBCOMMITTEE X3.2, American Standard Code for Information Interchange (1963) Both the Stanford and DEC uses of the ASCII control characters are in violation of the USA Standard Code, but no Federal Marshal is likely to come running out and arrest people who type control-T to their computers. — BRIAN REID, SCRIBE Introductory User’s Manual (1978) 371 (page 372) D Dirty Tricks Appendix D: Dirty Tricks TEX was designed to do the ordinary tasks of typesetting: to make paragraphs and pages. But the underlying mechanisms that facilitate ordinary typesetting— e.g., boxes, glue, penalties, and macros—are extremely versatile; hence people have discovered sneaky ways to coerce TEX into doing tricks quite different from what its author originally had in mind. Such clever constructions are not generally regarded as examples of “high TEX”; but many of them have turned out to be useful and instructive, worthy of being known (at least by a few wizards). The purpose of this appendix is to introduce crafty and/or courageous readers to the nether world of TEXarcana. Ä Ä Ä Ä Ä Ä Ä Ä Ä Ä Ä Please don’t read this material until you’ve had plenty of experience with plain TEX. After you have read and understood the secrets below, you’ll know all sorts of devious combinations of TEX commands, and you will often be tempted to write inscrutable macros. Always remember, however, that there’s usually a simpler and better way to do something than the first way that pops into your head. You may not have to resort to any subterfuge at all, since TEX is able to do lots of things in a straightforward way. Try for simple solutions first. 1. Macro madness. If you need to write complicated macros, you’ll need to be familiar with the fine points in Chapter 20. TEX’s control sequences are divided into two main categories, “expandable” and “unexpandable”; the former category includes all macros and \if...\fi tests, as well as special operations like \the and \input, while the latter category includes the primitive commands listed in Chapter 24. The expansion of expandable tokens takes place in TEX’s “mouth,” but primitive commands (including assignments) are done in TEX’s “stomach.” One important consequence of this structure is that it is impossible to redefine a control sequence or to advance a register while TEX is expanding the token list of, say, a \message or \write command; assignment operations are done only when TEX is building a vertical or horizontal or math list. For example, it’s possible to put \n asterisks into a paragraph, by saying simply ‘{\loop\ifnum\n>0 *\advance\n-1 \repeat}’. But it’s much more difficult to define a control sequence \asts to consist of exactly \n consecutive asterisks. If \n were known to be at most 5, say, it would be possible to write \edef\asts{\ifcase\n\or*\or**\or***\or****\or*****\else\bad\fi} since TEX handles \ifcase in its mouth. But for general \n it would be impossible to use a construction like ‘\edef\asts{\loop\ifnum\n>0 *\advance\n-1 \repeat}’, since \n doesn’t change during an \edef. A more elaborate program is needed; e.g., {\xdef\asts{} \loop\ifnum\n>0 \xdef\asts{\asts*}\advance\n-1 \repeat} And here’s another solution (which is faster, because token list registers can be expanded more quickly than macros, using \the): \newcount\m \newtoks\t \m=\n \t={} \loop \ifnum\m>0 \t=\expandafter{\the\t *} \advance\m-1 \repeat \edef\asts{\the\t} 373 374 Appendix D: Dirty Tricks However, both of these solutions have a running time proportional to the square of \n. There’s a much quicker way to do the job: \begingroup\aftergroup\edef\aftergroup\asts\aftergroup{ \loop \ifnum\n>0 \aftergroup*\advance\n-1 \repeat \aftergroup}\endgroup Get it? The \aftergroup commands cause a whole list of other tokens to be saved up for after the group! This method has only one flaw, namely that it takes up \n cells of space on TEX’s input stack and \n more on TEX’s save stack; hence a special version of TEX may be required when \n is larger than 150 or so. (Incidentally, there’s a completely different way to put \n asterisks into a paragraph, namely to say ‘\setbox0=\hbox{*}\cleaders\copy0\hskip\n\wd0’. This may seem to be the fastest solution of all; but actually it is not so fast, when all things are considered, since it generates four bytes of dvi output per asterisk, compared to only one byte per asterisk in the other methods. Input/output time takes longer than computation time, both in TEX itself and in the later stages of the printing process.) The problem just solved may seem like a rather special application; after all, who needs a control sequence that contains a variable number of asterisks? But the same principles apply in other similar cases, e.g., when you want to construct a variablelength \parshape specification. Similarly, many of the “toy problems” solved below are meant to illustrate paradigms that can be used in real-life situations. The precise rules for expansion are explained in Chapter 20; and the best way to get familiar with TEX’s expansion mechanism is to watch it in action, looking at the log file when \tracingmacros=2 and \tracingcommands=2. One of the important ways to change the normal order of expansion is to use \expandafter; the construction \expandafter\a\b causes \b to be expanded first, then \a. And since \expandafter is itself expandable, the construction \expandafter\expandafter\expandafter\a\expandafter\b\c causes \c to be expanded first, then \b, then \a. (The next step, \expandafter\expandafter\expandafter\expandafter \expandafter\expandafter\expandafter\a \expandafter\expandafter\expandafter\b\expandafter\c\d is probably too lengthy to be of any use.) It’s possible to make good use of \expandafter\a\b even when \a isn’t expandable. For example, the token list assignment ‘\t=\expandafter{\the\t *}’ in the example on the previous page was able to invade territory where expansion is normally suppressed, by expanding after a left brace. Similarly, \t=\expandafter{\expandafter*\the\t} would have worked; and \uppercase\expandafter{\romannumeral\n} yields the value of register \n in uppercase roman numerals. Appendix D: Dirty Tricks Here’s a more interesting example: Recall that \fontdimen1 is the amount of “slant per point” of a font; hence, for example, ‘\the\fontdimen1\tenit’ expands to ‘0.25pt’, where the characters ‘pt’ are of category 12. After the macro definitions {\catcode‘p=12 \catcode‘t=12 \gdef\\#1pt{#1}} \let\getfactor=\\ \def\kslant#1{\kern\expandafter\getfactor\the\fontdimen1#1\ht0} one can write, e.g., ‘\kslant\tenit’ and this will expand to ‘\kern0.25\ht0’. If the boundary of \box0 is considered to be slanted by 0.25 horizontal units per vertical unit, this kern measures the horizontal distance by which the top edge of the box is skewed with respect to an edge at the baseline. All of the computation of \kslant is done in TEX’s mouth; thus, the mouth can do some rather complicated things even though it cannot assign new values. (Incidentally, an indirect method was used here to define the control sequence \getfactor when the character t had category 12, since control words normally consist only of letters. The alternative construction {\catcode‘p=12 \catcode‘t=12 \csname expandafter\endcsname\gdef \csname getfactor\endcsname#1pt{#1}} would also have worked, since \csname and \endcsname don’t contain ‘p’ or ‘t’ !) The mechanism by which TEX determines the arguments of a macro can be applied in unexpected ways. Suppose, for example, that \t is a token list register that contains some text; we wish to determine if at least one asterisk (*12 ) appears in that text. Here’s one way to do it: \newif\ifresult % for the result of a computed test \def\atest#1{\expandafter\a\the#1*\atest\a} \long\def\a#1*#2#3\a{\ifx\atest#2\resultfalse\else\resulttrue\fi} Now after ‘\atest\t’, the control sequence \ifresult will be \iftrue or \iffalse, depending on whether or not \t contains an asterisk. (Do you see why?) And here’s a slightly more elegant way to do the same thing, using \futurelet to look ahead: \def\btest#1{\expandafter\b\the#1*\bb} \long\def\b#1*{\futurelet\next\bb} \long\def\bb#1\bb{\ifx\bb\next\resultfalse\else\resulttrue\fi} In both cases the solution works if \t contains control sequence tokens as well as character tokens, provided that the special control sequences \atest, \a, and \bb don’t appear. Notice, however, that an asterisk is “hidden” if it appears within a group {...}; the test is limited to asterisks at nesting level zero. A token list register is always balanced with respect to grouping, so there is no danger of the test leading to error messages concerning missing braces or extra braces. We can apply the ideas in the preceding paragraph to solve a problem related to generalized math formatting: The goal is to set TEX up so that the respective constructions ‘ α ’, ‘ α \eqno β ’, and ‘ α \leqno β ’ will cause a macro \generaldisplay to be invoked, with \eq defined to be α; furthermore, the test \ifeqno should be true when an equation number β is present, and \ifleqno should be true in the case of \leqno. When β is present, it should be stored in \eqn. Here 375 376 Appendix D: Dirty Tricks α and β are arbitrary balanced token lists that don’t contain either \eqno or \leqno at nesting level zero. The following macros do the required maneuvers: \newif\ifeqno \newif\ifleqno \everydisplay{\displaysetup} \def\displaysetup#1{\displaytest#1\eqno\eqno\displaytest} \def\displaytest#1\eqno#2\eqno#3\displaytest{% \if!#3!\ldisplaytest#1\leqno\leqno\ldisplaytest \else\eqnotrue\leqnofalse\def\eqn{#2}\def\eq{#1}\fi \generaldisplay} \def\ldisplaytest#1\leqno#2\leqno#3\ldisplaytest{\def\eq{#1}% \if!#3!\eqnofalse\else\eqnotrue\leqnotrue\def\eqn{#2}\fi} An examination of the three cases α , α\eqno β , α\leqno β shows that the correct actions will ensue. Parameter #3 in the tests ‘\if!#3!’ will be either empty or \eqno or \leqno; thus, the condition will be false (and the second ‘!’ will be skipped) unless #3 is empty. Returning to the problem of *’s in \t, suppose that it’s necessary to consider *’s at all levels of nesting. Then a slower routine must be used: \def\ctest#1{\resultfalse\expandafter\c\the#1\ctest} \def\c{\afterassignment\cc\let\next= } \def\cc{\ifx\next\ctest \let\next\relax \else\ifx\next*\resulttrue\fi\let\next\c\fi \next} Here \afterassignment has been used to retain control after a non-future \let; the ‘= ’ ensures that exactly one token is swallowed per use of \c. This routine could be modified in an obvious way to count the total number of *’s and/or tokens in \t. Notice the ‘\let\next’ instructions in \cc; it should be clear why the alternative \def\cc{\ifx\next\ctest\else\ifx\next*\resulttrue\fi\c\fi} would not work. (The latter \c would always swallow a ‘\fi’.) Space tokens are sometimes anomalous, so they deserve special care. The following macro \futurenonspacelet behaves essentially like \futurelet except that it discards any implicit or explicit space tokens that intervene before a nonspace is scanned: \def\futurenonspacelet#1{\def\cs{#1}% \afterassignment\stepone\let\nexttoken= } \def\\{\let\stoken= } \\ % now \stoken is a space token \def\stepone{\expandafter\futurelet\cs\steptwo} \def\steptwo{\expandafter\ifx\cs\stoken\let\next=\stepthree \else\let\next=\nexttoken\fi \next} \def\stepthree{\afterassignment\stepone\let\next= } An operation like \futurenonspacelet is useful, for example, when implementing macros that have a variable number of arguments. Notice that ‘\def\stepthree#1{\stepone}’ would not work here, because of TEX’s rule that a Ã10 token is bypassed if it would otherwise be treated as an undelimited argument. Because of this rule it is difficult to distinguish explicit space tokens from implicit ones. The situation is surprisingly complex, because it’s possible Appendix D: Dirty Tricks to use \uppercase to create “funny space” tokens like *10 ; for example, the commands \uccode‘ =‘* \uppercase{\uppercase{\def\fspace{ }\let\ftoken= } } make \fspace a macro that expands to a funny space, and they make \ftoken an implicit funny space. (The tests \if\fspace*, \if\ftoken*, \ifcat\fspace\stoken, and \ifcat\ftoken\stoken will all be true, assuming that * has category 12; but if * has category 10, \if\fspace* will be false, because TEX normalizes all newly created space tokens to Ã10 , as explained in Chapter 8.) Since the various forms of space tokens are almost identical in behavior, there’s no point in dwelling on the details.† The argument to \write is expanded when a \shipout occurs, but sometimes expansion isn’t desired. Here’s a macro (suggested by Todd Allen) that suppresses all expansion, by inserting \noexpand before each control sequence or active character. The macro assumes that ~ is an active character, and that the tokens being written do not include implicit spaces or braces. Funny spaces are changed to ordinary ones. \long\def\unexpandedwrite#1#2{\def\finwrite{\write#1}% {\aftergroup\finwrite\aftergroup{\sanitize#2\endsanity}}} \def\sanitize{\futurelet\next\sanswitch} \def\sanswitch{\ifx\next\endsanity \else\ifcat\noexpand\next\stoken\aftergroup\space\let\next=\eat \else\ifcat\noexpand\next\bgroup\aftergroup{\let\next=\eat \else\ifcat\noexpand\next\egroup\aftergroup}\let\next=\eat \else\let\next=\copytoken\fi\fi\fi\fi \next} \def\eat{\afterassignment\sanitize \let\next= } \long\def\copytoken#1{\ifcat\noexpand#1\relax\aftergroup\noexpand \else\ifcat\noexpand#1\noexpand~\aftergroup\noexpand\fi\fi \aftergroup#1\sanitize} \def\endsanity\endsanity{} As before, the heavy use of \aftergroup in \unexpandedwrite means that parameter #2 should not include more than about 150 tokens. † The following little program is for TEX exegetes who insist on learning the whole story: Macro \stest decides whether or not the first token of a given token list register is a hspace tokeni as defined in Chapter 24. If so, the macro decides whether or not the token is “funny,” i.e., whether or not the character code is different from an ASCII hspacei; the macro also decides whether a space token is explicit or implicit. \newif\ifspace \newif\iffunny \newif\ifexplicit \def\stest#1{\expandafter\s\the#1! \stest} \def\s{\funnyfalse \global\explicitfalse \futurelet\next\ss} \def\ss{\ifcat\noexpand\next\stoken \spacetrue \ifx\next\stoken \let\next=\sss \else\let\next=\ssss \fi \else \let\next=\sssss \fi \next} \long\def\sss#1 #2\stest{\def\next{#1}% \ifx\next\empty \global\explicittrue \fi} \long\def\ssss#1#2\stest{\funnytrue {\uccode‘#1=‘~ \uppercase{\ifcat\noexpand#1}\noexpand~% active funny space \else \escapechar=\if*#1‘?\else‘*\fi \if#1\string#1\global\explicittrue\fi \fi}} \long\def\sssss#1\stest{\spacefalse} 377 378 Appendix D: Dirty Tricks 2. List macros. The next several macros we shall discuss can be used to maintain lists of information in the form \\{hitem1 i}\\{hitem2 i} . . . \\{hitemn i} where each hitemi is a balanced list of tokens. A parameterless control sequence whose replacement text has this form may be called a list macro. The empty list macro has n = 0 and it is called \empty. It’s easy to add new items at either end of a list macro, and to concatenate list macros, for example as follows: \toksdef\ta=0 \toksdef\tb=2 % token list registers for temp use \long\def\leftappenditem#1\to#2{\ta={\\{#1}}\tb=\expandafter{#2}% \edef#2{\the\ta\the\tb}} \long\def\rightappenditem#1\to#2{\ta={\\{#1}}\tb=\expandafter{#2}% \edef#2{\the\tb\the\ta}} \def\concatenate#1=#2{\ta=\expandafter{#2}\tb=\expandafter{#3}% \edef#1{\the\ta\the\tb}} Conversely, the left item of a list can be removed and placed in a control sequence by the \lop macro defined in the following curious way: \def\lop#1\to#2{\expandafter\lopoff#1\lopoff#1#2} \long\def\lopoff\\#1#2\lopoff#3#4{\def#4{#1}\def#3{#2}} For example, if \l expands to the list ‘\\{a\b}\\{c}\\{{d}}’, the macro invocation \lop\l\to\z makes \l expand to ‘\\{c}\\{{d}}’ and \z expand to ‘a\b’. The \lop operation should be used only when \l is nonempty, otherwise an error will occur; to test if \l is empty, one simply says ‘\ifx\l\empty’. The programming details of the \lop macro indicate why individual items have been enclosed in {...} groups. A simpler kind of list, in which grouping is omitted and an extra \\ appears at the end, suffices for many purposes; one could define, for instance, \long\def\lopoff\\#1\\#2\lopoff#3#4{\def#4{#1}\def#3{\\#2}} and the results would be almost the same as before. In this case an empty list macro expands to ‘\\’. However, the new \lop resulting from this new \lopoff macro also removes a pair of braces, if the leftmost item happens to be a group; extra braces are included in our general scheme to prevent such anomalies. So far the examples we’ve considered haven’t revealed why the \\’s appear in the general scheme; it appears that grouping by itself should be enough. But in fact, the \\ separators are enormously useful, because we can define \\ to be any desired one-argument macro, and then we can execute the list! For example, here’s a way to count the number of items: \def\cardinality#1\to#2{#2=0 \long\def\\##1{\advance#2 by1 }#1} (Parameter #2 is supposed to be the name of a count register.) And here’s a way to take a list macro and center all its items on individual lines within a \vbox: \def\centerlist#1{\def\\##1{\relax##1\cr}% \vbox{\halign{\hfil##\hfil\cr#1}}} Appendix D: Dirty Tricks A particular item can be selected by its position number from the left: \def\select#1\of#2\to#3{\def#3{\outofrange}% \long\def\\##1{\advance#1-1 \ifnum#1=0 \def#3{##1}\fi}#2} (Here #1 is a count register, #2 is a list macro, and #3 is a control sequence.) And so on; hundreds of other applications can be imagined.† TEX does all of the preceding operations efficiently, in the sense that the running time will be proportional to the length of the list macro involved. It’s natural to ask if the rightmost item can be removed with equal efficiency, since the final item of a list is somewhat hard to isolate. There is apparently no way to delete the nth item of an n-item list in order n steps, maintaining complete generality, unless the \aftergroup trick (by which we created a macro that expands to n asterisks) is used; and the \aftergroup trick is somewhat unattractive in the list application, because the list might be quite long.‡ However, if we restrict list items to unexpandable tokens, it turns out to be possible to remove the rightmost item quite efficiently: \def\deleterightmost#1{\edef#1{\expandafter\xyzzy#1\xyzzy}} \long\def\xyzzy\\#1#2{\ifx#2\xyzzy\yzzyx \else\noexpand\\{#1}\fi\xyzzy#2} \long\def\yzzyx#1\xyzzy\xyzzy{\fi} Careful study of this example shows that TEX’s mouth is capable of doing recursive operations, given sufficiently tricky macros. The contents of a \count register can easily be converted to decimal and stored in a control sequence; for example, if \n is a register, ‘\edef\csn{\the\n}’ puts its value into \csn. Conversely, a value from \csn can be put back into \n by saying simply ‘\n=\csn’. There’s usually no point in doing this transformation just to minimize the usage of \count registers, since TEX has 256 of them; but a decimal representation like the expansion of \csn can be stored in a list macro, and that might be useful in some applications. Incidentally, there’s a neat way to test if such a control-sequencenumber is zero: ‘\if0\csnhtrue texti\elsehfalse texti\fi’ works because extra digits of a nonzero number will be ignored with the htrue texti. A technique something like list macros can be used to maintain unordered sets of control sequences. In this case it’s convenient to leave off the braces; for example, \def\l{\\\alpha\\\beta\\\gamma} defines a “set macro” \l that represents the control sequences { \alpha, \beta, \gamma }. A straightforward construction tests whether a given control sequence is in the set: \def\ismember#1\of#2{\resultfalse\def\given{#1}% \def\\##1{\def\next{##1}\ifx\next\given\resulttrue\fi}#2} And an efficient but not-so-straightforward construction removes all occurrences of † The concept of a list macro is strongly related to the concept of a list procedure in a programming language; see Communications of the ACM 7 (1964), 280. ‡ The interested reader may enjoy constructing a macro that removes the kth item of an n-item list macro \l in O(n log n) steps, given k and \l, without using \aftergroup. 379 380 Appendix D: Dirty Tricks control sequences that are \ifx-equivalent to a given control sequence: \def\remequivalent#1\from#2{\let\given=#1% \ifx#2\empty\else\edef#2{\expandafter\plugh#2\plugh}\fi} \def\plugh\\#1#2{\ifx#1\given\else\noexpand\\\noexpand#1\fi \ifx#2\plugh\hgulp\fi\plugh#2} \def\hgulp\fi\plugh\plugh{\fi} 3. Verbatim listing. Plain TEX includes a macro called \dospecials that is essentially a set macro, representing the set of all characters that have a special category code. (The control sequence \do plays the rˆ ole of \\ in the discussion above.) Therefore it’s easy to change all of the special characters to category 12 (other): \def\uncatcodespecials{\def\do##1{\catcode‘##1=12 }\dospecials} This works even when the set of special characters has been changed, provided that \dospecials has been updated to represent the current set. The operation \uncatcodespecials just defined is important, of course, when TEX’s automatic features need to be temporarily disabled. Let’s suppose that we want to create a listing of some computer file, reproducing the characters and the spacing exactly as they appear in the file. To make the problem more interesting, let’s also print line numbers in front of each line, as in the listing of story.tex on page 24. To make the problem simpler, let’s assume that the file contains only standard ASCII printing characters: no tab marks or form feeds or such things. Our goal is to devise a \listing macro such that, e.g., ‘\listing{story}’ will insert a listing of the story.tex file into a manuscript, after which TEX’s normal conventions will be restored. The listing should be in \tt type. A macro of the following form meets the desired specifications: \def\listing#1{\par\begingroup\setupverbatim\input#1 \endgroup} Notice that the \endgroup command here will nicely “turn off” all the weird things that \setupverbatim turns on. Notice also that the commands ‘\input#1 \endgroup’ will not be listed verbatim, even though they follow \setupverbatim, since they entered TEX’s reading mechanism when the \listing macro was expanded (i.e., before the verbatim business was actually set up). But what should \setupverbatim do? Well, it ought to include \obeylines, since this automatically inserts a \par at the end of each line that is input; it ought to include \uncatcodespecials, so that special characters print as themselves; and it ought to include \obeyspaces, so that each space counts. But we need to look carefully at each of these things to see exactly what they do: (1) Plain TEX’s \obeylines macro changes the \catcode of ^^M to \active, and then it says ‘\let^^M=\par’. Since ^^M is placed at the end of each line, this effectively ends each line with \par; however, \obeylines doesn’t say ‘\def^^M{\par}’, so we must make any desired changes to \par before invoking \obeylines. (2) The \uncatcodespecials operation changes a space to category 12; but the \tt font has the character ‘Ã’ in the hspacei position, so we don’t really want Ã12 . (3) The \obeyspaces macro in Appendix B merely changes the hspacei character to category 13; active character Ã13 has been defined to be the same as \space, a macro that expands to Ã10 . This is usually what is desired; for example, it means that spaces in constructions like ‘\hbox to 10 pt {...}’ won’t cause any trouble. But in our application it has an undesirable effect, because it produces spaces that are affected by the space factor. To defeat this feature, it’s necessary either to Appendix D: Dirty Tricks say \frenchspacing or to redefine Ã13 to be the same as \Ã. The latter alternative is better, because the former will discard spaces at the beginning of each line. The \setupverbatim macro should also take care of putting a line number into the position of the paragraph indentation. We can take care of this by introducing a counter variable and using \everypar, as follows: \newcount\lineno % the number of file lines listed \def\setupverbatim{\tt \lineno=0 \obeylines \uncatcodespecials \obeyspaces \everypar{\advance\lineno by1 \llap{\sevenrm\the\lineno\ \ }}} {\obeyspaces\global\let =\ } % let active space = control space In theory, this seems like it ought to work; but in practice, it fails in two ways. One rather obvious failure—at least, it becomes obvious when the macro is tested—is that all the empty lines of the file are omitted. The reason is that the \par command at the end of an empty line doesn’t start up a new paragraph, because it occurs in vertical mode. The other failure is not as obvious, because it occurs much less often: The \tt fonts contain ligatures for Spanish punctuation, so the sequences ?‘ and !‘ will be printed as ¿ and ¡ respectively. Both of these defects can be cured by inserting \def\par{\leavevmode\endgraf} \catcode‘\‘=\active before \obeylines in the \setupverbatim macro, and by defining ‘ 13 as follows: {\catcode‘\‘=\active \gdef‘{\relax\lq}} A similar scheme could be used to produce verbatim listings in other fonts; but more characters would have to be made active, in order to break ligatures and to compensate for ASCII characters that aren’t present. Instead of listing a file verbatim, you might want to define a \verbatim macro such that ‘\verbatim{this is {\it!}}’ yields ‘this is {\it!}’. It’s somewhat dangerous to change category codes, because TEX stamps the category on each character when that character is first read from a file. Thus, if \verbatim were defined by a construction of the form \long\def\verbatim#1{hsomethingi}, argument #1 would already be converted to a list of tokens when hsomethingi starts; \catcode changes would not affect the argument. The alternative is to change category codes before scanning the argument to \verbatim: \def\verbatim{\begingroup\tt\uncatcodespecials \obeyspaces\doverbatim} \newcount\balance {\catcode‘=2 \catcode‘\{=12 \catcode‘\}=12 \gdef\doverbatim{ \gdef\verbatimloop#1> This works; but it’s slow, and it allows verbatim setting only of text that has balanced braces. It would not be suitable for typesetting the examples in a book like The TEXbook. (Appendix E contains the verbatim macros that were actually used.) Note also that if this \verbatim{...} macro appears in the argument to another macro like 381 382 Appendix D: Dirty Tricks \centerline, it will fail because the category codes can no longer be changed. The \footnote macro in Appendix B is careful to avoid scanning its argument prematurely; it uses \bgroup and \egroup in a somewhat tricky way, so that category code changes are permitted inside plain TEX footnotes. On the other hand, there is a fairly fast way to convert a token list to an almost-verbatim transcript: \long\def\verbatim#1{\def\next{#1}% {\tt\frenchspacing\expandafter\strip\meaning\next}} \def\strip#1>{} Tokens are stripped off in this construction since, for example, \meaning\next might be ‘macro:->this is {\it !}’. Notice that a space will be inserted after the control word \it, but no space might actually have occurred there in the argument to \verbatim; such information has been irretrievably lost. One of the problems with verbatim mode is that it’s hard to stop; if we turn off all of TEX’s normal control capabilities, we end up “painting ourselves into a corner” and reaching a point of no return. The \listing macro was able to solve this problem because the end of a file brings an old token list back to life. Another solution would be to specify a certain number of lines, after which verbatim mode should end. Otherwise it’s necessary to put some constraint on the text, i.e., to make certain texts unprintable in verbatim mode. For example, here’s an approach that typesets everything between \beginverbatim and \endverbatim, assuming only that the control sequence \endverbatim does not need to be set: \def\beginverbatim{\par\begingroup\setupverbatim\doverbatim} {\catcode‘\|=0 \catcode‘\\=12 % | is temporary escape character |obeylines|gdef|doverbatim^^M#1\endverbatim{#1|endgroup}} This construction assumes that \beginverbatim appears at the end of a line in the manuscript file. Argument #1 will be read entirely into TEX’s memory before anything happens, so the total amount of verbatim material had better not be too voluminous. Incidentally, it isn’t necessary to say that this macro is \long, because the \par’s inserted by \obeylines are really ^^M’s. Another approach is to keep one character untouchable. For example, it’s possible to define things so that ‘\verbatimhcharihtextihchari’ will typeset the htexti verbatim, where the htexti is not supposed to contain any occurrences of the repeated delimiter hchari: \def\verbatim{\begingroup\setupverbatim\doverbatim} \def\doverbatim#1{\def\next##1#1{##1\endgroup}\next} 4. Selective loading of macros. Some interesting problems arise when a computer system acquires a large library of macro files. For example, suppose that a file macs.tex contains the lines \let\italcorr=\/ \def\/{\unskip\italcorr} because somebody thought it would be nice to allow an optional space before TEX’s primitive \/ command. That’s fine, except if macs.tex is input twice; for example, two other macro files might both say \input macs. When those lines are processed the second time, \italcorr will be \let equal to a macro that expands to ‘\unskip\italcorr’, Appendix D: Dirty Tricks and you can guess what will happen: TEX will get into an infinite loop, stoppable only by interrupting the program manually. Fortunately there’s an easy way to prevent this problem, by placing a suitable interlock near the beginning of every macro file that might introduce such anomalies: \ifx\macsisloaded\relax\endinput\else\let\macsisloaded=\relax\fi Then \macsisloaded will be undefined at the time of the first \ifx, but the file will not be read twice. A different control sequence should, of course, be used for each file. Another difficulty with large sets of macros is that they take up space. It would be nice to preload every macro that every TEX user has ever dreamed up; but there might not be enough room, because TEX’s memory capacity is finite. You might find it necessary to hold back and to load only the macros that are really needed. How much memory space does a macro require? Well, there are four kinds of memory involved: token memory, name memory, string memory, and character memory. (If any of these becomes too full, it will be necessary to increase what TEX calls the macro memory size, the hash size, the number of strings, and/or the pool size, respectively; see Chapter 27.) The token memory is most important; a macro takes one cell of token memory for each token in its definition, including the ‘{’ and the ‘}’. For example, the comparatively short definition \def\example#1\two{\four} takes five tokens: #1, two , {1 , four , and }2 . Each control sequence also takes up one cell of name memory, one cell of string memory, and as many cells of character memory as there are characters in the name (seven in the case of \example). Character memory is comparatively cheap; four characters, or in some cases five, will fit in the same number of bits as a single cell of token memory, inside the machine. Therefore you don’t save much by choosing short macro names. TEX will tell you how close you come to exceeding its current memory capacity if you say \tracingstats=1. For example, one of the runs that the author made while testing galley proofs of this appendix reported the following statistics: Here is how much of TeX’s memory you used: 209 strings out of 1685 1659 string characters out of 17636 27618 words of memory out of 52821 1172 multiletter control sequences out of 2500 Consequently there was plenty of room for more macros: 52821 − 27618 = 25203 unused cells of main memory, 2500 − 1172 = 1328 of name memory, 1685 − 209 = 1476 of string memory, and 17636 − 1659 = 15977 of character memory. But a fairly large TEX was being used, and only the macros of Appendices B and E were loaded; in other circumstances it might have been necessary to conserve space. One obvious way to keep from loading too many macros is to keep the macro files short and to \input only the ones that you need. But short files can be a nuisance; sometimes there’s a better way. For example, let’s suppose that a file contains five optional classes of macros called A, B, C, D, E, and that a typical user will probably want only at most two or three of these five; let’s design a \load macro so that, for example, ‘\load{macs}{AC}’ will load file macs.tex including options A and C but not 383 384 Appendix D: Dirty Tricks options B, D, or E. The following \load macro converts its second argument into a set macro called \options: \def\load#1#2{\let\options=\empty \addoptions#2\end \input#1 } \def\addoptions#1{\ifx#1\end \let\next=\relax \else\let\\=\relax\edef\options{\options\\#1}% \let\next=\addoptions \fi \next} Inside the file macs.tex, a portion of code that should be loaded only under option B, say, can be enclosed by ‘\ifoption B ... \fi’, where \ifoption is defined thus: \def\ifoption#1{\def\\##1{\if##1#1\resulttrue\fi}% \resultfalse \options \ifresult} (This is a simple application of ideas presented earlier in this appendix.) However, the \ifoption...\fi scheme isn’t very robust, because it requires all of the macros in the optional part to be well nested with respect to \if... and \fi; a macro like \ifoption itself couldn’t easily be defined in such a place! There’s a better scheme that also runs faster, based on category code changes. This idea (due to Max D´ıaz) requires that the leftmost nonblank character on each line be either ‘\’ or ‘{’; it’s usually easy to arrange this. Furthermore, one other symbol, say ~, is reserved. Then the text material that is to be loaded only under option B is preceded by the line ‘\beginoption B’ and followed by a line that says ‘~endoptionalcode’. The \catcode for ~ is set to 14 (comment character), hence the ~endoptionalcode line will have no effect if code is not being skipped. The \beginoption macro works like this: \def\beginoption#1{\ifoption#1\else\begingroup\swapcategories\fi} \def\swapcategories{\catcode‘\\=14 \catcode‘\{=14 \catcode‘\~=0 } \let\endoptionalcode=\endgroup \catcode‘\~=14 Once the categories have been swapped, all lines will be skipped at high speed until the control sequence ~endoptionalcode is encountered; then everything will be restored to its former state. Under this scheme, material that should be loaded only under both options B and D can be prefaced by both ‘\beginoption B’ and ‘\beginoption D’; material that should be loaded under either option B or option D (or both) can be prefaced by \beginoption B ~oroption D if we define \oroption#1 to be an abbreviation for ‘\ifoption#1\endgroup\fi’. Another kind of selective loading is sometimes appropriate, based on whether or not a particular control sequence is defined. In this scheme, if the control sequence is undefined, it should remain undefined and it should take up no space whatever in TEX’s memory. There’s a slick way to do this, namely to say \ifx\cs\undefined ... \fi (assuming that \undefined has never been defined). TEX does not put undefined control sequences into its internal tables if they follow \ifx or if they are encountered while skipping conditional text. You can use this idea, for example, to prepare a bibliography for a paper, by reading a suitably arranged bibliography file; only the entries that correspond to defined control sequences will be loaded. Appendix D: Dirty Tricks 5. Brace hacks. Several of TEX’s operations depend on grouping, and you’ll want to know exactly what this means if you try to do certain tricky things. For example, plain TEX’s control sequences \bgroup and \egroup are “implicit braces” because they have been defined by \let\bgroup={ \let\egroup=} This means that you can include them in the replacement texts of definitions without worrying about how they nest; for example, the macros \def\beginbox{\setbox0=\hbox\bgroup} \def\endbox{\egroup\copy0 } allow you to make a box between \beginbox and \endbox; the behavior is almost the same as \def\beginbox#1\endbox{\setbox0=\hbox{#1}\copy0 } but different in three important ways: (1) The first alternative allows category codes to change inside the box. (2) The first alternative is faster, because it doesn’t need to scan the box contents both as an argument and as a sequence of actual commands. (3) The first alternative takes less memory space, because no argument needs to be stored. Thus, the first alternative is usually superior. For the purposes of this discussion we shall assume that only ‘{’ has category 1 and that only ‘}’ has category 2, although any characters can actually be used as group delimiters. Group nesting is crucial during two of TEX’s main activities: (a) when TEX is scanning a hbalanced texti, e.g., when TEX is forming the replacement text of a macro, a parameter, or a token list variable; (b) when TEX must determine whether the token & or \span or \cr or \crcr is the end of an entry within an alignment. TEX’s mouth has two internal counting mechanisms to deal with nesting: The “master counter” goes up by 1 for each {1 scanned by TEX, and down by 1 for each }2 ; the “balance counter” is similar, but it is affected only by explicit {1 and }2 tokens that are actually contributed to a token list that is being formed. The master counter decreases by 1 when TEX evaluates the alphabetic constant ‘{, and it increases by 1 when TEX evaluates ‘}, hence the net change is zero when such constants are evaluated. As a consequence of these rules, certain constructions produce the following effects: Input { \bgroup \iffalse{\fi \ifnum0=‘{\fi Master counter change expanded unexpanded 1 1 0 0 1 1 0 1 Balance counter change expanded unexpanded 1 1 0 0 0 1 0 1 The last two cases produce no begin-group tokens when expanded, but they do affect the master counter as shown. Thus, for example, \def\eegroup{\ifnum0=‘{\fi}} makes \eegroup behave rather like \egroup, but the expansion of \eegroup also decreases the master counter. Alignment processing uses only the master counter, not the balance counter. An alignment entry ends with the first & or \span or \cr or \crcr that appears when 385 386 Appendix D: Dirty Tricks the master counter has the value that was present in the counter at the beginning of the entry. Thus, for example, the curious construction \halign{\show\par#\relax\cr \global\let\par=\cr {\global\let\par=\cr}\cr \par} causes TEX to perform three \show instructions, in which the respective values of \par shown are \par, \relax, and \cr. Similarly, each template in the preamble to an alignment ends with the first & or \cr or \crcr that appears at the master counter level that was in effect at the beginning of the entry; hence & and \cr and \crcr tokens can appear within a template of an alignment, if they are hidden by braces (e.g., if they appear in a definition). These facts allow us to draw two somewhat surprising conclusions: (1) If an alignment entry has the form ‘ α \iffalse{\fi β \iffalse}\fi γ ’, it’s possible for β to include & and \cr tokens that aren’t local to a group.* (2) The construction {\span\iffalse}\fi appearing in a preamble contributes ‘{’ to the template without any net change to the master counter; thus, it’s very much like \bgroup, except that it produces {1 explicitly. If you understand (1) and (2), you’ll agree that the present appendix deserves its name. 6. Box maneuvers. Let’s turn now from syntax to semantics, i.e., from TEX’s mouth to its gastro-intestinal tract. Sometimes an odd symbol is needed in boldface type, but it’s available only in a normal weight. In such cases you can sometimes get by with “poor man’s bold,” obtained by overprinting the normal weight symbol with slight offsets. The following macro typesets its argument three times in three slightly different places, equidistant from each other; but the result takes up just as much space as if \pmb had been simply \hbox: \def\pmb#1{\setbox0=\hbox{#1}% \kern-.025em\copy0\kern-\wd0 \kern.05em\copy0\kern-\wd0 \kern-.025em\raise.0433em\box0 } ∞’. The results are somewhat fuzzy fuzzy, and they For example, ‘\pmb{\infty}’ yields ‘∞ certainly are no match for the real thing if it’s available; but poor man’s bold is better than nothing, and once in a while you can get away with it. When you put something into a box register, you don’t need to put the contents of that register into your document. Thus, you can write macros that do experiments behind the scenes, trying different possibilities before making a commitment to a particular decision. For example, suppose you are typesetting a text in two languages, and you would like to choose the column widths so that the same number of lines is obtained in both cases. For example, the following texts balance perfectly when the * The token list α should not be empty, however, because TEX expands the first token of an alignment entry before looking at the template, in order to see if the entry begins with \noalign or \omit. The master counter value that is considered to be present at the beginning of an entry is the value in the counter just after the “u part” of the template has been entirely read. Appendix D: Dirty Tricks first column is 157.1875 pt wide and the second column is 166.8125 pt wide; but the second column would be one line longer than the first if they were both 162 pt wide: A. The creative part is really more interesting than the deductive part. Instead of concentrating just on finding good answers to questions, it’s more important to learn how to find good questions! B. You’ve got something there. I wish our teachers would give us problems like, “Find something interesting about x,” instead of “Prove x.” A. Exactly. But teachers are so conservative, they’d be afraid of scaring off the “grind” type of students who obediently and mechanically do all the homework. Besides, they wouldn’t like the extra work of grading the answers to nondirected questions. The traditional way is to put off all creative aspects until the last part of graduate school. For seventeen or more years, a student is taught examsmanship, then suddenly after passing enough exams in graduate school he’s told to do something original. A. La parte creativa es mucho mejor que la deductiva. En vez de concentrarse en buscar buenas respuestas a ciertas cuestiones es m´ as importante aprender a proponerse buenas preguntas. B. Me parece una buena ocurrencia. Me gustar´ıa que los profesores propusieran problemas del estilo de hhEncuentren algo interesante sobre xii en vez de hhDemuestre que x . . . ii. A. Exactamente. Pero los profesores son tan conservadores que temer´ıan espantar al tipo de estudiante hhapisonadoraii que hace lo que le proponen para casa, obedientemente y de forma mec´ anica. Adem´ as, no creo que les gustase el trabajo adicional de calificar respuestas a preguntas abiertas. La forma tradicional es dejar la parte creativa para los cursos altos. Durante diecisiete a˜ nos o m´ as se ense˜ na al estudiante a aprobar, luego de golpe, cerca de la graduaci´ on, se le pide que haga algo original. Some implementations of TEX display the output as you are running, so that you can choose column widths interactively until a suitable balance is obtained. It’s fun to play with such systems, but it’s also possible to ask TEX to compute the column widths automatically. The following code tries up to ten times to find a solution in which the natural heights of the two columns are different by less than a given value, \delheight. The macros \firstcol and \secondcol are supposed to generate the columns, and the sum of column widths is supposed to be \doublewidth. \newdimen\doublewidth \newdimen\delheight \newif\iffail \newcount\n \newdimen\trialwidth \newdimen\lowwidth \newdimen\highwidth \def\balancetwocols{\lowwidth=10em % lower bound on \trialwidth \highwidth=\doublewidth \advance\highwidth-10em % upper bound {\n=1 \hbadness=10000 \hfuzz=\maxdimen % disable warnings \loop \maketrial \testfailure \iffail \preparenewtrial \repeat} \maketrial} % now under/overfull boxes will be shown \def\maketrial{\trialwidth=.5\lowwidth \advance\trialwidth by.5\highwidth \setbox0=\vbox{\hsize=\trialwidth \firstcol} \setbox2=\vbox{\hsize=\doublewidth\advance\hsize-\trialwidth\secondcol}} \def\testfailure{\dimen0=\ht0 \advance\dimen0-\ht2 \ifnum\dimen0\delheight \ifnum\n=10 \failfalse\else\failtrue\fi \else\failfalse\fi} \def\preparenewtrial{\ifdim\ht0>\ht2 \global\lowwidth=\trialwidth \else\global\highwidth=\trialwidth\fi \advance\n by1 } 387 388 Appendix D: Dirty Tricks Neither column will be less than 10 ems wide. This code does a “binary search,” assuming that a column will not increase in height when it is made wider. If no solution is found in 10 trials, there probably is no way to obtain the desired balance, because a tiny increase in the width of the taller column will make it shorter than the other one. The values of \hbadness and \hfuzz are made infinite during the trial settings, because warning messages that relate to unused boxes are irrelevant; after a solution is found, it is computed again, so that any relevant warnings will be issued. When a box has been put into a box register, you can change its height, width, or depth by assigning a new value to the \ht, \wd, or \dp. Such assignments don’t change anything inside the box; in particular, they don’t affect the setting of the glue. But changes to a box’s dimensions can be confusing if you don’t understand exactly how TEX deals with boxes in lists. The rules are stated in Chapter 12, but it may be helpful to restate them here in a different way. Given a box and the location of its reference point, TEX assigns locations to interior boxes as follows: (1) If the box is an hbox, TEX starts at the reference point and walks through the horizontal list inside. When the list contains a box, TEX puts the reference point of the enclosed box at the current position, and moves right by the width of that box. When the list contains glue or kerning, etc., TEX moves right by the appropriate amount. (2) If the box is a vbox, TEX starts at the upper left corner (i.e., TEX first moves up from the reference point, by the height of the box) and walks through the vertical list inside. When the list contains a box, TEX puts the upper left corner of that box at the current position; i.e., TEX moves down by the height of that box, then puts the box’s reference point at the current position, then moves down by the depth of the box. When the list contains glue or kerning, etc., TEX moves down by the appropriate amount. As a consequence of these rules, we can work out what happens when the dimensions of a box are changed. Let \delta be a hdimeni register, and let \h and \hh specify horizontal lists that don’t depend on \box0. Consider the following macro: \newdimen\temp \newdimen\delta \def\twohboxes#1{\setbox1=\hbox{\h \copy0 \hh} \temp=#10 \advance\temp by \delta #10=\temp \setbox2=\hbox{\h \copy0 \hh}} For example, \twohboxes\wd makes two hboxes, \box1 and \box2, that are identical except that the width of \box0 has been increased by δ in \box2. What difference does this make? There are several cases, depending on whether #1 is \wd, \ht, or \dp, and depending on whether \box0 is an hbox or a vbox. Case 1, \twohboxes\wd: The material from \hh is moved right by δ in \box2, compared to its position in \box1. Also \wd2 is δ more than \wd1. Case 2, \twohboxes\ht: If \box0 is an hbox, everything remains in the same position; but if \box0 is a vbox, everything in \copy0 moves up by δ. Also \ht2 may differ from \ht1. Case 3, \twohboxes\dp: Everything remains in the same position, but \dp2 may differ from \dp1. Similarly, we can work out the changes when box dimensions are changed for boxes within vertical lists. In this case we shall ignore the influence of interline glue by defining \twovboxes as follows: \def\twovboxes#1{ \setbox1=\vbox{\v\nointerlineskip\copy0\nointerlineskip\vv} \temp=#10 \advance\temp by \delta #10=\temp \setbox2=\vbox{\v\nointerlineskip\copy0\nointerlineskip\vv}} Appendix D: Dirty Tricks What is the difference between \box1 and \box2 now? Case 1, \twovboxes\wd: Everything remains in the same position, but \wd2 may differ from \wd1. Case 2, \twovboxes\ht: If \box0 is an hbox, everything in \v moves up by δ in \box2, compared to the corresponding positions in \box1, if we make the reference points of the two boxes identical; but if \box0 is a vbox, everything in it moves up by δ, together with the material in \v. Also, \ht2 is δ more than \ht1. Case 3, \twovboxes\dp: If \vv is empty, \dp2 is δ more than \dp1, and nothing else changes. Otherwise everything in \v and in \copy0 moves up by δ, and \ht2 is δ more than \ht1. TEX is designed to put boxes together either horizontally or vertically, not diagonally. But that’s not a serious limitation, because the use of negative spacing makes it possible to put things anywhere on a page. For example, the seven points in the diagram at the right of this • (0,8) paragraph were typeset by saying simply • (4,7) \hbox{\unit=\baselineskip \point 0 0 \point 0 8 \point 0 -8 \point -1 -2.5 \point 4 7 \point 4 2 \point 1 1.5 } • (1,1.5) • (4,2) • (0,0) The \point macro makes a box of width zero; hence the individual \point specifications can be given in any order, and there’s no restriction on the coordinates: \newdimen\unit \def\point#1 #2 {\rlap{\kern#1\unit \raise#2\unit\hbox{ \scriptstyle\bullet\;(#1,#2)}}} • (−1,−2.5) • (0,−8) If the \point specifications are not enclosed in an \hbox—i.e., if they occur in vertical mode—a similar construction can be used. In this case \point should create a box whose height and depth are zero: \def\point#1 #2 {\vbox to0pt{\kern-#2\unit \hbox{\kern#1\unit\scriptstyle\bullet\;(#1,#2)}\vss} \nointerlineskip} (The \nointerlineskip is necessary to prevent interline glue from messing things up.) If you enjoy fooling around making pictures, instead of typesetting ordinary text, TEX will be a source of endless frustration/amusement for you, because almost anything is possible if you have suitable fonts. For example, suppose you have a font \qc that contains four quarter circles: a = a b = b c = c d = d Each of these characters has the same height, the same width, and the same depth; the width and the height-plus-depth are equal to the diameter of the corresponding full circle. Furthermore, the reference point of each character is in a somewhat peculiar 389 390 Appendix D: Dirty Tricks place: Each quarter arc has a horizontal endpoint such that the lower edge of the curve is at the baseline, and a vertical endpoint such that the left edge is directly above or below the reference point. This convention makes it possible to guarantee perfect alignment between these characters and rules that meet them at the endpoints; the thickness of such rules should be \fontdimen8\qc. Given those characters, it’s possible to devise macros \path, \L, \R, \S, and \T such that \path{hany string of \L’s, \R’s, \S’s, and \T’si} produces a path that starts traveling East, but it turns left for each \L, right for each \R, goes straight for each \S, and turns backward for each \T. Thus, for example, \path{\L\T\S\T\R\L\T\S\T\R} d’, and you can also get the following effects: yields ‘ d bb \path{\L\R\S\R\S\R\S\S\R\R} d db c \path{\R\R\R\R\T\S\S\L\L\L\L\L\S\S} a b d ad a cbcb \def\X{\L\T\L\L\T\L\L\T} \path{\X\X\X\X} b c ac bc d b b c a d bd a d ac a d Furthermore, there are operations \B and \W that make the path black (visible) and white (invisible), respectively: d \path{\R\R\S \W\S\S\S\R\R \B\R\R\S\R\S\R\S\S\S\R\S\S\S\S\S\R\S\R \W\R\R\R\S\L\S \B\L\S\S\S\S} a c b c a a b b c (It may be necessary to put kerns before and after the path, since the box produced by \path may not be as wide as the actual path itself.) The \path macros work differently from \point, since the boxes need not have zero width in this application: \catcode‘\ =9 \endlinechar=-1 % ignore all spaces (temporarily) \newcount\dir \newdimen\y \newdimen\w \newif\ifvisible \let\B=\visibletrue \let\W=\visiblefalse \newbox\NE \newbox\NW \newbox\SE \newbox\SW \newbox\NS \newbox\EW \setbox\SW=\hbox{\qc a} \setbox\NW=\hbox{\qc b} \setbox\NE=\hbox{\qc c} \setbox\SE=\hbox{\qc d} \w=\wd\SW \dimen0=\fontdimen8\qc \setbox\EW=\hbox{\kern-\dp\SW \vrule height\dimen0 width\wd\SW} \wd\EW=\w \setbox\NS=\hbox{\vrule height\ht\SW depth\dp\SW width\dimen0} \wd\NS=\w \def\L{\ifcase\dir \dy+\NW \or\dx-\SW \or\dy-\SE \or\dx+\NE\dd-4\fi \dd+1} \def\S{\ifcase\dir \dx+\EW \or \dy+\NS \or \dx-\EW \or \dy-\NS \fi} \def\R{\ifcase\dir \dy-\SW\dd+4 \or\dx+\SE \or\dy+\NE \or\dx-\NW\fi \dd-1} \def\T{\ifcase\dir\kern-\w\dd+2\or\ey-\dd+2\or\kern\w\dd-2\or\ey+\dd-2\fi} Appendix D: Dirty Tricks \edef\dd#1#2{\global\advance\dir#1#2\space} \def\dx#1#2{\ifvisible\raise\y\copy#2 \if#1-\kern-2\w\fi\else\kern#1\w\fi} \def\dy#1#2{\ifvisible\raise\y\copy#2 \kern-\w \fi \global\advance\y#1\w} \def\ey#1{\global\advance\y#1\w} \def\path#1{\hbox{\B \dir=0 \y=0pt #1}} \catcode‘\ =10 \endlinechar=‘\^^M % resume normal spacing conventions \newcount\n % the current order in the \dragon and \nogard macros \def\dragon{\ifnum\n>0{\advance\n-1 \dragon\L\nogard}\fi} \def\nogard{\ifnum\n>0{\advance\n-1 \dragon\R\nogard}\fi} (The last three lines are not part of the \path macros, but they can be used as an interesting test case. To get the famous “dragon curve” of order 9, all you have to say is ‘\path{\dir=3 \n=9 \dragon}’.) Let’s turn now to another box-oriented problem. The \listing macro discussed earlier in this appendix was restricted to listing files that contain only visible ASCII characters. Sometimes it’s desirable to deal with ASCII htabi marks too, where a htabi is equivalent to 1 or 2 or · · · or 8 spaces (whatever is necessary to make the current line length a multiple of 8). How can this be done? We shall assume that files can contain a special symbol that TEX will input as character number 9, the ASCII htabi code; some implementations can’t actually do this. If a file contains the three symbols ^^I, plain TEX will normally input them as a single character, number 9; but in a verbatim listing of the file we naturally want such symbols to print as themselves, i.e., as ^^I. The following construction redefines \setupverbatim so that the previous \listing macro will work with htabi characters. The idea is to keep the line-so-far in an hbox, which can be “measured” in order to find out how many characters have appeared since the beginning of the line or since the most recent htabi. \def\setupverbatim{\tt \lineno=0 \def\par{\leavevmode\egroup\box0\endgraf} \obeylines \uncatcodespecials \obeyspaces \catcode‘\‘=\active \catcode‘\^^I=\active \everypar{\advance\lineno by1 \llap{\sevenrm\the\lineno\ \ }\startbox}} \newdimen\w \setbox0=\hbox{\tt\space} \w=8\wd0 % tab amount \def\startbox{\setbox0=\hbox\bgroup} {\catcode‘\^^I=\active \gdef^^I{\leavevmode\egroup \dimen0=\wd0 % the width so far, or since the previous tab \divide\dimen0 by\w \multiply\dimen0 by\w % compute previous multiple of \w \advance\dimen0 by\w % advance to next multiple of \w \wd0=\dimen0 \box0 \startbox}} (The new things in \setupverbatim are the ‘\egroup\box0’ in the redefinition of \par; the ‘\catcode‘\^^I=\active’; and the ‘\startbox’ in \everypar.) The \settabs and \+ macros of Appendix B provide another example of how tab operations can be simulated by boxing and unboxing. 391 392 Appendix D: Dirty Tricks Chapter 22 explains how to put vertical rules in tables by considering the rules to be separate columns. There’s also another way, provided that the rules extend all the way from the top of the table to the bottom. For example, \beginvrulealign \tabskip=10pt \halign{&\strut#\hfil\cr These& after\cr vertical& the\cr rules& alignment\cr were& was\cr inserted& completed!\cr} \endvrulealign yields These vertical rules were inserted after the alignment was completed! The magic macros in this case examine the bottom row of the alignment, which consists of alternating tabskip glue and boxes; each item of tabskip glue in that bottom row will be bisected by a vertical rule. Here’s how: \def\beginvrulealign{\setbox0=\vbox\bgroup} \def\endvrulealign{\egroup % now \box0 holds the entire alignment \setbox0=\vbox{\setbox2=\hbox{\vrule height\ht0 depth\dp0 width0pt} \unvbox0 \setbox0=\lastbox % now \box0 is the bottom row \nointerlineskip \copy0 % put it back \global\setbox1=\hbox{} % initialize box that will contain rules \setbox4=\hbox{\unhbox0 % now open up the bottom row \loop \skip0=\lastskip \unskip % remove tabskip glue \advance\skip0 by-.4pt % rules are .4pt wide \divide\skip0 by 2 \global\setbox1=\hbox{\hskip\skip0\vrule\hskip\skip0 \unhbox2\unhbox1}% \setbox2=\lastbox % remove alignment entry \ifhbox2 \setbox2=\hbox{\kern\wd2}\repeat}}% \hbox{\rlap{\box0}\box1}} % superimpose the alignment on the rules This method works with all alignments created by \halign{...}. For alignments created by, say, \halign to100pt{...}, the method works only if the bottom row of the alignment contains all of the columns, and only if ‘\box1’ is replaced by ‘\hbox to100pt{\unhbox1}’ at the end of \endvrulealign. 7. Paragraph maneuvers. Chapter 14 promised that Appendix D would present an example where ragged right and ragged left setting occur in the same paragraph. The following interesting example was suggested by the “Key Index” in Mathematical Reviews, where the entries consist of a possibly long title followed by dot leaders followed by a possibly long list of review numbers. If the title doesn’t fit on one line, it should be set ragged right, with hanging indentation on all lines after the first; if the references don’t all fit on one line, they should be set ragged left. For example, given the input ACM Symposium on Theory of Computing, Eighth Annual (Hershey, % Pa., 1976)\:1879, 4813, 5414, 6918, 6936, 6937, 6946, 6951, % 6970, 7619, 9605, 10148, 11676, 11687, 11692, 11710, 13869 Appendix D: Dirty Tricks the following three types of output are desired, depending on the column width: ACM Symposium on Theory of Computing, Eighth Annual (Hershey, Pa., 1976) . . . . . . . 1879, 4813, 5414, 6918, 6936, 6937, 6946, 6951, 6970, 7619, 9605, 10148, 11676, 11687, 11692, 11710, 13869 ACM Symposium on Theory of Computing, Eighth Annual (Hershey, Pa., 1976) . . . . . . . . . 1879, 4813, 5414, 6918, 6936, 6937, 6946, 6951, 6970, 7619, 9605, 10148, 11676, 11687, 11692, 11710, 13869 ACM Symposium on Theory of Computing, Eighth Annual (Hershey, Pa., 1976) . . . 1879, 4813, 5414, 6918, 6936, 6937, 6946, 6951, 6970, 7619, 9605, 10148, 11676, 11687, 11692, 11710, 13869 Notice that the dot leaders are treated in three different ways, depending on which works out best: They may occur at the left of the first line after the title, or they may appear at the end of the last line of the title (in which case they stop well before the right margin), or they may occur in the middle of a line. Furthermore, the ragged-right lines are supposed to end at least 0.5 em from the right margin. Our goal is to achieve all this as a special case of TEX’s general paragraphing method. The simple approach of Appendix B won’t work, because \raggedright is achieved there by adjusting \rightskip; TEX uses the same \rightskip value in all lines of a paragraph. The solution to this problem requires an understanding of the line-breaking algorithm; it depends on how demerits are calculated, and on how items are removed at the breakpoints, so the reader should review Chapter 14 until those concepts are firmly understood. Basically, we need to specify a sequence of box/glue/penalty items for the spaces in the title portion, another sequence for the spaces in the reference portion, and another sequence for the dot leaders. In the title portion of each index entry, interword spaces can be represented by the sequence \penalty10000 \hskip.5em plus3em \penalty0 \hskip-.17em plus-3em minus.11em Thus, there is a stretchability of 3 em if a line break occurs at the \penalty0; otherwise the net interword space will be .33 em, shrinkable to .22 em. This gives ragged right margins. The interword spaces in the reference portion are designed to produce ragged left margins and to minimize the number of lines devoted to references: \penalty1000 \hskip.33em plus-3em minus.11em \vadjust{}\penalty10000 \hskip0pt plus3em The \vadjust{} does nothing, but it doesn’t disappear at a line break. Thus, if a break occurs at the \penalty1000, the following line will begin with stretchability 3 em; but if no break occurs, the net space will be .33 em minus .11 em. Finally, the transition between title and references can be specified by \penalty10000 \hskip.5em plus3em \penalty600 \hskip-.17em plus-3em minus.11em \vadjust{}\penalty10000 \leaders\copy\dbox\hskip3.3\wd\dbox plus1fil minus.3\wd\dbox \kern3em \penalty600 \hskip-2.67em plus-3em minus.11em \vadjust{}\penalty10000 \hskip0pt plus3em 393 394 Appendix D: Dirty Tricks (Quite a mouthful.) This long sequence of penalty and glue items begins rather like the interword spaces in the first part, and it ends rather like the interword spaces in the last part. It has two permissible breakpoints, namely at the ‘\penalty600’ items. The first breakpoint causes the leaders to appear at the beginning of a line; the second causes them to appear at the end, but 3 ems away. The leader width will always be at least three times the width of \dbox, so at least two copies of \dbox will always appear. Here is the actual TEX code that can be used to set up the desired behavior: \hyphenpenalty10000 \exhyphenpenalty10000 \pretolerance10000 % no hyphens \newbox\dbox \setbox\dbox=\hbox to .4em{\hss.\hss} % dot box for leaders \newskip\rrskipb \rrskipb=.5em plus3em % ragged right space before break \newskip\rrskipa \rrskipa=-.17em plus-3em minus.11em % ditto, after \newskip\rlskipa \rlskipa=0pt plus3em % ragged left space after break \newskip\rlskipb \rlskipb=.33em plus-3em minus .11em % ditto, before \newskip\lskip \lskip=3.3\wd\dbox plus1fil minus.3\wd\dbox % for leaders \newskip\lskipa \lskipa=-2.67em plus-3em minus.11em % after leaders \mathchardef\rlpen=1000 \mathchardef\leadpen=600 % constants used \def\rrspace{\nobreak\hskip\rrskipb\penalty0\hskip\rrskipa} \def\rlspace{\penalty\rlpen\hskip\rlskipb\vadjust{}\nobreak\hskip\rlskipa} \uccode‘~=‘ \uppercase{ \def\:{\nobreak\hskip\rrskipb \penalty\leadpen \hskip\rrskipa \vadjust{}\nobreak\leaders\copy\dbox\hskip\lskip \kern3em \penalty\leadpen \hskip\lskipa \vadjust{}\nobreak\hskip\rlskipa \let~=\rlspace} \everypar{\hangindent=1.5em \hangafter=1 \let~=\rrspace}} \uccode‘~=0 \parindent=0pt \parfillskip=0pt \obeyspaces Putting the interword glue into \skip registers saves a great deal of time and memory space when TEX works with such paragraphs; ‘\hskiphexplicit gluei’ occupies six cells of TEX’s box memory, but ‘\hskiphskip registeri’ occupies only two. Notice the tricky use of \uppercase here to convert ~13 into Ã13 ; “random” active characters can be obtained in a similar way. Let’s turn now to a much simpler problem: hanging punctuation. “What is hanging punctuation?” asked Alice, margins, if they occur next to a line break.” with a puzzled frown. ‘Well, y’know, actually,’ ‘Yeah, I guess.’ “Really! But why do all your answered Bill, ‘I’d rather demonstrate it than remarks have single quotes, while mine are explain it.’ “Oh, now I see. Commas, periods, double?” ‘I haven’t the foggiest; it’s weird. and quotes are allowed to stick out into the Ask the author of this crazy book.’ Each comma in Alice and Bill’s demonstration paragraph was represented inside of TEX by the sequence of three items ‘,\kern-\commahang\kern\commahang’, and there were similar replacements for periods and for closing quotes; opening quotes were represented by the longer sequence \kern\qquotehang\vadjust{}\kern-\qquotehang‘‘\allowhyphens where \allowhyphens allows the following word to be hyphenated. This construction works because kerns disappear into line breaks in the proper way; the relevant rules from Chapter 14 are: (1) A line break can occur at a kern that is immediately followed by glue. (2) Consecutive glue, kern, and penalty items disappear at a break. Appendix D: Dirty Tricks To set TEX up for hanging punctuation, you can say \newdimen\commahang \setbox0=\hbox{,} \commahang=\wd0 \newdimen\periodhang \setbox0=\hbox{.} \periodhang=\wd0 \newdimen\quotehang \setbox0=\hbox{‘} \quotehang=\wd0 \newdimen\qquotehang \setbox0=\hbox{‘‘} \qquotehang=\wd0 \newskip\zzz \def\allowhyphens{\nobreak\hskip\zzz} \def\lqq{‘‘} \def\rqq{’’} \def\pnt{.} \def\comma{,\kern-\commahang\kern\commahang} \def\period{.\kern-\periodhang\kern\periodhang} \def\rquote{’\kern-\quotehang\kern\quotehang} \def\lquote{\ifhmode\kern\quotehang\vadjust{}\else\leavevmode\fi \kern-\quotehang‘\allowhyphens} \catcode‘,=\active \let,=\comma \catcode‘.=\active \let.=\period \catcode‘’=\active \def’{\futurelet\next\rqtest} \catcode‘‘=\active \def‘{\futurelet\next\lqtest} \def\rqtest{\ifx\next’\let\next=\rquotes\else\let\next=\rquote\fi\next} \def\lqtest{\ifx\next‘\let\next=\lquotes\else\let\next=\lquote\fi\next} \def\rquotes’{\rqq\kern-\qquotehang\kern\qquotehang} \def\lquotes‘{\ifhmode\kern\qquotehang\vadjust{}\else\leavevmode\fi \kern-\qquotehang\lqq\allowhyphens} Notice that the macros need to do their own checking for ligatures, and they also take appropriate actions when a paragraph begins with an opening quote. Since \kern does not affect the space factor, hanging punctuation doesn’t affect TEX’s spacing conventions within a line. Partially hanging punctuation can be obtained by decreasing the amounts of \commahang, etc. The macros \pnt, \lq, and \rq should be used in constants; for example, a dimension of 6.5 in must be written ‘6\pnt5in’ when hanging punctuation is in effect, and ‘\catcode\lq,=12’ makes commas inactive again. A special font with zero-width \hyphenchar should be used for “hanging hyphenation.” And now for our next trick, let’s consider an application to short footnotes. The footnotes at the bottom of this page1,2,3,4,5,6,7,8,9,10 look funny, because most of them are quite short. When a document has lots of footnotes, and when most of them take up only a small part of a line, the output routine ought to reformat them in some more appropriate way. 1 First footnote. 2 Second footnote. (Every once in a while a long footnote might occur, just to make things difficult.) 3 Third footnote. 4 Fourth footnote. 5 Fifth footnote. (This is incredibly boring, but it’s just an example.) 6 Another. 7 And another. 8 Ho hum. 9 Umpteenth footnote. 10 Oodles of them. 395 396 Appendix D: Dirty Tricks For example, one approach would be to typeset the footnotes in narrow columns and to put, say, three columns of footnotes at the bottom of each page. The ten example footnotes might then look like this: 1 2 First footnote. Second footnote. (Every once in a while a long footnote might occur, just to make things difficult.) 3 4 5 Third footnote. Fourth footnote. Fifth footnote. (This is incredibly boring, but it’s just an example.) 6 7 8 9 10 Another. And another. Ho hum. Umpteenth footnote. Oodles of them. In this case, the footnotes could be generated by \insert\footins{\eightpoint \hsize=9pc \parindent=1pc \leftskip=0pt \raggedright \pretolerance=10000 \hyphenpenalty=10000 \exhyphenpenalty=10000 \interlinepenalty=\interfootnotelinepenalty \floatingpenalty=20000 \splittopskip=\ht\strutbox \splitmaxdepth=\dp\strutbox \item{^{\the\footno}}\struthtext of footnotei\strut \par\allowbreak} and \count\footins would be set to 333 so that each footnote line would be considered to occupy about one third of a line on the page. The output routine would then see a \box\footins that looks like this: \vbox(142.0+2.0)x108.0 .\hbox(7.0+2.0)x108.0, glue set 42.23425fil [] .\penalty 0 .\hbox(7.0+2.0)x108.0, glue set 0.29266 [] .\penalty 250 .\glue(\baselineskip) 1.44444 .\hbox(5.55556+1.55556)x96.0, glue set 0.8693, shifted 12.0 [] .\penalty 100 .\glue(\baselineskip) 1.88889 .\hbox(5.55556+1.55556)x96.0, glue set 0.92438, shifted 12.0 [] .. . .\hbox(7.0+2.0)x108.0, glue set 18.56308fil [] .\penalty 0 .\hbox(7.0+2.0)x108.0, glue set 36.92476fil [] .\penalty 0 The individual footnotes each end with ‘\penalty 0’; footnotes that take up more than one line have larger penalties between the lines, and interline glue appears there too. How should the output routine break such a box up into three roughly equal pieces? Notice that the contents of the box are completely rigid, i.e, there is no glue that can stretch or shrink. Furthermore, we can assume that the contents of the box are regular, i.e., that the inter-baseline distances are all the same. In such circumstances a fairly simple balancing routine can be used to trisect the box. Let’s consider a more general problem: Suppose that a rigid vbox is given, n lines tall, where adjacent baselines are b units apart. Suppose also that the top Appendix D: Dirty Tricks baseline is h units from the top of the vbox, where 0 < h < b. (In our footnote example, b = 9 pt and h = 7 pt; in the standard settings of plain TEX, b = 12 pt and h = 10 pt. We might as well work the problem for general b and h.) It follows that the height of the vbox is H = h + b(n − 1) = bn + h − b. If n lines are to be distributed evenly into k columns, the first column should contain dn/ke lines. (This denotes the smallest integer greater than or equal to n/k.) For example, our application to footnotes has n = 16 and k = 3, hence the first column should contain 6 lines. After forming the first column, we have reduced the problem to n = 10 and k = 2, so two 5-line columns will complete the operation. (Notice that it is better to divide 16 into 6 + 5 + 5 instead of 6 + 6 + 4.) Once we have found the first column, it’s always possible to reduce the k-column problem to a (k − 1)-column problem, so we need only concentrate on finding the first column. Let m = dn/ke. The height of the given box is bn + h − b, and the height of the first column should be bm + h − b; hence we want to do a \vsplit to that height. However, it isn’t necessary to calculate bm + h − b exactly, since a bit of arithmetic proves that bm + h − b < bn + h − b + h < b(m + 1) + h − b. k Therefore it suffices to \vsplit to height H 0 = H/k + h; under the assumptions of rigidity, and assuming that a valid break is possible after each line, \vsplit to H 0 will split after the maximum number of lines that yield a box of height ≤ H 0 . (We have observed that m lines produce a box of height < H 0 while m + 1 lines produce a box of height > H 0 .) The following TEX code does this: \newcount\k \newdimen\h % registers used by the \rigidbalance routine \def\rigidbalance#1#2 #3 {\setbox0=\box#1 \k=#2 \h=#3 \line{\splittopskip=\h \vbadness=10000 \hfilneg \valign{##\vfil\cr\dosplits}}} \def\dosplits{\ifnum\k>0 \noalign{\hfil}\splitoff \global\advance\k-1\cr\dosplits\fi} \def\splitoff{\dimen0=\ht0 \divide\dimen0 by\k \advance\dimen0 by\h \vsplit0 to \dimen0 } This code is interesting on a number of counts. First, notice that the calculation does not depend on b, only on h and the height of the given box; hence \rigidbalance has three parameters: a box register number, the number of columns k, and the top baseline height h. The routine splits the given vbox into k nearly equal pieces and justifies the result in a \line. The value of \splittopskip is set to h so that subsequent vboxes will satisfy the ground rules of the original vbox, as the problem is reduced from k to k − 1. Each column will be preceded by \hfil, hence \hfilneg is used to cancel the \hfil before the first column. A \valign is used to align all of the columns at the top. Notice that the preamble to this \valign is quite simple; and the body of the \valign is generated by a recursive macro \dosplits that produces the k columns. The value of \vbadness is set to 10000 because each \vsplit operation will produce an underfull vbox whose badness is 10000. 397 398 Appendix D: Dirty Tricks In our application to footnotes, the \output routine can reformat the contents of \box\footins by saying, for example, \rigidbalance\footins 3 7pt \setbox\footins=\lastbox since \lastbox will be the result of \rigidbalance. This solution to the problem of short footnotes might result in club lines or widow lines, since the balancing routine we have described simply trisects the total number of lines. For example, if the tenth footnote of our example had not been present, the fifteen remaining lines would have been split 5 + 5 + 5; the second column would have been headed by the lonely word ‘difficult.)’, and the third column would have started with ‘just an example.)’. The rigid balancing procedure could be replaced by one that allows ragged-bottom columns, but there’s also another approach: The entire set of footnotes could be combined into a single paragraph, with generous spacing between the individual items. For example, the ten footnotes we have been considering might appear as follows: 1 First 2 Second footnote. (Every once in a while a long footnote might occur, just footnote. 3 Third footnote. 4 Fourth footnote. 5 Fifth footnote. (This to make things difficult.) 6 Another. 7 And another. 8 Ho hum. is incredibly boring, but it’s just an example.) 9 Umpteenth footnote. 10 Oodles of them. It would be possible to take the contents of \box\footins shown previously and to reformat everything into a paragraph, but such an operation would be needlessly complicated. If footnotes are to be paragraphed by the output routine, it’s better simply to prepare them in unjustified hboxes. Each of these hboxes will be unboxed later, so we are free to play with their heights, widths, and depths. It’s convenient to set the depth to zero and the height to an estimate of how much a particular footnote will contribute to the final paragraph. For example, if a footnote takes up exactly half of the \hsize, and if the final footnote is going to be set with \baselineskip=10pt, then the height of the footnote hbox should be set to 5 pt. By letting \count\footins=1000, we’ll have a pretty good estimate of the size of the final footnote paragraph. In other words, the following insertion scheme is suggested: \insert\footins{\floatingpenalty=20000 \eightpoint \setbox0=\hbox{% ^{\the\footno}htext of footnotei\penalty-10\hskip\footglue} \dp0=0pt \ht0=\fudgefactor\wd0 \box0} The penalty of −10 tends to favor line breaks between footnotes; \footglue is the amount of glue between footnotes in the final footnote paragraph; and \fudgefactor is the ratio of \baselineskip to \hsize in that paragraph. The author defined the necessary quantities as follows in his experiments: \eightpoint \newskip\footglue \footglue=1.5em plus.3em minus.3em \newdimen\footnotebaselineskip \footnotebaselineskip=10pt \dimen0=\footnotebaselineskip \multiply\dimen0 by 1024 \divide \dimen0 by \hsize \multiply\dimen0 by 64 \xdef\fudgefactor{\expandafter\getfactor\the\dimen0 } (The computation of \fudgefactor uses the fact that 1 pt = 1024 × 64 sp, and it assumes that the \footnotebaselineskip is less than 16 pt.) Appendix D: Dirty Tricks Inside the output routine, \box\footins will now be a vbox of hboxes, and the height of this vbox will be an estimate of the height of the final paragraph. For example, our ten footnotes produce \vbox(34.48158+0.0)x386.4221 .\hbox(2.00175+0.0)x70.68285 [] .\hbox(10.94359+0.0)x386.4221 [] .\hbox(2.09749+0.0)x74.06345 [] .\hbox(2.2077+0.0)x77.95517 [] .\hbox(7.6296+0.0)x269.40376 [] .\hbox(1.40851+0.0)x49.73532 [] .\hbox(1.87659+0.0)x66.26334 [] .\hbox(1.38826+0.0)x49.02003 [] .\hbox(2.67213+0.0)x94.35402 [] .\hbox(2.25597+0.0)x79.65926 [] and the height of 34.48158 pt corresponds to an estimate of about three and a half lines. (TEX’s page builder has also added \skip\footins when estimating the total contribution due to footnotes.) The reformatting of \box\footins takes place in three stages. First the vbox of hboxes is changed to an hbox of hboxes, so that we obtain, e.g., \hbox(10.94359+0.0)x1217.5593 .\hbox(2.00175+0.0)x70.68285 [] .. . .\hbox(2.25597+0.0)x79.65926 [] (the same contents as before, but strung in a horizontal row instead of a vertical column). Then the inner hboxes are unboxed, and we obtain \hbox(6.68999+2.0)x1217.5593 .\mathon .\hbox(3.86665+0.0)x4.16661, shifted -2.82333 [] .\mathoff .\eightrm F .etc. Finally the outer hbox is unboxed, and the horizontal list inside it is converted into a paragraph. Here is the actual TEX code: \def\makefootnoteparagraph{\unvbox\footins \makehboxofhboxes \setbox0=\hbox{\unhbox0 \removehboxes} \baselineskip=\footnotebaselineskip\noindent\unhbox0\par} \def\makehboxofhboxes{\setbox0=\hbox{} \loop\setbox2=\lastbox \ifhbox2 \setbox0=\hbox{\box2\unhbox0}\repeat} \def\removehboxes{\setbox0=\lastbox \ifhbox0{\removehboxes}\unhbox0 \fi} The \removehboxes operation is especially noteworthy, because it uses TEX’s save stack to hold all of the hboxes before unboxing them. Each level of recursion in this routine uses one cell of input stack space and three cells of save stack space; thus, 399 400 Appendix D: Dirty Tricks it is generally safe to do more than 100 footnotes without exceeding TEX’s capacity. The \makehboxofhboxes routine is not as efficient; TEX doesn’t allow a vbox to be unboxed in horizontal mode, or vice versa, hence the trick of \removehboxes cannot be used. This means that the running time is proportional to n2 , if there are n footnotes, because the time to make or unmake a box is proportional to the number of items in the top-level list inside. However, the constant of proportionality is small, so there is no need to resort to a more complicated scheme that would be asymptotically faster. Indeed, the \lastbox operation itself has a running time approximately equal to a+mb, where m is the number of items on the list preceding the box that is removed; hence \removehboxes has a running time of order n2 as well. But the constant b is so small that for practical purposes it’s possible to think of \lastbox as almost instantaneous. Note, however, that it would be a mistake to bypass the \removehboxes operation by saying ‘\setbox0=\hbox{\unhbox2\unhbox0}’ in \makehboxofhboxes; that would make the top-level list inside \box0 too long for efficient unboxing. 8. Communication with output routines. It would be possible to write an entire book about TEX output routines; but the present appendix is already too long, so it will suffice to mention only one or two sneaky tricks that a person might not readily think of. (Appendix E gives some less sneaky examples.) Sometimes an output routine needs to know why it was invoked, so there’s a problem of communicating information from the rest of the program. TEX provides general \mark operations, but marks don’t always yield the right sorts of clues. Then there’s \outputpenalty, which can be tested to see what penalty occurred at a breakpoint; any penalty of −10000, −10001, −10002, or less, forces the output routine to act, hence different penalty values can be used to pass different messages. (When the output routine puts material back on the list of contributions, it need not restore the penalty at the breakpoint.) If output has been forced by a highly negative value of \outputpenalty, the output routine can use \vbox{\unvcopy255} to discover how full the page-so-far actually is. Underfull and overfull boxes are not reported when \box255 is packaged for use by the output routine, so there’s no harm in ejecting a page prematurely if you want to pass a signal. (Set \holdinginserts positive to pass a signal when the contents of \box255 will be sent back through the page builder again, if any insertions are present.) Perhaps the dirtiest trick of all is to communicate with the output routine via the depth of \box255. For example, suppose that you want to know whether or not the current page ends with the last line of a paragraph. If each paragraph ends with ‘\specialstrut’, where \specialstrut is like \strut but 1 sp deeper, then \dp255 will have a recognizable value if a page ends simultaneously with a paragraph. (Of course, \maxdepth must be suitably large; plain TEX takes \maxdepth=4pt, while struts are normally 3.5 pt deep, so there’s no problem.) A distance of 1000 sp is invisible to the naked eye, so a variety of messages can be passed in this way. If the value of \vsize is very small, TEX will construct paragraphs as usual but it will send them to the output routine one line at a time. In this way the output routine could attach marginal notes, etc., based on what occurs in the line. Paragraphs that have been rebuilt in this way can also be sent back from the output routine to the page builder; normal page breaks will then be found, if \vsize has been restored. An output routine can also write notes on a file, based on what occurs in a manuscript. A two-pass system can be devised where TEX simply gathers information Appendix D: Dirty Tricks during the first pass; the actual typesetting can be done during the second pass, using \read to recover information that was written during the first. 9. Syntax checking. Suppose you want to run a manuscript through TEX just to check for errors, without getting any output. Is there a way to make TEX run significantly faster while doing this? Yes; here’s how: (1) Say ‘\font\dummy=dummy’ ; your system should include a file dummy.tfm that defines a font with no characters (but with enough \fontdimen parameters to qualify as a math symbol font). (2) Set all the font identifiers you are using equal to \dummy. For example, \let\tenrm=\dummy, \let\tenbf=\dummy, . . . , \textfont0=\dummy, etc. (3) Say ‘\dummy’ to select the dummy font (since plain TEX may have selected the real \tenrm). (4) Set \tracinglostchars=0, so that TEX won’t complain when characters aren’t present in the dummy font. (5) Set \output={\setbox0=\box255\deadcycles=0} so that nothing will be shipped out, yet TEX will not think that your output routine is flaky. (6) Say \newtoks\output, so that no other output routine will be defined. (7) Say \frenchspacing so that TEX will not have to do space factor calculations. (8) Say \hbadness=10000 so that underfull boxes will not be reported. (9) And if you want to disable \write commands, use the following trick due to Frank Yellin: \let\immediate=\relax \def\write#1#{{\afterassignment}\toks0=} These changes usually make TEX run more than four times as fast. Wolfe, who had moved around the desk and into his chair, put up a palm at him: “Please, Mr. Hombert. I think it is always advisable to take a short-cut when it is feasible.” — REX STOUT, The Rubber Band (1936) “My dear Watson, try a little analysis yourself,” said he, with a touch of impatience. “You know my methods. Apply them, and it will be instructive to compare results.” — CONAN DOYLE, The Sign of the Four (1890) 401 (page 402) E Example Formats Appendix E: Example Formats Although the plain TEX format of Appendix B is oriented to technical reports, it can readily be adapted to quite different applications. Examples of three such adaptations are provided in this appendix: (1) a format for business letters; (2) a format for concert programs; (3) the format used to typeset this book. Let’s consider business letters first. Suppose that you want TEX to format your correspondence, and that you have n letters to send. If your computer system contains a file letterformat.tex like the one described later in this appendix, it’s easy to do the job by applying TEX to a file that looks like this: hoptional magnificationi \input letterformat hbusiness letter1 i .. . hbusiness lettern i \end Here each of the n business letters has the form hletterheadi \address hone or more lines of addressi \body hone or more paragraphs of texti \closing hone or more lines for salutation and signaturei hoptional annotationsi hoptional postscriptsi \endletter \makelabel % omit this if you don’t want an address label The hletterheadi at the beginning of this construction is usually a control sequence like \rjdletterhead for letters by R. J. D.; each letter writer can have a personalized letterhead that is stored with the letterformat macros. The hoptional annotationsi at the end are any number of one-line notes preceded by ‘\annotations’; the hoptional postscriptsi are any number of paragraphs preceded by ‘\ps’. When TEX is processing the \address and the \closing and the optional \annotations, it produces output line-for-line just as the lines appear in the input file; but when TEX is processing the \body of the letter and the optional \ps, it chooses line breaks and justifies lines as it normally does when typesetting paragraphs in books. A complete example, together with the resulting output, appears on the next two pages. This example starts with ‘\magnification=\magstep1’ because the letter is rather short. Magnification is usually omitted if the letters are long-winded; ‘\magnification=\magstephalf’ is appropriate when they are medium-size. The same magnification applies to all n letters, so you must run TEX more than once if you want more than one magnification. 403 404 Appendix E: Example Formats \magnification=\magstep1 \input letterformat \rjdletterhead % (see the output on the next page) \address Prof.~Brian~K. Reid Department of Electrical Engineering Stanford University Stanford, CA 94305 \body Dear Prof.~Reid: I understand that you are having difficulties with Alka-Seltzer tablets. Since there are 25~pills per bottle, while the manufacturer’s directions recommend ‘‘plop,~plop, fizz,~fizz,’’ my colleagues tell me that you have accumulated a substantial number of bottles in which there is one tablet left. % (See the 1978 SCRIBE User Manual, page 90.) At present I am engaged in research on the potential applications of isolated analgesics. If you would be so kind as to donate your Alka-Seltzer collection to our project, I would be more than happy to send you preprints of any progress reports that we may publish concerning this critical problem. \closing Sincerely, R. J. Drofnats Professor \annotations RJD/dek cc: {\sl The \TeX book} \ps P. S. \ If you like, I will check into the possibility that your donation and the meals that you have been eating might be tax-deductible, in connection with our research. \endletter \makelabel Appendix E: Example Formats 405 406 Appendix E: Example Formats If the letter is more than one page long, the addressee, date, and page number will appear at the top of subsequent pages. For example, the previous letter comes out as follows, if additional paragraphs are added to the text: The macro package letterformat.tex that produces this format begins with a simple macro that expands to the current date. \def\today{\ifcase\month\or January\or February\or March\or April\or May\or June\or July\or August\or September\or October\or November\or December\fi \space\number\day, \number\year} Then comes the specification of page layout, which is “ragged” at the bottom. A rather large \interlinepenalty is used so that page breaks will tend to occur between paragraphs. \raggedbottom \interlinepenalty=1000 \hsize=6.25truein \voffset=24pt \advance\vsize by-\voffset \parindent=0pt \parskip=0pt \nopagenumbers \headline={\ifnum\pageno>1 \tenrm To \addressee\hfil\today\hfil Page \folio \else\hfil\fi} Appendix E: Example Formats The contents of a letter are typeset either in “line mode” (obeying lines) or in “paragraph mode” (producing paragraphs in block style). Control sequences \beginlinemode and \beginparmode are defined to initiate these modes; and another control sequence, \endmode, is defined and redefined so that the current mode will terminate properly: \def\beginlinemode{\endmode \begingroup\obeylines\def\endmode{\par\endgroup}} \def\beginparmode{\endmode \begingroup\parskip=\medskipamount \def\endmode{\par\endgroup}} \let\endmode=\par \def\endletter{\endmode\vfill\supereject} One of the chief characteristics of this particular business letter format is a parameter called \longindentation, which is used to indent the closing material, the date, and certain aspects of the letterhead. The \address macro creates a box that will be used both in the letter and in the label on the envelope. If individual lines of the address exceed \longindentation, they are broken, and hanging indentation is used for any material that must be carried over. \newdimen\longindentation \longindentation=4truein \newbox\theaddress \def\address{\beginlinemode\getaddress} {\obeylines\gdef\getaddress #1 #2 {#1\gdef\addressee{#2}% \global\setbox\theaddress=\vbox\bgroup\raggedright% \hsize=\longindentation \everypar{\hangindent2em}#2 \def\endmode{\egroup\endgroup \copy\theaddress \bigskip}}} (Parameter #2 to \getaddress will be the contents of the line following \address, i.e., the name of the addressee.) The closing macros are careful not to allow a page break anywhere between the end of the \body and the beginning of a \ps. \def\body{\beginparmode} \def\closing{\beginlinemode\getclosing} {\obeylines\gdef\getclosing #1 #2 {#1\nobreak\bigskip \leftskip=\longindentation #2 \nobreak\bigskip\bigskip\bigskip % space for signature \def {\endgraf\nobreak}}} \def\annotations{\beginlinemode\def\par{\endgraf\nobreak}\obeylines\par} \def\ps{\beginparmode\nobreak \interlinepenalty5000\def\par{\endgraf\penalty5000}} The remaining portion of letterformat.tex deals with letterheads and labels, which of course will be different for different organizations. The following macros were used to generate the examples in this appendix; they can be modified in more-or-less obvious ways to produce suitable letterheads of other kinds. Special fonts are generally 407 408 Appendix E: Example Formats needed, and they should be loaded at ‘true’ sizes so that they are not affected by magnification. One tiny refinement worth noting here is the \up macro, which raises brackets so that they look better in a telephone number. \def\up#1{\leavevmode \raise.16ex\hbox{#1}} \font\smallheadfont=cmr8 at 8truept \font\largeheadfont=cmdunh10 at 14.4truept \font\logofont=manfnt at 14.4truept \def\rjdletterhead{ \def\sendingaddress{R. J. DROFNATS, F.T.U.G.\par PROFESSOR OF FARM ECOLOGY\par TEX.RJD @ SU-SCORE.ARPA\par \up[415\up]\thinspace 497-4975\par} \def\returnaddress{R. J. Drofnats, Dept.~of Farm Ecology\par The University of St.~Anford\par P. O. Box 1009, Haga Alto, CA 94321 USA} \letterhead} \def\letterhead{\pageno=1 \def\addressee{} \univletterhead {\leftskip=\longindentation {\baselineskip9truept\smallheadfont\sendingaddress} \bigskip\bigskip\rm\today\bigskip}} \def\univletterhead{\vglue-\voffset \hbox{\hbox to\longindentation{\raise4truemm\hbox{\logofont \kern2truept X\kern-1.667truept \lower2truept\hbox{X}\kern-1.667truept X}\hfil \largeheadfont The University of St.~Anford\hfil}% \kern-\longindentation \vbox{\smallheadfont\baselineskip9truept \leftskip=\longindentation BOX 1009\par HAGA ALTO, CA 94321}} \vskip2truept\hrule\vskip4truept } \def\makelabel{\endletter\hbox{\vrule \vbox{\hrule \kern6truept \hbox{\kern6truept\vbox to 2truein{\hsize=\longindentation \smallheadfont\baselineskip9truept\returnaddress \vfill\moveright 2truein\copy\theaddress\vfill}% \kern6truept}\kern6truept\hrule}\vrule} \pageno=0\vfill\eject} Our second example is a format for concert programs, to be used in connection with orchestra performances, recitals, and the like. We shall assume that the entire program fits on a single page, and that the copy is to be 4 inches wide. Comparatively large type (12 pt) will normally be used, but there is a provision for 10 pt and even 8 pt type in case the program includes pieces with a lot of subparts (e.g., Bach’s Mass in B minor, or Beethoven’s Diabelli Variations). To select the type size, a user says \bigtype, \medtype, or \smalltype, respectively. These macros for size switching are comparatively simple because concert programs don’t require any mathematics; hence Appendix E: Example Formats the math fonts don’t need to be changed. On the other hand, the format does take sharp and flat signs from the “math italic” font, which it calls ‘\mus’: \font\twelverm=cmr12 \font\twelvebf=cmbx12 \font\twelveit=cmti12 \font\twelvesl=cmsl12 \font\twelvemus=cmmi12 \font\eightrm=cmr8 \font\eightbf=cmbx8 \font\eightit=cmti8 \font\eightsl=cmsl8 \font\eightmus=cmmi8 \def\bigtype{\let\rm=\twelverm \let\bf=\twelvebf \let\it=\twelveit \let\sl=\twelvesl \let\mus=\twelvemus \baselineskip=14pt minus 1pt \rm} \def\medtype{\let\rm=\tenrm \let\bf=\tenbf \let\it=\tenit \let\sl=\tensl \let\mus=\teni \baselineskip=12pt minus 1pt \rm} \def\smalltype{\let\rm=\eightrm \let\bf=\eightbf \let\it=\eightit \let\sl=\eightsl \let\mus=\eightmus \baselineskip=9.5pt minus .75pt \rm} \hsize=4in \nopagenumbers \bigtype Notice the shrinkability in the \baselineskip settings. This would be undesirable in a book format, because different spacing between lines on different pages would look bad; but in a one-page document it helps squeeze the copy to fit the page, in an emergency. (There’s no need for stretchability in the baselineskip here, because a \vfill will be used at the bottom of the page.) Musical programs have a specialized vocabulary, and it is desirable to define a few control sequences for things that plain TEX doesn’t make as convenient as they could be for this particular application: \def\(#1){{\rm(}#1\/{\rm)}} \def\sharp{\raise.4ex\hbox{\mus\char"5D}} \def\flat{\raise.2ex\hbox{\mus\char"5B}} \let\,=\thinspace The \( macro produces roman parentheses in the midst of italicized text; the \sharp and \flat macros produce musical signs in the current type size. The \, macro makes it easy to specify the thin space that is used in constructions like ‘K. 550’ and ‘Op. 59’. (Plain TEX has already defined \, and \sharp and \flat in a different way; but those definitions apply only to math formulas, so they aren’t relevant in this application.) Before discussing the rest of the music macros, let’s take a look at a complete example. The next two pages show the input and output for a typical concert program. 409 410 Appendix E: Example Formats \input concert \tsaologo \medskip \centerline{Friday, November 19, 1982, 8:00 p.m.} \bigskip \centerline{\bf PROGRAM} \medskip \composition{Variations on a Theme by Tchaikovsky} \composer{Anton S. Arensky (1861--1906)} \smallskip {\medtype \movements{Tema: Moderato\cr Var.~I: Un poco pi\‘u mosso&Var.~V: Andante\cr Var.~II: Allegro non troppo&Var.~VI: Allegro con spirito\cr Var.~III: Andantino tranquillo&Var.~VII: Andante con moto\cr Var.~IV: Vivace&Coda: Moderato\cr} } \bigskip \composition{Concerto for Horn and Hardart, S.\,27} \composer{P. D. Q. Bach (1807--1742)?} \smallskip \movements{Allegro con brillo\cr Tema con variazione \(su una tema differente)\cr Menuetto con panna e zucchero\cr} \medskip \soloists{Ben Lee User, horn\cr Peter Schickele, hardart\cr} \bigskip \centerline{INTERMISSION} \bigskip \composition{Symphony No.\,3 in E\flat\ Major\cr Op.\,55, ‘‘The Eroica’’\cr} \composer{Ludwig van Beethoven (1770--1827)} \smallskip \movements{Allegro con brio\cr Marcia funebre: Adagio assai\cr Scherzo: Allegro vivace\cr Finale: Allegro molto\cr} \bigskip \smalltype \noindent Members of the audience are kindly requested to turn off the alarms on their digital watches, and to cough only between movements. \bye Appendix E: Example Formats THE ST. ANFORD ORCHESTRA R. J. Drofnats, Conductor Friday, November 19, 1982, 8:00 p.m. PROGRAM Variations on a Theme by Tchaikovsky Anton S. Arensky (1861–1906) Tema: Moderato Var. I: Un poco pi u mosso Var. II: Allegro non troppo Var. III: Andantino tranquillo Var. IV: Vivace Var. V: Andante Var. VI: Allegro con spirito Var. VII: Andante con moto Coda: Moderato Concerto for Horn and Hardart, S. 27 P. D. Q. Bach (1807–1742)? Allegro con brillo Tema con variazione (su una tema differente) Menuetto con panna e zucchero Ben Lee User, horn Peter Schickele, hardart INTERMISSION Symphony No. 3 in E[ Major Op. 55, “The Eroica” Ludwig van Beethoven (1770–1827) Allegro con brio Marcia funebre: Adagio assai Scherzo: Allegro vivace Finale: Allegro molto Members of the audience are kindly requested to turn off the alarms on their digital watches, and to cough only between movements. 411 412 Appendix E: Example Formats Most of the macros in concert.tex have already been defined. Plain TEX takes care of things like \centerline and \bigskip, so only \composition, \composer, \movements, and \soloists remain to be specified: \def\composition#1{\halign{\bf\quad##\hfil\cr \kern-1em#1\crcr}} % use \cr’s if more than one line \def\composer#1{\rightline{\bf#1}} \def\movements#1{\halign{\quad\it##\hfil&&\qquad\it##\hfil\cr#1\crcr}} \def\soloists#1{\centerline{\bf\vbox{\halign{##\hfil\cr#1\crcr}}}} The \composition macro is set up to put the title of the composition on two or more lines, if needed, but a single line usually suffices. Notice that \crcr has been used so that the final \cr in the argument to \composition is not needed. Similarly, \movements might be used to produce only a single line, and \soloists might be used when there is only one soloist. There’s also a \tsaologo macro. It applies only to one particular orchestra, but the definition is somewhat interesting nonetheless: \def\tsaologo{\vbox{\bigtype\bf \line{\hrulefill} \kern-.5\baselineskip \line{\hrulefill\phantom{ THE ST.\,ANFORD ORCHESTRA }\hrulefill} \kern-.5\baselineskip \line{\hrulefill\hbox{ THE ST.\,ANFORD ORCHESTRA }\hrulefill} \kern-.5\baselineskip \line{\hrulefill\phantom{ R. J. Drofnats, Conductor }\hrulefill} \kern-.5\baselineskip \line{\hrulefill\hbox{ R. J. Drofnats, Conductor }\hrulefill} }} The author has extended these macros to a more elaborate format that includes special features for listing the members of the orchestra and for program notes, etc.; in this way it becomes fairly easy to typeset little booklets for concert patrons. Such extensions need not be discussed further in this appendix, because they don’t illustrate any essentially new ideas. Notice that the \composition and \movements and \soloists macros do not include any special provision for vertical spacing; the user is supposed to insert \smallskip, \medskip, and \bigskip as desired. This was done deliberately, because different concert programs seem to demand different spacing; no automatic scheme actually works very well in practice, since musical literature is so varied. Let’s turn now to the design of a format for an entire book, using this book itself as an example. How did the author prepare the computer file that generated The TEXbook? We have already seen several hundred pages of output produced from that file; our goal in the remainder of this appendix will be to examine the input that was used behind the scenes. In the first place, the author prepared sample pages and showed them to the publisher’s book designer. (The importance of this step cannot be overemphasized. There is a danger that authors—who are now able to typeset their own books with TEX—will attempt to do their own designs, without professional help. Book design is Appendix E: Example Formats an art that requires considerable creativity, skill, experience, and taste; it is one of the most important services that a publisher traditionally provides to an author.) Sample pages that are used as the basis of a design should show each of the elements in the book. In this case the elements included chapter titles, illustrations, subchapter headings, footnotes, displayed formulas, typewriter type, dangerous bends, exercises, answers, quotations, tables, numbered lists, bulleted lists, etc.; the author also expressed a desire for generous margins, so that readers could make marginal notes. The designer, Herb Caswell, faced a difficult problem of bringing all those disparate elements into a consistent framework. He decided to achieve this by using a uniform indentation of 3 picas for normal paragraph openings as well as for dangerous bends; and to establish this element of the design by using it also for all the displayed material, instead of centering the displays. He decided to put the page numbers in bold type, out in the margins (where there was plenty of room, thanks to the author’s request for white space); and he decided to use italic type with caps and lower case for the running headlines, so that the pages would have a somewhat informal flavor. He chose 10-point type (on a 12-point base) for the main text, and 9-point type (on an 11-point base) for the dangerous bends; the typeface was predetermined. He chose an \hsize of 29 picas and a \vsize of 44 picas. He decided to give subheadings like ‘ x EXERCISE 13.8’ in boldface caps before the statement of each exercise. He specified the amount of vertical space before and after such things as exercises, dangerous-bend paragraphs, and displayed equations. He decided to devote an entire left-hand page to each chapter illustration. And so on; each decision influenced the others, so that the final book would appear to be as coherent and attractive as possible under the circumstances. After the main portion of the book was designed, he worked out a format for the front matter (i.e., the pages that precede page 1); he arranged to have the same amount of “sinkage” (white space) at the top of each page there, so that the opening pages of the book would look unified and “open.” The author hasn’t actually followed the designer’s specifications in every detail. For example, nothing about stretching or shrinking of vertical spaces appeared in the design specs; the author introduced the notion of flexible glue on his own initiative, based on his observations of cut-and-paste operations often used in page makeup. If this book has any beauties, they should be ascribed to Herb Caswell; if it has any blemishes, they should be ascribed to Don Knuth, who wrote the formatting macros that we are now about to discuss. The computer file manual.tex that generated The TEXbook begins with a copyright notice, and then it says ‘\input manmac’. The auxiliary file manmac.tex contains the formatting macros, and it begins by loading 9-point, 8-point, and 6-point fonts: \font\ninerm=cmr9 \font\ninei=cmmi9 \font\ninesy=cmsy9 \font\ninebf=cmbx9 \font\ninett=cmtt9 \font\nineit=cmti9 \font\ninesl=cmsl9 \font\eightrm=cmr8 \font\eighti=cmmi8 \font\eightsy=cmsy8 \font\eightbf=cmbx8 \font\eighttt=cmtt8 \font\eightit=cmti8 \font\eightsl=cmsl8 \font\sixrm=cmr6 \font\sixi=cmmi6 \font\sixsy=cmsy6 \font\sixbf=cmbx6 (These fonts had been \preloaded in Appendix B; now they’re officially loaded.) 413 414 Appendix E: Example Formats The fonts intended for math formulas need to have a nonstandard \skewchar. The typewriter fonts are given \hyphenchar=-1 so that hyphenation is inhibited when control sequence names and keywords appear in the text of a paragraph. \skewchar\ninei=’177 \skewchar\eighti=’177 \skewchar\sixi=’177 \skewchar\ninesy=’60 \skewchar\eightsy=’60 \skewchar\sixsy=’60 \hyphenchar\ninett=-1 \hyphenchar\eighttt=-1 \hyphenchar\tentt=-1 A few more fonts are needed for special purposes: \font\tentex=cmtex10 \font\inchhigh=cminch \font\titlefont=cmssdc10 at 40pt \font\eightss=cmssq8 \font\eightssi=cmssqi8 \font\tenu=cmu10 \font\manual=manfnt \font\magnifiedfiverm=cmr5 at 10pt % % % % % % % % TeX character set as in Appendix C inch-high caps for chapter openings titles in chapter openings quotations in chapter closings ditto, slanted unslanted text italic METAFONT logo and special symbols to demonstrate magnification Now we come to the size-switching macros, which are much more elaborate than they were in the previous example because mathematics needs to be supported in three different sizes. The format also provides for a pseudo “small caps” (\sc); a true caps-and-small-caps font was not really necessary in the few cases that \sc was used. A dimension variable \ttglue is set equal to the desired spacing for the typewriter-like text that occasionally appears in paragraphs; the \tt fonts have fixed spacing, which doesn’t mix well with variable spacing, hence the macros below use \ttglue between words in appropriate places. \catcode‘@=11 % we will access private macros of plain TeX (carefully) \newskip\ttglue \def\tenpoint{\def\rm{\fam0\tenrm}% switch to 10-point type \textfont0=\tenrm \scriptfont0=\sevenrm \scriptscriptfont0=\fiverm \textfont1=\teni \scriptfont1=\seveni \scriptscriptfont1=\fivei \textfont2=\tensy \scriptfont2=\sevensy \scriptscriptfont2=\fivesy \textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex \textfont\itfam=\tenit \def\it{\fam\itfam\tenit}% \textfont\slfam=\tensl \def\sl{\fam\slfam\tensl}% \textfont\ttfam=\tentt \def\tt{\fam\ttfam\tentt}% \textfont\bffam=\tenbf \scriptfont\bffam=\sevenbf \scriptscriptfont\bffam=\fivebf \def\bf{\fam\bffam\tenbf}% \tt \ttglue=.5em plus.25em minus.15em \normalbaselineskip=12pt \setbox\strutbox=\hbox{\vrule height8.5pt depth3.5pt width0pt}% \let\sc=\eightrm \let\big=\tenbig \normalbaselines\rm} \def\ninepoint{\def\rm{\fam0\ninerm}% switch to 9-point type \textfont0=\ninerm \scriptfont0=\sixrm \scriptscriptfont0=\fiverm \textfont1=\ninei \scriptfont1=\sixi \scriptscriptfont1=\fivei \textfont2=\ninesy \scriptfont2=\sixsy \scriptscriptfont2=\fivesy \textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex \textfont\itfam=\nineit \def\it{\fam\itfam\nineit}% Appendix E: Example Formats \textfont\slfam=\ninesl \def\sl{\fam\slfam\ninesl}% \textfont\ttfam=\ninett \def\tt{\fam\ttfam\ninett}% \textfont\bffam=\ninebf \scriptfont\bffam=\sixbf \scriptscriptfont\bffam=\fivebf \def\bf{\fam\bffam\ninebf}% \tt \ttglue=.5em plus.25em minus.15em \normalbaselineskip=11pt \setbox\strutbox=\hbox{\vrule height8pt depth3pt width0pt}% \let\sc=\sevenrm \let\big=\ninebig \normalbaselines\rm} \def\eightpoint{\def\rm{\fam0\eightrm}% switch to 8-point type \textfont0=\eightrm \scriptfont0=\sixrm \scriptscriptfont0=\fiverm \textfont1=\eighti \scriptfont1=\sixi \scriptscriptfont1=\fivei \textfont2=\eightsy \scriptfont2=\sixsy \scriptscriptfont2=\fivesy \textfont3=\tenex \scriptfont3=\tenex \scriptscriptfont3=\tenex \textfont\itfam=\eightit \def\it{\fam\itfam\eightit}% \textfont\slfam=\eightsl \def\sl{\fam\slfam\eightsl}% \textfont\ttfam=\eighttt \def\tt{\fam\ttfam\eighttt}% \textfont\bffam=\eightbf \scriptfont\bffam=\sixbf \scriptscriptfont\bffam=\fivebf \def\bf{\fam\bffam\eightbf}% \tt \ttglue=.5em plus.25em minus.15em \normalbaselineskip=9pt \setbox\strutbox=\hbox{\vrule height7pt depth2pt width0pt}% \let\sc=\sixrm \let\big=\eightbig \normalbaselines\rm} \def\tenbig#1{{\hbox{\left#1\vbox to8.5pt{}\right.\[email protected]}}} \def\ninebig#1{{\hbox{\textfont0=\tenrm\textfont2=\tensy \left#1\vbox to7.25pt{}\right.\[email protected]}}} \def\eightbig#1{{\hbox{\textfont0=\ninerm\textfont2=\ninesy \left#1\vbox to6.5pt{}\right.\[email protected]}}} \def\tenmath{\tenpoint\fam-1 } % for 10-point math in 9-point territory Issues of page layout are dealt with next. First, the basics: \newdimen\pagewidth \newdimen\pageheight \newdimen\ruleht \hsize=29pc \vsize=44pc \maxdepth=2.2pt \parindent=3pc \pagewidth=\hsize \pageheight=\vsize \ruleht=.5pt \abovedisplayskip=6pt plus 3pt minus 1pt \belowdisplayskip=6pt plus 3pt minus 1pt \abovedisplayshortskip=0pt plus 3pt \belowdisplayshortskip=4pt plus 3pt (The curious value of \maxdepth was chosen only to provide an example in Chapter 15; there’s no deep reason behind it.) When the author prepared this book, he made notes about what things ought to go into the index from each page. These notes were shown in small type on his proofsheets, like the words ‘marginal hacks’ in the right margin of this page. The manmac format uses an insertion class called \margin to handle such notes. \newinsert\margin \dimen\margin=\maxdimen % no limit on the number of marginal notes \count\margin=0 \skip\margin=0pt % marginal inserts take up no space 415 marginal hacks 416 Appendix E: Example Formats The \footnote macro of plain TEX needs to be changed because footnotes are indented and set in 8-point type. Some simplifications have also been made, since footnotes are used so infrequently in this book. \def\footnote#1{\edef\@sf{\spacefactor\the\spacefactor}#1\@sf \insert\footins\bgroup\eightpoint \interlinepenalty100 \let\par=\endgraf \leftskip=0pt \rightskip=0pt \splittopskip=10pt plus 1pt minus 1pt \floatingpenalty=20000 \smallskip\item{#1}\bgroup\strut\aftergroup\@foot\let\next} \skip\footins=12pt plus 2pt minus 4pt % space added when footnote exists \dimen\footins=30pc % maximum footnotes per page The text of running headlines will be kept in a control sequence called \rhead. Some pages should not have headlines; the \titlepage macro suppresses the headline on the next page that is output. \newif\iftitle \def\titlepage{\global\titletrue} % for pages without headlines \def\rhead{} % \rhead contains the running headline \def\leftheadline{\hbox to \pagewidth{% \vbox to 10pt{}% strut to position the baseline \llap{\tenbf\folio\kern1pc}% folio to left of text \tenit\rhead\hfil}} % running head flush left \def\rightheadline{\hbox to \pagewidth{\vbox to 10pt{}% \hfil\tenit\rhead\/% running head flush right \rlap{\kern1pc\tenbf\folio}}} % folio to right of text Pages are shipped to the output by the \onepageout macro, which attaches headlines, marginal notes, and/or footnotes, as appropriate. Special registration marks are typeset at the top of title pages, so that the pages will line up properly on printing plates that are made photographically from TEX’s “camera-ready” output. A small page number is also printed next to the corner markings; such auxiliary information will, of course, be erased before the pages are actually printed. \def\onepageout#1{\shipout\vbox{ % here we define one page of output \offinterlineskip % butt the boxes together \vbox to 3pc{ % this part goes on top of the 44pc pages \iftitle \global\titlefalse \setcornerrules \else\ifodd\pageno\rightheadline\else\leftheadline\fi\fi \vfill} \vbox to \pageheight{ \ifvoid\margin\else % marginal info is present \rlap{\kern31pc\vbox to0pt{\kern4pt\box\margin \vss}}\fi #1 % now insert the main information \ifvoid\footins\else % footnote info is present \vskip\skip\footins \kern-3pt \hrule height\ruleht width\pagewidth \kern-\ruleht \kern3pt \unvbox\footins\fi \boxmaxdepth=\maxdepth}} \advancepageno} Appendix E: Example Formats \def\setcornerrules{\hbox to \pagewidth{% for camera alignment \vrule width 1pc height\ruleht \hfil \vrule width 1pc} \hbox to \pagewidth{\llap{\sevenrm(page \folio)\kern1pc}% \vrule height1pc width\ruleht depth0pt \hfil \vrule width\ruleht depth0pt}} \output{\onepageout{\unvbox255}} A different output routine is needed for Appendix I (the index), because most of that appendix appears in two-column format. Instead of handling double columns with an ‘\lr’ switch, as discussed in Chapter 23, manmac does the job with \vsplit, after collecting more than enough material to fill a page. This approach makes it comparatively easy to balance the columns on the last page of the index. A more difficult approach would be necessary if the index contained insertions (e.g., footnotes); fortunately, it doesn’t. Furthermore, there is no need to use \mark as suggested in the index example of Chapter 23, since the entries in Appendix I tend to be quite short. The only real complication that manmac faces is the fact that Appendix I begins and ends with single-column format; partial pages need to be juggled carefully as the format changes back and forth. \newbox\partialpage \def\begindoublecolumns{\begingroup \output={\global\setbox\partialpage=\vbox{\unvbox255\bigskip}}\eject \output={\doublecolumnout} \hsize=14pc \vsize=89pc} \def\enddoublecolumns{\output={\balancecolumns}\eject \endgroup \pagegoal=\vsize} \def\doublecolumnout{\splittopskip=\topskip \splitmaxdepth=\maxdepth \[email protected]=44pc \advance\[email protected] by-\ht\partialpage \setbox0=\vsplit255 to\[email protected] \setbox2=\vsplit255 to\[email protected] \onepageout\pagesofar \unvbox255 \penalty\outputpenalty} \def\pagesofar{\unvbox\partialpage \wd0=\hsize \wd2=\hsize \hbox to\pagewidth{\box0\hfil\box2}} \def\balancecolumns{\setbox0=\vbox{\unvbox255} \[email protected]=\ht0 \advance\[email protected] by\topskip \advance\[email protected] by-\baselineskip \divide\[email protected] by2 \splittopskip=\topskip {\vbadness=10000 \loop \global\setbox3=\copy0 \global\setbox1=\vsplit3 to\[email protected] \ifdim\ht3>\[email protected] \global\advance\[email protected] by1pt \repeat} \setbox0=\vbox to\[email protected]{\unvbox1} \setbox2=\vbox to\[email protected]{\unvbox3} \pagesofar} The balancing act sets \vbadness infinite while it is searching for a suitable column height, so that underfull vboxes won’t be reported unless the actual columns are bad after balancing. The columns in Appendix I have a lot of stretchability, since there’s a \parskip of 0pt plus .8pt between adjacent entries, and since there is room for more than 50 lines per column; therefore the manmac balancing routine tries to make both the top and bottom baselines agree at the end of the index. In applications where the glue is not so flexible it would be more appropriate to let the right-hand column be a little short; the best way to do this is probably to replace the command ‘\unvbox3’ by ‘\dimen2=\dp3 \unvbox3 \kern-\dimen2 \vfil’. 417 418 Appendix E: Example Formats The next macros are concerned with chapter formatting. Each chapter in the manuscript file starts out with the macro \beginchapter; it ends with \endchapter and two quotations, followed by \eject. For example, Chapter 15 was generated by TEX commands that look like this in the file manual.tex: \beginchapter Chapter 15. How \TeX\ Makes\\Lines into Pages \TeX\ attempts to choose desirable places to divide your document into . . . (about 1100 lines of the manuscript are omitted here) break. \ (Deep breath.) \ You got that? \endchapter Since it is impossible to foresee how [footnotes] will happen to come out in the make-up, it is impracticable to number them from 1 up on each page. The best way is to number them consecutively throughout an article or by chapters in a book. \author UNIVERSITY OF CHICAGO PRESS, {\sl Manual of Style\/} (1910) \bigskip Don’t use footnotes in your books, Don. \author JILL KNUTH (1962) \eject The ‘\\’ in the title line specifies a line break to be used on the left-hand title page that faces the beginning of the chapter. Most of the \beginchapter macro is devoted to preparing that title page; the \TeX logo needs somewhat different spacing when it is typeset in \titlefont, and the \inchhigh digits need to be brought closer together in order to look right in a title. \newcount\exno % for the number of exercises in the current chapter \newcount\subsecno % for the number of subsections in the current chapter \outer\def\beginchapter#1 #2#3. #4\par{\def\chapno{#2#3} \global\exno=0 \subsecno=0 \ifodd\pageno \errmessage{You had too much text on that last page; I’m backing up} \advance\pageno by-1 \fi \def\\{ } % \\’s in the title will be treated as spaces \message{#1 #2#3:} % show the chapter title on the terminal \xdef\rhead{#1 #2#3: #4\unskip} % establish a new running headline {\def\TeX{T\kern-.2em\lower.5ex\hbox{E}\kern-.06em X} \def\\{#3} \ifx\empty\\ \rightline{\inchhigh #2\kern-.04em} \else\rightline{\inchhigh #2\kern-.06em#3\kern-.04em}\fi \vskip1.75pc \baselineskip=36pt \lineskiplimit=1pt \lineskip=12pt \let\\=\cr % now the \\’s are line dividers \halign{\line{\titlefont\hfil##}\\#4\unskip\\} \titlepage\vfill\eject} % output the chapter title page \tenpoint\noindent\ignorespaces} % the first paragraph is not indented Appendix E: Example Formats An extra page is ejected at the end of a chapter, if necessary, so that the closing quotations will occur on a right-hand page. (The logic for doing this is not perfect, but it doesn’t need to be, because it fails only when the chapter has to be shortened or lengthened anyway; book preparation with TEX, as with type, encourages interaction between humans and machines.) The lines of the quotations are set flush right by using \obeylines together with a stretchable \leftskip: \outer\def\endchapter{\ifodd\pageno \else\vfill\eject\null\fi \begingroup\bigskip\vfill % beginning of the quotes \def\eject{\endgroup\eject} % ending of the quotes \def\par{\ifhmode\/\endgraf\fi}\obeylines \def\TeX{T\kern-.2em\lower.5ex\hbox{E}X} \eightpoint \let\tt=\ninett \baselineskip=10pt \interlinepenalty=10000 \leftskip=0pt plus 40pc minus \parindent \parfillskip=0pt \let\rm=\eightss \let\sl=\eightssi \everypar{\sl}} \def\author#1(#2){\smallskip\noindent\rm--- #1\unskip\enspace(#2)} We come now to what goes on inside the chapters themselves. Dangerous and doubly dangerous bends are specified by typing ‘\danger’ or ‘\ddanger’ just before a paragraph that is supposed to display a warning symbol: \def\dbend{{\manual\char127}} % "dangerous bend" sign \def\[email protected]{\medbreak\begingroup\clubpenalty=10000 \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2 \hbox to0pt{\hskip-\hangindent\dbend\hfill}\ninepoint} \outer\def\danger{\[email protected]} \def\[email protected]{\medbreak\begingroup\clubpenalty=10000 \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2 \hbox to0pt{\hskip-\hangindent\dbend\kern1pt\dbend\hfill}\ninepoint} \outer\def\ddanger{\[email protected]} \def\enddanger{\endgraf\endgroup} % omits the \medbreak (It’s necessary to type ‘\enddanger’ at the end of a dangerous bend only in rare cases that a medium space is not desired after the paragraph; e.g., ‘\smallskip\item’ might be used to give an itemized list within the scope of the dangerous bend sign.) A few chapters and appendices of this book (e.g., Chapter 18 and Appendix B) are divided into numbered subsections. Such subsections are specified in the manuscript by typing, for example, \subsection Allocation of registers. Appendix A is subdivided in another way, by paragraphs that have answer numbers: \outer\def\subsection#1. {\medbreak\advance\subsecno by 1 \noindent{\it \the\subsecno.\enspace#1.\enspace}} \def\ansno#1.#2:{\medbreak\noindent \hbox to\parindent{\bf\hss#1.#2.\enspace}\ignorespaces} We will see below that the manuscript doesn’t actually specify an \ansno directly; each call of \ansno is generated automatically by the \answer macro. Appendix H points out The TEXbook calls for three hyphenation exceptions: \hyphenation{man-u-script man-u-scripts ap-pen-dix} 419 420 Appendix E: Example Formats A few macros in manmac provide special constructions that are occasionally needed in paragraphs: \MF for ‘hijklmnj’, \AmSTeX for ‘AMS-TEX’, \bull for ‘ ’, \dn and \up for ‘↓’ and ‘↑’, \| and for ‘|’ and ‘Ã’. To typeset 3 pt of hstuffi, ´105 = 69, ˝69 = 105, wow the manuscript says 3\pt of \, \oct{105}=69, \hex{69}=105, \cstok{wow} using the macros \pt, \ F N V ^ f n v ~ Υ ² ν χ ϕ /  ? G O W _ g o w Ä ˝8 ˝9 ˝A ˝B ˝C ˝D ˝E ˝F ˝0x ˝1x ˝2x ˝3x ˝4x ˝5x ˝6x ˝7x Appendix F: Font Tables When TEX typesets mathematics it assumes that family 0 contains normal roman fonts and that families 1, 2, and 3 contain math italic, math symbol, and math extension fonts. The special characters in these fonts are usually given symbolic names by a \mathchardef instruction, which assigns a hexadecimal code to the symbol. This code has four digits, where the first tells what kind of symbol is involved, the second specifies the family, and the other two give the font position. For example, \mathchardef\ll="321C says that \ll is character ˝1C of the math symbol font (family 2), and that it’s a “relation” (class 3). A complete list of the symbolic names provided by the plain TEX format appears later in this appendix. Font cmsy10 is plain TEX’s math symbol font, and it contains 128 symbols laid out as shown below. Its \skewchar should be set to ´060 so that math accents will be positioned properly over the calligraphic capital letters. Figure 5. Math symbol font layout, showing cmsy10 (\cal, \textfont2). ´00x ´01x ´02x ´03x ´04x ´05x ´06x ´07x ´10x ´11x ´12x ´13x ´14x ´15x ´16x ´17x ´0 ´1 ´2 ´3 ´4 ´5 ´6 ´7 − ⊕ ³ ∼ ← ⇐ 0 ∀ ℵ H P X  h √ · ª ≡ ≈ → ⇒ ∞ ∃ A I Q Y a i q † × ⊗ ⊆ ⊂ ↑ ⇑ ∈ ¬ B J R Z b | ∇ ‡ ∗ ® ⊇ ⊃ ↓ ⇓ 3 ∅ C K S ∪ c k ∫ ¶ ÷ ¯ ≤ ¿ ↔ ⇔ 4 < D L T ∩ d l t ♣ ¦ ° ≥ À % 5 = E M U ] e m u ♦ ± ◦ ¹ ≺ & . 6 > F N V ∧ { \ v ♥ ∓ • º Â ' ∝ 7 ⊥ G O W ∨ } o w ♠ § ˝8 ˝9 ˝A ˝B ˝C ˝D ˝E ˝F ˝0x ˝1x ˝2x ˝3x ˝4x ˝5x ˝6x ˝7x 431 432 Appendix F: Font Tables The final font of plain TEX is cmex10, which includes large symbols and pieces that can be used to build even larger ones. For example, arbitrarily large left parentheses can be constructed by putting ´060 at the top and ´100 at the bottom, and by using as many copies of ´102 as necessary in the middle. Large square root signs are made from ´164 , ´165 , and ´166 ; large left braces have four component parts: ´070 , ´072 , ´074 , ´076 . Figure 6. Math extension font layout, showing cmex10 (\textfont3). ´00x ´01x ´02x ´03x ´04x ´05x ´06x ´07x ´10x ´11x ´12x ´13x ´14x ´15x ´16x ´17x ´0 ¡ ´1 ¢ ´2 £ ´3 ¤ ´4 ¥ ´5 ¦ ´6 § ´7 ¨ ² ˝0x » ¼ ½ ¾ ¿ À Á Â ˝1x ) * + , - . / © ³ Ã (   H P ª ´ !   I Q X Y h i  a  µ " # ° ¸ % ± ¹ & º ' ˝2x J K L M N O ˝4x [ \ ] ^ _ ˝5x  R Z b j q r ˝8 ˝9 ˝A y ¯ · p x ® z  S D T c k d l { | s ˝B t ˝C E U e m F V W f n g o ~ Ä u v ˝D ˝E } G w ˝F ˝3x ˝6x ˝7x Appendix F: Font Tables When TEX “loads” a font into its memory, it doesn’t look at the actual shapes of the characters; it only loads the font metric information (e.g., cmr10.tfm), which includes the heights, widths, depths, and italic corrections, together with information about ligatures and kerning. Furthermore, the metric information that comes with a font like cmex10 tells TEX that certain characters form a series; for example, all of the left parentheses are linked together in order of increasing size: ´000 , ´020 , ´022 , and ´040 , followed by the extensible left parenthesis, which is ´060 + [´102 ]n + ´100 . Similarly, the two summation signs (´120 , ´130 ) and the three \widehat accents (´142 , ´143 , ´144 ) are linked together. Appendix G explains how TEX goes about choosing particular sizes for math delimiters, math operators, and math accents. Each font also has at least seven \fontdimen parameters, which have the following significance and typical values (rounded to two decimal places): # 1 2 3 4 5 6 7 Meaning Value in cmr10 cmbx10 cmsl10 cmti10 cmtt10 cmmi10 slant per pt 0.00 pt 0.00 pt 0.17 pt 0.25 pt 0.00 pt 0.25 pt interword space 3.33 pt 3.83 pt 3.33 pt 3.58 pt 5.25 pt 0.00 pt interword stretch 1.67 pt 1.92 pt 1.67 pt 1.53 pt 0.00 pt 0.00 pt interword shrink 1.11 pt 1.28 pt 1.11 pt 1.02 pt 0.00 pt 0.00 pt x-height 4.31 pt 4.44 pt 4.31 pt 4.31 pt 4.31 pt 4.31 pt quad width 10.00 pt 11.50 pt 10.00 pt 10.22 pt 10.50 pt 10.00 pt extra space 1.11 pt 1.28 pt 1.11 pt 1.02 pt 5.25 pt 0.00 pt The slant parameter is used to position accents; the next three parameters define interword spaces when text is being typeset; the next two define the font-oriented dimensions 1ex and 1em; and the last is the additional amount that is added to interword spaces at the end of sentences (i.e., when \spacefactor is 2000 or more and \xspaceskip is zero). When a font is magnified (using ‘at’ or ‘scaled’), all of the parameters except the slant are subject to magnification at the time the font is loaded into TEX’s memory. Notice that cmmi10 has zero spacing. This is the mark of a font that is intended only for mathematical typesetting; the rules in Appendix G state that the italic correction is added between adjacent characters from such fonts. Math symbol fonts (i.e., fonts in family 2) are required to have at least 22 \fontdimen parameters instead of the usual seven; similarly, math extension fonts must have at least 13. The significance of these additional parameters is explained in Appendix G. If you want to increase the number of parameters past the number that actually appear in a font’s metric information file, you can assign new values immediately after that font has been loaded. For example, if some font \ff with seven parameters has just entered TEX’s memory, the command \fontdimen13\ff=5pt will set parameter number 13 to 5 pt; the intervening parameters, numbers 8–12, will be set to zero. You can even give more than seven parameters to \nullfont, provided that you assign the values before any actual fonts have been loaded. 433 434 Appendix F: Font Tables Now that the font layouts have all been displayed, it’s time to consider the names of the various mathematical symbols. Plain TEX defines more than 200 control sequences by which you can refer to math symbols without having to find their numerical positions in the layouts. It’s generally best to call a symbol by its name, for then you can easily adapt your manuscripts to other fonts, and your manuscript will be much more readable. The symbols divide naturally into groups based on their mathematical class (Ord, Op, Bin, Rel, Open, Close, or Punct), so we shall follow that order as we discuss them. N.B.: Unless otherwise stated, math symbols are available only in math modes. For example, if you say ‘\alpha’ in horizontal mode, TEX will report an error and try to insert a sign. 1. Lowercase Greek letters. α β γ δ ² ε ζ η θ ϑ \alpha \beta \gamma \delta \epsilon \varepsilon \zeta \eta \theta \vartheta ι κ λ µ ν ξ o π ρ \iota \kappa \lambda \mu \nu \xi o \pi \varpi \rho % σ ς τ υ φ ϕ χ ψ ω \varrho \sigma \varsigma \tau \upsilon \phi \varphi \chi \psi \omega There’s no \omicron, because it would look the same as o. Notice that the letter \upsilon (υ) is a bit wider than v (v); both of them should be distinguished from \nu (ν). Similarly, \varsigma (ς) should not be confused with \zeta (ζ). It turns out that \varsigma and \upsilon are almost never used in math formulas; they are included in plain TEX primarily because they are sometimes needed in short Greek citations (cf. Appendix J). 2. Uppercase Greek letters. Γ ∆ Θ Λ \Gamma \Delta \Theta \Lambda Ξ Π Σ Υ \Xi \Pi \Sigma \Upsilon Φ \Phi Ψ \Psi Ω \Omega The other Greek capitals appear in the roman alphabet (\Alpha ≡ {\rm A}, \Beta ≡ {\rm B}, etc.). It’s conventional to use unslanted letters for uppercase Greek, and slanted letters for lowercase Greek; but you can obtain (Γ, ∆, . . . , Ω) by typing ({\mit\Gamma}, {\mit\Delta}, \ldots, {\mit\Omega}). 3. Calligraphic capitals. To get the letters A . . . Z that appear in Figure 5, type {\cal A}\ldots{\cal Z}. Several other alphabets are also used with mathematics (notably Fraktur, script, and “blackboard bold”); they don’t come with plain TEX, but more elaborate formats like AMS-TEX do provide them. Appendix F: Font Tables 4. Miscellaneous symbols of type Ord. ℵ ¯h ı   ℘ < = ∂ ∞ \aleph \hbar \imath \jmath \ell \wp \Re \Im \partial \infty 0 \prime ∅ \emptyset ∇ √ \nabla \surd > \top ⊥ \bot k \| 6 \angle 4 \triangle \ \backslash ∀ ∃ ¬ [ \ ] ♣ ♦ ♥ ♠ \forall \exists \neg \flat \natural \sharp \clubsuit \diamondsuit \heartsuit \spadesuit The dotless letters \imath and \jmath should be used when i and j are accented; for example, \hat\imath yields ˆı. The \prime symbol is intended for use in subscripts and superscripts, as explained in Chapter 16, so you usually see it in a smaller size. On the other hand, the \angle symbol has been built up from other pieces; it does not get smaller when it appears in a subscript or superscript. 5. Digits. To get italic digits 0123456789, say {\it0123456789}; to get boldface digits 0123456789, say {\bf0123456789}; to get oldstyle digits , say {\oldstyle0123456789}. These conventions work also outside of math mode. 6. “Large” operators. The following symbols come in two sizes, for text and display styles: PX T \ JK \sum \bigcap \bigodot QY S [ NO \prod \bigcup \bigotimes a F G LM \coprod \bigsqcup \bigoplus Z _ ] R W U \int \bigvee \biguplus I H V ^ \oint \bigwedge It is important to distinguish these large Op symbols from the similar but smaller Bin symbols whose names are the same except for a ‘big’ prefix. Large operators usually occur at the beginning of a formula or subformula, and they usually are subscripted; binary operations usually occur between two symbols or subformulas, and they rarely are subscripted. For example, Sm \bigcup_{n=1}^m(x_n\cup y_n) yields n=1 (xn ∪ yn ) The large operators \sum, \prod, \coprod, and \int should also be distinguished from smaller symbols called \Sigma (Σ), \Pi (Π), \amalg (q), and \smallint (∫ ), respectively; the \smallint operator is rarely used. 435 436 Appendix F: Font Tables 7. Binary operations. Besides + and −, you can type ± ∓ \ · × ∗ ? ¦ ◦ • ÷ \pm \mp \setminus \cdot \times \ast \star \diamond \circ \bullet \div ∩ ∪ ] u t / . o ° 4 5 \cap \cup \uplus \sqcap \sqcup \triangleleft \triangleright \wr \bigcirc \bigtriangleup \bigtriangledown ∨ ∧ ⊕ ª ⊗ ® ¯ † ‡ q \vee \wedge \oplus \ominus \otimes \oslash \odot \dagger \ddagger \amalg It’s customary to say G\backslash H to denote double cosets of G by H (G\H), and p\backslash n to mean that p divides n (p\n); but X\setminus Y denotes the elements of set X minus those of set Y (X \ Y ). Both operations use the same symbol, but \backslash is type Ord, while \setminus is type Bin (so TEX puts more space around it). 8. Relations. Besides , and =, you can type ≤ ≺ ¹ ¿ ⊂ ⊆ v ∈  ^ _ \leq \prec \preceq \ll \subset \subseteq \sqsubseteq \in \vdash \smile \frown ≥ Â º À ⊃ ⊇ w 3 a | k \geq \succ \succeq \gg \supset \supseteq \sqsupseteq \ni \dashv \mid \parallel ≡ ∼ ' ³ ≈ ∼ = ./ ∝ |= . = ⊥ \equiv \sim \simeq \asymp \approx \cong \bowtie \propto \models \doteq \perp The symbols \mid and \parallel define relations that use the same characters as you get from | and \|; TEX puts space around them when they are relations. 9. Negated relations. Many of the relations just listed can be negated or “crossed out” by prefixing them with \not, as follows: 6< 6 ≤ 6≺ 6¹ 6⊂ 6⊆ 6v \not< \not\leq \not\prec \not\preceq \not\subset \not\subseteq \not\sqsubseteq 6> 6 ≥ 6Â 6 º 6⊃ 6 ⊇ 6 w \not> \not\geq \not\succ \not\succeq \not\supset \not\supseteq \not\sqsupseteq 6= 6 ≡ 6∼ 6 ' 6≈ 6∼ = 6 ³ \not= \not\equiv \not\sim \not\simeq \not\approx \not\cong \not\asymp Appendix F: Font Tables The symbol \not is a relation character of width zero, so it will overlap a relation that comes immediately after it. The positioning isn’t always ideal, because some relation symbols are wider than others; for example, \not\in gives ‘6∈’, but it is preferable to have a steeper cancellation, ‘∈’. / The latter symbol is available as a special control sequence called \notin. The definition of \notin in Appendix B indicates how similar symbols can be constructed. 10. Arrows. There’s also another big class of relations, namely those that point: ← ⇐ → ⇒ ↔ ⇔ 7→ ←( ) * ) \leftarrow ←− \longleftarrow \Leftarrow ⇐= \Longleftarrow \rightarrow −→ \longrightarrow \Rightarrow =⇒ \Longrightarrow \leftrightarrow ←→\longleftrightarrow \Leftrightarrow ⇐⇒\Longleftrightarrow \mapsto 7−→ \longmapsto \hookleftarrow ,→ \hookrightarrow \leftharpoonup * \rightharpoonup \leftharpoondown + \rightharpoondown \rightleftharpoons ↑ ⇑ ↓ ⇓ l m % & . - \uparrow \Uparrow \downarrow \Downarrow \updownarrow \Updownarrow \nearrow \searrow \swarrow \nwarrow Up and down arrows will grow larger, like delimiters (see Chapter 17). To put symbols over left and right arrows, plain TEX provides a \buildrel macro: You type \buildrelhsuperscripti\overhrelationi, and the superscript is placed on top of the relation just as limits are placed over large operators. For example, αβ −→ def = \buildrel \alpha\beta \over \longrightarrow \buildrel \rm def \over = (In this context, ‘\over’ does not define a fraction.) 11. Openings. The following left delimiters are available, besides ‘(’: [ \lbrack { \lbrace b \lfloor h \langle d \lceil You can also type simply ‘[’ to get \lbrack. All of these will grow if you prefix them by \bigl, \Bigl, \biggl, \Biggl, or \left. Chapter 17 also mentions \lgroup and \lmoustache, which are available in sizes greater than \big. If you need more delimiters, the following combinations work reasonably well in the normal text size: [[ \lbrack\!\lbrack hh \langle\!\langle (( (\!( 12. Closings. The corresponding right delimiters are present too: ] \rbrack } \rbrace c \rfloor i \rangle e \rceil Everything that works for openings works also for closings, but reversed. 437 438 Appendix F: Font Tables 13. Punctuation. TEX puts a thin space after commas and semicolons that appear in mathematical formulas, and it does the same for a colon that is called \colon. (Otherwise a colon is considered to be a relation, as in ‘x := y’ and ‘a : b :: c : d’, which you type by saying ‘x:=y’ and ‘a:b::c:d’.) Examples of \colon are f: A → B L(a, b; c: x, y; z) f\colon A\rightarrow B L(a,b;c\colon x,y;z) Plain TEX also defines \ldotp and \cdotp to be ‘.’ and ‘·’ with the spacing of commas and semicolons. These symbols don’t occur directly in formulas, but they are useful in the definition of \ldots and \cdots. 14. Alternate names. If you don’t like plain TEX’s name for some math symbol— for example, if there’s another name that looks better or that you can remember more easily—the remedy is simple: You just say, e.g., ‘\let\cupcap=\asymp’. Then you can type ‘f(n)\cupcap n’ instead of ‘f(n)\asymp n’. Some symbols have alternate names that are so commonly used that plain TEX provides two or more equivalent control sequences: 6= ≤ ≥ { } → ← 3 ∧ ∨ ¬ | k \ne or \neq (same as \not=) \le (same as \leq) \ge (same as \geq) \{ (same as \lbrace) \} (same as \rbrace) \to (same as \rightarrow) \gets (same as \leftarrow) \owns (same as \ni) \land (same as \wedge) \lor (same as \vee) \lnot (same as \neg) \vert (same as |) \Vert (same as \|) There’s also \iff ( ⇐⇒ ), which is just like \Longleftrightarrow except that it puts an extra thick space at each side. 15. Non-math symbols. Plain TEX makes four special symbols available outside of math mode, although the characters themselves are actually typeset from the math symbols font: § ¶ † ‡ \S \P \dag \ddag These control sequences do not act like ordinary math symbols; they don’t change their size when they appear in subscripts or superscripts, and you must say, e.g., Appendix F: Font Tables x^{\P} instead of x^\P when you use them in formulas. However, the \dag and \ddag symbols are available in math mode under the names \dagger and \ddagger. It would be easy to define mathematical equivalents of \S and \P, if these symbols suddenly caught a mathematician’s fancy. Seek not for fresher founts afar, Just drop your bucket where you are. — SAM WALTER FOSS, Back Country Poems (1892) No one compositor will have all the signs and symbols available. The number of special signs and symbols is almost limitless, with new ones being introduced all the time. — UNIVERSITY OF CHICAGO PRESS, Manual of Style (1969) 439 (page 440) G Generating Boxes from Formulas Appendix G: Generating Boxes from Formulas People who define new math fonts and/or macros sometimes need to know exactly how TEX manipulates the constituents of formulas. The purpose of this appendix is to explain the precise positioning rules by which TEX converts a math list into a horizontal list. (It is a good idea to review the introduction to math lists in Chapter 17 before reading further; “double dangerous bends” are implied throughout this appendix.) TEX relies on lots of parameters when it typesets formulas, and you have the option of changing any or all of them. But of course you will want to know what each parameter means, before you change it. Therefore each rule below is numbered, and a table appears at the end to show which rules depend on which parameters. The most important parameters appear in the symbol fonts (family 2) and the extension fonts (family 3). TEX will not typeset a formula unless \textfont2, \scriptfont2, and \scriptscriptfont2 each contain at least 22 \fontdimen parameters. For brevity we shall call these parameters σ1 to σ22 , where the parameter is taken from \textfont2 if the current style is display or text (D or D 0 or T or T 0 ), from \scriptfont2 if the current style is S or S 0 , and from \scriptscriptfont2 otherwise. Similarly, the three fonts in family 3 must each have at least 13 \fontdimen parameters, and we will denote them by ξ1 to ξ13 . The notation ξ9 , for example, stands for the ninth parameter of \scriptfont3, if TEX is typesetting something in \scriptstyle. A math list is a sequence of items of the various kinds listed in Chapter 17, and TEX typesets a formula by converting a math list to a horizontal list. When such typesetting begins, TEX has two other pieces of information in addition to the math list itself. (a) The starting style tells what style should be used for the math list, unless another style is specified by a style item. For example, the starting style for a displayed formula is D, but for an equation in the text or an equation number it is T ; and for a subformula it can be any one of the eight styles defined in Chapter 17. We shall use C to stand for the current style, and we shall say that the math list is being typeset in style C. (b) The typesetting is done either with or without penalties. Formulas in the text of a paragraph are converted to horizontal lists in which additional penalty items are inserted after binary operations and relations, in order to aid in line breaking. Such penalties are not inserted in other cases, because they would serve no useful function. The eight styles are considered to be D > D 0 > T > T 0 > S > S 0 > SS > SS 0 , in decreasing order. Thus, C ≤ S means that the current style is S, S 0 , SS , or SS 0 . Style C 0 means the current style with a prime added if one isn’t there; for example, we have C 0 = T 0 if and only if C = T or C = T 0 . Style C↑ is the superscript style for C; this means style S if C is D or T , style S 0 if C is D0 or T 0 , style SS if C is S or SS , and style SS 0 if C is S 0 or SS 0 . Finally, style C↓ is the subscript style, which is (C↑)0 . Chapter 17 stated that the most important components of math lists are called atoms, and that each atom has three fields called its nucleus, subscript, and superscript. We frequently need to execute a subroutine called “Set box x to the so-and-so field in style such-and-such.” This means (a) if the specified field is empty, x is set equal to a null box; (b) if the field contains a symbol, x is set to an hbox containing that symbol in the appropriate size, and the italic correction for the character is included in the width of the box; (c) if the field contains a math list or horizontal list, x is set to an hbox containing the result of typesetting that list with the specified starting style. In case (c), the glue is set with no stretching or shrinking, and an additional level of hboxing is omitted if it turns out to be redundant. Another subroutine sets box x to a specified variable delimiter, having a specified minimum height plus depth. This means that a search is conducted as follows: 441 442 Appendix G: Generating Boxes from Formulas The delimiter is defined by two symbols, a “small character” a in family f and a “large character” b in family g. The search looks first at character a in scriptscriptfont f , if C ≤ SS ; then it looks at a in scriptfont f , if C ≤ S; then it looks at a in textfont f . If nothing suitable is found from a and f , the larger alternative b and g is examined in the same way. Either (a, f ) or (b, g) may be (0, 0), which means that the corresponding part of the search is to be bypassed. When looking at a character in a font, the search stops immediately if that character has sufficient height plus depth, or if the character is extensible; furthermore, if the character does not stop the search, but if it has a successor in the font, the successor is looked at next. (See the hijklmnj manual or the system documentation of tfm files for further information about successors and extensible characters.) If the search runs all the way to completion without finding a suitable character, the one with greatest height plus depth is chosen. If no characters at all were found (either because a = f = b = g = 0 or because the characters did not exist in the fonts), x is set to an empty box whose width is \nulldelimiterspace. If an extensible character was found, x is set to a vbox containing enough pieces to build up a character of sufficient size; the height of this vbox is the height of the topmost piece, and the width is the width of the repeatable piece. Otherwise x is set to an hbox containing the character that was found; the italic correction of the character is included in the width of this box. There’s also a subroutine that “reboxes” a given box to a given width. If the box doesn’t already have the desired width, TEX unpackages it (unless it was a vbox), then adds a kern for an italic correction if one was implied, and inserts \hss glue at both left and right; the resulting horizontal list is packaged into an hbox. This process is used, for example, to give a common width to the numerator and denominator of a fraction; it centers whichever is smaller, unless infinite glue is present in addition to the newly added \hss. If x is a box, we shall use the abbreviations h(x), d(x), and w(x) for its height, depth, and width, respectively. Here now are the rules for typesetting a given math list in starting style C. The process applies from left to right, translating each item in turn. Two passes are made over the list; most of the work is done by the first pass, which compiles individual translations of the math items. We shall consider this part of the task first: 1. If the current item is a rule or discretionary or penalty or “whatsit” or boundary item, simply leave it unchanged and move to the next item. 2. If the current item is glue or a kern, translate it as follows: If it is glue from \nonscript, check if the immediately following item is glue or a kern; and if so, remove that item if C ≤ S. Otherwise, if the current item is from \mskip or \mkern, convert 1 from mu to absolute units by multiplying each finite dimension by 18 σ6 . Then move on to the next item. 3. If the current item is a style change, set C to the specified style. Delete the current item from the list and move on to the next. 4. If the current item is a four-way choice, it contains four math lists for the four main styles. Replace it by the math list that corresponds to the current style C, then move to the first unprocessed item. 5. If the current item is a Bin atom, and if this was the first atom in the list, or if the most recent previous atom was Bin, Op, Rel, Open, or Punct, change the current Bin to Ord and continue with Rule 14. Otherwise continue with Rule 17. Appendix G: Generating Boxes from Formulas 6. If the current item is a Rel or Close or Punct atom, and if the most recent previous atom was Bin, change that previous Bin to Ord. Continue with Rule 17. 7. If the current item is an Open or Inner atom, go directly to Rule 17. 8. If the current item is a Vcent atom (from \vcenter), let its nucleus be a vbox of height-plus-depth v. Change the height to 12 v + a and the depth to 12 v − a, where a is the axis height, σ22 . Change this atom to type Ord and continue with Rule 17. 9. If the current item is an Over atom (from \overline), set box x to the nucleus in style C 0 . Then replace the nucleus by a vbox containing kern θ, hrule of height θ, kern 3θ, and box x, from top to bottom, where θ = ξ8 is the default rule thickness. (This puts a rule over the nucleus, with 3θ clearance, and with θ units of extra white space assumed to be present above the rule.) Continue with Rule 16. 10. If the current item is an Under atom (from \underline), set box x to the nucleus in style C. Then replace the nucleus by a vtop made from box x, kern 3θ, and hrule of height θ, where θ = ξ8 is the default rule thickness; and add θ to the depth of the box. (This puts a rule under the nucleus, with 3θ clearance, and with θ units of extra white space assumed to be present below the rule.) Continue with Rule 16. 11. If the current item is a Rad atom (from \radical, e.g., \sqrt), set box x to the nucleus in style C 0 . Let θ = ξ8 ; and let ϕ = σ5 if C > T , otherwise ϕ = θ. Set ψ = θ + 14 |ϕ|; this is the minimum clearance that will be allowed between box x and the rule that will go above it. Set box y to a variable delimiter for this radical atom, having height plus depth h(x) + d(x) + ψ + θ or more. Then set θ ← h(y); this is the thickness of the rule to be used in the radical construction. (Note that the font designer specifies the thickness of the rule by making it the height of the radical character; the baseline of the character should be precisely at the bottom of the rule.) If d(y) > h(x) + d(x) + ψ, increase ψ by half of the excess; i.e., set ψ ← 12 (ψ + d(y) − h(x) − d(x)). Construct a vbox consisting of kern θ, hrule of height θ, kern ψ, and box x, from top to bottom. The nucleus of the radical atom is now replaced by box y raised by h(x) + ψ, followed by the new vbox. Continue with Rule 16. 12. If the current item is an Acc atom (from \mathaccent), just go to Rule 16 if the accent character doesn’t exist in the current size. Otherwise set box x to the nucleus in style C 0 , and set u to the width of this box. If the nucleus is not a single character, let s = 0; otherwise set s to the kern amount for the nucleus followed by the \skewchar of its font. If the accent character has a successor in its font whose width is ≤ u, change it to the successor and repeat this sentence. Now set δ ← min(h(x), χ), where χ is \fontdimen5 (the x-height) in the accent font. If the nucleus is a single character, replace box x by a box containing the nucleus together with the superscript and subscript of the Acc atom, in style C, and make the sub/superscripts of the Acc atom empty; also increase δ by the difference between the new and old values of h(x). Put the accent into a new box y, including the italic correction. Let z be a vbox consisting of: box y moved right s + 12 (u − w(y)), kern −δ, and box x. If h(z) < h(x), add a kern of h(x) − h(z) above box y and set h(z) ← h(x). Finally set w(z) ← w(x), replace the nucleus of the Acc atom by box z, and continue with Rule 16. 13. If the current item is an Op atom, mark this atom as having limits if it has been marked with \limits, or if it has been marked with \displaylimits and C > T . If the nucleus is not a symbol, set δ ← 0 and go to Rule 13a. Otherwise if C > T and if the nucleus symbol has a successor in its font, move to the successor. (This is where 443 444 Appendix G: Generating Boxes from Formulas P R operators like and change to a larger size in display styles.) Put the symbol into a new box x, in the current size, and set δ to the italic correction for the character; include δ in the width of box x if and only if limits are to be set or there is no subscript. Shift box x down by 21 (h(x) − d(x)) − a, where a = σ22 , so that the operator character is centered vertically on the axis; this shifted box becomes the nucleus of the Op atom. 13a. If limits are not to be typeset for this Op atom, go to Rule 17; otherwise the limits are attached as follows: Set box x to the superscript field in style C↑; set box y to the nucleus field in style C; and set box z to the subscript field in style C↓. Rebox all three of these boxes to width max(w(x), w(y), w(z)). If the superscript field was not empty, attach box x above box y, separated by a kern of size max(ξ9 , ξ11 − d(x)), and shift box x right by 12 δ; also put a kern of size ξ13 above box x. If the subscript field was not empty, attach box z below box y, separated by a kern of size max(ξ10 , ξ12 − h(z)), and shift box z left by 12 δ; also put a kern of size ξ13 below box z. The resulting vbox becomes the nucleus of the current Op atom; move to the next item. 14. If the current item is an Ord atom, go directly to Rule 17 unless all of the following are true: The nucleus is a symbol; the subscript and superscript are both empty; the very next item in the math list is an atom of type Ord, Op, Bin, Rel, Open, Close, or Punct; and the nucleus of the next item is a symbol whose family is the same as the family in the present Ord atom. In such cases the present symbol is marked as a text symbol. If the font information shows a ligature between this symbol and the following one, using the specified family and the current size, then insert the ligature character and continue as specified by the font; in this process, two characters may collapse into a single Ord text symbol, and/or new Ord text characters may appear. If the font information shows a kern between the current symbol and the next, insert a kern item following the current atom. As soon as an Ord atom has been fully processed for ligatures and kerns, go to Rule 17. 15. If the current item is a generalized fraction (and it had better be, because that’s the only possibility left if Rules 1–14 don’t apply), let θ be the thickness of the bar line and let (λ, ρ) be the left and right delimiters. If this fraction was generated by \over or \overwithdelims, then θ = ξ8 ; if it was generated by \atop or \atopwithdelims, θ = 0; otherwise it was generated by \above or \abovewithdelims, and a specific value of θ was given at that time. The values of λ and ρ are null unless the fraction is “with delims.” 15a. Put the numerator into box x, using style T or T 0 if C is D or D 0 , otherwise using style C↑. Put the denominator into box z, using style T 0 if C > T , otherwise using C↓. If w(x) < w(z), rebox x to width w(z); if w(z) < w(x), rebox z to width w(x). 15b. If C > T , set u ← σ8 and v ← σ11 . Otherwise set u ← σ9 or σ10 , according as θ 6= 0 or θ = 0, and set v ← σ12 . (The fraction will be typeset with its numerator shifted up by an amount u with respect to the current baseline, and with the denominator shifted down by v, unless the boxes are unusually large.) 15c. If θ = 0 (\atop), the numerator and denominator are combined as follows: Set ϕ ← 7ξ8 or 3ξ8 , according as C > T or C ≤ T ; ϕ is the minimum clearance that will be tolerated between numerator and denominator. Let ψ = (u − d(x)) − (h(z) − v ) be the actual clearance that would be obtained with the current values of u and v; if ψ < ϕ, add 12 (ϕ − ψ) to both u and v. Then construct a vbox of height h(x) + u and depth d(z) + v, consisting of box x followed by an appropriate kern followed by box z. Appendix G: Generating Boxes from Formulas 15d. If θ 6= 0 (\over), the numerator and denominator are combined as follows: Set ϕ ← 3θ or θ, according as C > T or C ≤ T ; ϕ is the minimum clearance that will be tolerated between numerator or denominator and the bar line. Let a = σ22 be the current axis height; the middle of the bar line will be placed at this height. If (u − d(x)) − (a + 21 θ) < ϕ, increase u by the difference between these quantities; and if (a − 12 θ) − (h(z) − v ) < ϕ, increase v by the difference. Finally construct a vbox of height h(x) + u and depth d(z) + v, consisting of box x followed by a kern followed by an hrule of height θ followed by another kern followed by box z, where the kerns are figured so that the bottom of the hrule occurs at a − 12 θ above the baseline. 15e. Enclose the vbox that was constructed in Rule 15c or 15d by delimiters whose height plus depth is at least σ20 , if C > T , and at least σ21 otherwise. Shift the delimiters up or down so that they are vertically centered with respect to the axis. Replace the generalized fraction by an Inner atom whose nucleus is the resulting sequence of three boxes (left delimiter, vbox, right delimiter). Rules 1–15 account for the preliminary processing of math list items; but we still haven’t specified how subscripts and superscripts are to be typeset. Therefore some of those rules lead to the following post-process: 16. Change the current item to an Ord atom, and continue with Rule 17. 17. If the nucleus of the current item is a math list, replace it by a box obtained by typesetting that list in the current style. Then if the nucleus is not simply a symbol, go on to Rule 18. Otherwise we are in the common case that a math symbol is to be translated to its horizontal-list equivalent: Convert the symbol to a character box for the specified family in the current size. If the symbol was not marked by Rule 14 above as a text symbol, or if \fontdimen parameter number 2 of its font is zero, set δ to the italic correction; otherwise set δ to zero. If δ is nonzero and if the subscript field of the current atom is empty, insert a kern of width δ after the character box, and set δ to zero. Continue with Rule 18. 18. (The remaining task for the current atom is to attach a possible subscript and superscript.) If both subscript and superscript fields are empty, move to the next item. Otherwise continue with the following subrules: 18a. If the translation of the nucleus is a character box, possibly followed by a kern, set u and v equal to zero; otherwise set u ← h − q and v ← d + r, where h and d are the height and depth of the translated nucleus, and where q and r are the values of σ18 and σ19 in the font corresponding to styles C↑ and C↓. (The quantities u and v represent minimum amounts by which the superscript and subscript will be shifted up and down; these preliminary values of u and v may be increased later.) 18b. If the superscript field is empty (so that there is a subscript only), set box x to the subscript in style C↓, and add \scriptspace to w(x). Append this box to the translation of the current item, shifting it down by max(v, σ16 , h(x) − 54 |σ5 |), and move to the next item. (The idea is to make sure that the subscript is shifted by at least v and by at least σ16 ; furthermore, the top of the subscript should not extend above 54 of the current x-height.) 18c. Set box x to the superscript field in style C↑, and add \scriptspace to w(x). Then set u ← max(u, p, d(x) + 14 |σ5 |), where p = σ13 if C = D, p = σ15 if C = C 0 , and p = σ14 otherwise; this gives a tentative position for the superscript. 445 446 Appendix G: Generating Boxes from Formulas 18d. If the subscript field is empty (so that there is a superscript only), append box x to the translation of the current atom, shifting it up by u, and move to the next item. Otherwise (i.e., both subscript and superscript are present), set box y to the subscript in style C↓, add \scriptspace to w(y), and set v ← max(v, σ 17 ). 18e. (The remaining task is to position a joint subscript/superscript combination.) Let θ = ξ8 be the default rule thickness. If (u − d(x)) − (h(y) − v ) ≥ 4θ, go to Rule 18f. (This means that the white space between subscript and superscript is at least 4θ.) Otherwise reset v so that (u − d(x)) − (h(y) − v ) = 4θ. Let ψ = 45 |σ5 | − (u − d(x)). If ψ > 0, increase u by ψ and decrease v by ψ. (This means that the bottom of the superscript will be at least as high above the baseline as 54 of the x-height.) 18f. Finally, let δ be zero unless it was set to a nonzero value by Rules 13 or 17. (This is the amount of horizontal displacement between subscript and superscript.) Make a vbox of height h(x) + u and depth d(y) + v, consisting of box x shifted right by δ, followed by an appropriate kern, followed by box y. Append this vbox to the translation of the current item and move to the next. After the entire math list has been processed by Rules 1–18, TEX looks at the last atom (if there was one), and changes its type from Bin to Ord (if it was of type Bin). Then the following rule is performed: 19. If the math list begins and ends with boundary items, compute the maximum height h and depth d of the boxes in the translation of the math list that was made on the first pass, taking into account the fact that some boxes may be raised or lowered. Let a = σ22 be the axis height, and let δ = max(h−a, d+a) be the amount by which the formula extends away from the axis. Replace the boundary items by delimiters whose height plus depth is at least max(bδ/500cf, 2δ − l), where f is the \delimiterfactor and l is the \delimitershortfall. Shift the delimiters up or down so that they are vertically centered with respect to the axis. Change the left boundary item to an Open atom and the right boundary item to a Close atom. (All of the calculations in this step are done with C equal to the starting style of the math list; style items in the middle of the list do not affect the style of the right boundary item.) 20. Rules 1–19 convert the math list into a sequence of items in which the only remaining atoms are of types Ord, Op, Bin, Rel, Open, Close, Punct, and Inner. After that conversion is complete, a second pass is made through the entire list, replacing all of the atoms by the boxes and kerns in their translations. Furthermore, additional inter-element spacing is inserted just before each atom except the first, based on the type of that atom and the preceding one. Inter-element spacing is defined by the three parameters \thinmuskip, \medmuskip, and \thickmuskip; the mu units are converted to absolute units as in Rule 2 above. Chapter 18 has a chart that defines the interelement spacing, some of which is \nonscript, i.e., it is inserted only in styles > S. The list might also contain style items, which are removed during the second pass; they are used to change the current style just as in the the first pass, so that both passes have the same value of C when they work on any particular atom. 21. Besides the inter-element spacing, penalties are placed after the translation of each atom of type Bin or Rel, if the math list was part of a paragraph. The penalty after a Bin is \binoppenalty, and the penalty after a Rel is \relpenalty. However, the penalty is not inserted after the final item in the entire list, or if it has a numeric Appendix G: Generating Boxes from Formulas value ≥ 10000, or if the very next item in the list is already a penalty item, or after a Rel atom that is immediately followed by another Rel atom. 22. After all of the preceding actions have been performed, the math list has been totally converted to a horizontal list. If the result is being inserted into a larger horizontal list, in horizontal mode or restricted horizontal mode, it is enclosed by “math-on” and “math-off” items that each record the current value of \mathsurround. Or if this list is a displayed formula, it is processed further as explained in Chapter 19. Summary of parameter usage. Here is the promised index that refers to everything affected by the mysterious parameters in the symbol fonts. Careful study of the rules allows you to get the best results by appropriately setting the parameters for new fonts that you may wish to use in mathematical typesetting. Each font parameter has an external name that is used in supporting software packages; for example, σ14 is generally referred to as ‘sup2’ and ξ8 as ‘default rule thickness’. These external names are indicated in the table. Parameter Used in Parameter Used in σ2 σ5 σ6 σ8 σ9 σ10 σ11 σ12 σ13 σ14 σ15 σ16 space x height quad num1 num2 num3 denom1 denom2 sup1 sup2 sup3 sub1 17 11, 18b, 18c, 18e 2, 20 15b 15b 15b 15b 15b 18c 18c 18c 18b σ17 σ18 σ19 σ20 σ21 σ22 ξ8 ξ9 ξ10 ξ11 ξ12 ξ13 sub2 sup drop sub drop delim1 delim2 axis height default rule thickness big op spacing1 big op spacing2 big op spacing3 big op spacing4 big op spacing5 18d 18a 18a 15e 15e 8, 13, 15d, 19 9, 10, 11, 15, 15c, 18e 13a 13a 13a 13a 13a Besides the symbol and extension fonts (families 2 and 3), the rules above also refer to parameters in other families: Rule 17 uses \fontdimen parameter 2 (space) to determine whether to insert an italic correction between adjacent letters, and Rule 12 uses parameter 5 (x height) to position an accent character. Several non-font parameters also affect mathematical typesetting: dimension parameters \delimitershortfall (Rule 19), \nulldelimiterspace (in the construction of variable delimiters for Rules 11, 15e, 19), \mathsurround (Rule 22), and \scriptspace (Rules 18bcd); integer parameters \delimiterfactor (Rule 19), \binoppenalty (Rule 21), and \relpenalty (Rule 21); muglue parameters \thinmuskip, \medmuskip, and \thickmuskip (Rule 20). Woe to the author who always wants to teach! The secret of being a bore is to tell everything. — VOLTAIRE, De la Nature de l’Homme (1737) Very few Compositors are fond of Algebra, and rather chuse to be employed upon plain work. — PHILIP LUCKOMBE, The History and Art of Printing (1770) 447 (page 448) H Hyphenation Appendix H: Hyphenation It’s better to break a word with a hyphen than to stretch interword spaces too much. Therefore TEX tries to divide words into syllables when there’s no good alternative available. But computers are notoriously bad at hyphenation. When the typesetting of newspapers began to be fully automated, jokes about “the-rapists who pre-ached on wee-knights” soon began to circulate. It’s not hard to understand why machines have behaved poorly at this task, because hyphenation is quite a difficult problem. For example, the word ‘record’ is supposed to be broken as ‘rec-ord’ when it is a noun, but ‘re-cord’ when it is a verb. The word ‘hyphenation’ itself is somewhat exceptional; if ‘hy-phen-a-tion’ is compared to similar words like ‘con-cat-e-na-tion’, it’s not immediately clear why the ‘n’ should be attached to the ‘e’ in one case but not the other. Examples like ‘dem-on-stra-tion’ vs. ‘de-mon-stra-tive’ show that the alteration of two letters can actually affect hyphens that are nine positions away. A good solution to the problem was discovered by Frank M. Liang during 1980–1982, and TEX incorporates the new method. Liang’s algorithm works quickly and finds nearly all of the legitimate places to insert hyphens; yet it makes few if any errors, and it takes up comparatively little space in the computer. Moreover, the method is flexible enough to be adapted to any language, and it can also be used to hyphenate words in two languages simultaneously. Liang’s Ph.D. thesis, published by Stanford University’s Department of Computer Science in 1983, explains how to take a dictionary of hyphenated words and teach it to TEX; i.e., it explains how to compute tables by which TEX will be able to reconstruct most of the hyphens in the given dictionary, without error. TEX hyphenates a given word by first looking for it in an “exception dictionary,” which specifies the hyphen positions for words that deserve special treatment. If the word isn’t there, TEX looks for patterns in the word, and this is the key idea underlying Liang’s method. Here’s how it works, using the word ‘hyphenation’ as an example, when TEX is operating with the English-oriented patterns of plain TEX format: The given word is first extended by special markers at either end; in this case we obtain .hyphenation. if ‘.’ denotes the special marker. The extended word has subwords . h y p h e n a t i o n . of length one, .h hy yp ph he en na at ti io on n. of length two, .hy hyp yph phe hen ena nat ati tio ion on. of length three, and so on. Each subword of length k is a pattern that defines k + 1 small integer values relating to the desirability of hyphens in the positions 449 450 Appendix H: Hyphenation between and adjacent to its letters. We can show these values by attaching them as subscripts; for example, ‘ 0 h 0 e 2 n 0 ’ means that the values corresponding to the subword ‘hen’ are 0, 0, 2, and 0, where the 2 relates to hyphens between the ‘e’ and the ‘n’. The interletter values are entirely zero for all subwords except those that match an entry in TEX’s current “pattern dictionary”; and in this case, only the subwords 0 h 0 y3 p 0 h 0 0 h 0 e 2 n 0 0 h 0 e 0 n 0 a 4 0h0e0n5a0t0 1n0a0 0n2a0t0 1t0i0o0 2i0o0 0o2n0 occur as special patterns. TEX now computes the maximum interletter value that occurs at each subword touching each interletter position. For example, between ‘e’ and ‘n’ there are four relevant values in this case (2 from 0 h 0 e 2 n 0 , 0 from 0 h 0 e 0 n 0 a 4 , 0 from 0 h 0 e 0 n 5 a 0 t 0 , and 1 from 1 n 0 a 0 ); the maximum of these is 2. The result of all the maximizations is . 0 h 0 y3 p 0 h 0 e 2 n 5 a 4 t 2 i 0 o 2 n 0 . Now comes the final step: A hyphen is considered to be acceptable between two letters if the associated interletter value is odd. Thus, two potential breakpoints have been found: ‘hy-phen-ation’. Similarly, the word ‘concatenation’ contains the patterns 0o2n0 0o0n1c0 1c0a0 1n0a0 0n2a0t0 1t0i0o0 2i0o0 0o2n0 and this yields ‘ 0 c 0 o 2 n 1 c 0 a 0 t 0 e 1 n 2 a 1 t 2 i 0 o 2 n 0 ’, i.e., ‘con-cate-na-tion’. Let’s try a 34-letter word: ‘supercalifragilisticexpialidocious’ matches the plain TEX patterns u 1 pe r 1 c 1 ca al 1 i ag 1 i gil 4 il 1 i il 4 ist is 1 ti st 2 i s 1 tic 1 exp x 3 p pi 3 a 2 i 1 a i 2 al 2 id 1 do 1 ci 2 io 2 us (where subscripts that aren’t shown are zero), and this yields .0s0u1p0e0r1c0a0l1i0f0r0a0g1i0l4i0s1t2i0c1e0x3p2i3a0l2i1d0o1c2i0o2u0s0. The resulting hyphens ‘su-per-cal-ifrag-ilis-tic-ex-pi-ali-do-cious’ agree with Random House’s Unabridged Dictionary (which also shows a few more: ‘su-per-cal-i-frag-i-lis-tic-ex-pi-al-i-do-cious’). Plain TEX loads exactly 4447 patterns into TEX’s memory, beginning with ‘ 0 . 0 a 0 c 0 h 4 ’ and ending with ‘ 4 z 1 z 2 ’ and ‘ 0 z 4 z 0 y0 ’. The interletter values in these patterns are all between 0 and 5; a large odd value like the 5 in ‘ 0 h 5 e 0 l 0 o 0 ’ forces desirable hyphen points in words like ‘bach-e-lor’ and ‘ech-e-lon’, while a large even value like the 4 in ‘ 0 h 0 a 0 c 0 h 4 ’ suppresses undesirable hyphens in words like ‘tooth-aches’. Liang derived these patterns by preparing a special version of Webster’s Pocket Dictionary (Merriam, 1966) that contains about 50,000 words including derived forms. Then he checked a preliminary set of patterns obtained from this data against an up-to-date hyphenation dictionary of about 115,000 words obtained from a publisher; errors found in this run led to the Appendix H: Hyphenation addition of about 1000 words like camp-fire, Af-ghan-i-stan, and bio-rhythm to the pocket dictionary list. He weighted a few thousand common words more heavily so that they would be more likely to be hyphenated; as a result, the patterns of plain TEX guarantee complete hyphenation of the 700 or so most common words of English, as well as common technical words like al-go-rithm. These patterns find 89.3% of the hyphens in Liang’s dictionary as a whole, and they insert no hyphens that are not present. Patterns derived from the common words of a language tend to work well on uncommon or newly coined words that are not in the original dictionary. For example, Liang’s patterns find a correct subset of the hyphens in the word that all of today’s unabridged dictionaries agree is the longest in English, namely pneu-monoul-tra-mi-cro-scop-ic-sil-i-co-vol-canoco-nio-sis. They even do fairly well on words from other languages that aren’t too distant from English; for example, the pseudo-German utterances of Mark Twain’s Connecticut Yankee come out with only six or seven bad hyphens: Con-stanti-nop-o-li-tanis-cherdudel-sack-spfeifen-mach-ers-ge-sellschafft; Ni-hilis-ten-dy-na-mittheaterkaestchensspren-gungsat-ten-taetsver-suchun-gen; Transvaal-trup-pen-tropen-trans-porttram-pelth-iertreib-er-trau-ungsthrae-nen-tra-goedie; Mekka-musel-man-nen-massen-menchenmo-er-der-mohren-mut-ter-mar-mor-mon-u-menten-machen. But when plain TEX is tried on the name of a famous Welsh city, Llan-fair-p-wll-gwyn-gyll-gogerychwyrn-drob-wl-l-l-lan-tysil-i-o-gogogoch, linguistic differences became quite evident, since the correct hyphens are Llan-fair-pwll-gwyn-gyll-go-ger-ychwyrn-dro-bwll-llan-ty-sil-i-o-go-go-goch. Appropriate pattern values for other languages can be derived by applying Liang’s method to suitable dictionaries of hyphen points. Dictionaries of English do not always agree on where syllable boundaries occur. For example, the American Heritage Dictionary says ‘in-de-pend-ent’ while Webster’s says ‘in-de-pen-dent’. Plain TEX generally follows Webster except in a few cases where other authorities seem preferable. [From here to the end of this appendix, TEX will be typesetting with \hyphenpenalty=-1000 \pretolerance=-1 \tolerance=1000 \doublehyphendemerits=-100000 \finalhyphendemerits=-100000 so that hyphens will be inserted much more often than usual.] 451 452 Appendix H: Hyphenation The fact that plain TEX finds only 90% of the permissible hyphen points in a large dictionary is, of course, no cause for alarm. When word frequency is taken into account, the probability rises to well over 95%. Since TEX’s line-breaking algorithm often succeeds in finding a way to break a paragraph without needing hyphens at all, and since there’s a good chance of finding a different hyphen point near to one that is missed by TEX’s patterns, it is clear that manual intervention to correct or insert hyphenations in TEX output is rarely needed, and that such refinements take a negligible amount of time compared to the normal work of keyboarding and proofreading. But you can always insert words into TEX’s exception dictionary, if you find that the patterns aren’t quite right for your application. For example, this book was typeset with three exceptional words added: The format in Appendix E includes the command \hyphenation{man-u-script man-u-scripts ap-pen-dix} which tells TEX how to hyphenate the words ‘manuscript’, ‘manuscripts’, and ‘appendix’. Notice that both singular and plural forms of ‘manuscript’ were entered, since the exception dictionary affects hyphenation only when a word agrees completely with an exceptional entry. (Precise rules for the \hyphenation command are discussed below.) If you want to see all of the hyphens that plain TEX will find in some random text, you can say ‘\showhyphens{hrandom texti}’ and the results will appear on your terminal (and in the log file). For example, *\showhyphens{random manuscript manuscripts appendix} Underfull \hbox (badness 10000) detected at line 0 [] \tenrm ran-dom manuscript manuscripts ap-pendix shows the hyphen positions that would have been found in this book without the addition of any \hyphenation exceptions. Somehow the word ‘manuscript’ slips through all of the ordinary patterns; the author added it as an exception for this particular job because he used it 80 times (not counting its appearances in this appendix). The \showhyphens macro creates an hbox that is intentionally underfull, so you should ignore the warning about ‘badness 10000’; this spurious message comes out because TEX displays hyphens in compact form only when it is displaying the contents of anomalous hboxes. (TEX wizards may enjoy studying the way \showhyphens is defined in Appendix B.) Ä If you want to add one or more words to the exception dictionary, just say \hyphenation{hwordsi} where hwordsi consists of one or more hwordi items separated by spaces. A hwordi must consist entirely of letters and hyphens; more precisely, a “hyphen” in this context is the token - 12 . A “letter” in this context is a character token whose category code is 11 or 12, or a control sequence defined by \chardef, or \charh8-bit numberi, such that the corresponding character has a nonzero \lccode. TEX uses the \lccode to convert each let- Appendix H: Hyphenation ter to “lowercase” form; a word-to-be-hyphenated will match an entry in the exception dictionary if and only if both words have the same lowercase form after conversion to lowercase. Ä TEX will henceforth insert discretionary hyphens in the specified positions, whenever it attempts to hyphenate a word that matches an entry in the exception dictionary, except that hyphens are never inserted after the very first letter or before the last or second-last letter of a word. You must insert your own discretionary hyphens if you want to allow them in such positions. A \hyphenation entry might contain no hyphens at all; then TEX will insert no hyphens in the word. Ä The exception dictionary is global; i.e., exceptions do not disappear at the end of a group. If you specify \hyphenation of the same word more than once, its most recently specified hyphen positions are used. Ä Ä The exception dictionary is dynamic, but the pattern dictionary is static: To change TEX’s current set of hyphenation patterns, you must give an entirely new set, and TEX will spend a little time putting them into a form that makes the hyphenation algorithm efficient. The command format is \patterns{hpatternsi}, where hpatternsi is a sequence of hpatterni items separated by spaces. This command is available only in INITEX, not in production versions of TEX, since the process of pattern compression requires extra memory that can be put to better use in a production system. INITEX massages the patterns and outputs a format file that production versions can load at high speed. Ä Ä A hpatterni in the \patterns list has a more restricted form than a hwordi in the \hyphenation list, since patterns are supposed to be prepared by experts who are paid well for their expertise. Each hpatterni consists of one or more occurrences of hvalueihletteri, followed by hvaluei. Here hvaluei is either a digit (0 12 to 9 12 ) or empty; an empty hvaluei stands for zero. For example, the pattern ‘ 0 a 1 b 0 ’ can be represented as 0a1b0 or a1b0 or 0a1b or simply a1b. A hletteri is a character token of category 11 or 12 whose \lccode is nonzero. If you want to use a digit as a hletteri, you must precede it by a nonempty hvaluei; for example, if for some reason you want the pattern ‘ 1 a 0 1 2 ’ you can obtain it by typing ‘1a012’, assuming that \lccode‘1 is nonzero. Exception: The character ‘.’ is treated as if it were a hletteri of code 0 when it appears in a pattern. Code 0 (which obviously cannot match a nonzero \lccode) is used by TEX to represent the left or right edge of a word when it is being hyphenated. Ä Ä Plain TEX inputs a file called hyphen.tex that sets up the pattern dictionary and the initial exception dictionary. The file has the form \patterns{.ach4 .ad4der .af1t .al3t · · · zte4 4z1z2 z4zy} \hyphenation{as-so-ciate as-so-ciates dec-li-na-tion oblig-a-tory phil-an-thropic present presents project projects reci-procity re-cog-ni-zance ref-or-ma-tion ret-ri-bu-tion ta-ble} The first thirteen exceptions keep TEX from inserting incorrect hyphens; for example, ‘pro-ject’ and ‘pre-sent’ are words like ‘re-cord’, that cannot be hyphenated without knowing the context. The other exception, ‘ta-ble’, is included just to meet the claim that plain TEX fully hyphenates the 700 or so most common words of English. 453 454 Appendix H: Hyphenation Ä Ä But how does TEX decide what sequences of letters are “words” that should be hyphenated? Let’s recall that TEX is working on a horizontal list that contains boxes, glue, rules, ligatures, kerns, discretionaries, marks, whatsits, etc., in addition to simple characters; somehow it has to pick out things to hyphenate when it is unable to find suitable breakpoints without hyphenation. The presence of punctuation marks before and/or after a word should not make a word unrecognizable or unhyphenatable; neither should the presence of ligatures and kerns within a word. On the other hand, it is desirable to do hyphenation quickly, not spending too much time trying to handle unusual situations that might be hyphenatable but hard to recognize mechanically. Ä Ä TEX looks for potentially hyphenatable words by searching ahead from each glue item that is not in a math formula. The search bypasses characters whose \lccode is zero, or ligatures that begin with such characters; it also bypasses whatsits and implicit kern items, i.e., kerns that were inserted by TEX itself because of information stored with the font. If the search finds a character with nonzero \lccode, or if it finds a ligature that begins with such a character, that character is called the starting letter. But if any other type of item occurs before a suitable starting letter is found, hyphenation is abandoned (until after the next glue item). Thus, a box or rule or mark, or a kern that was explicitly inserted by \kern or \/, must not intervene between glue and a hyphenatable word. If the starting letter is not lowercase (i.e., if it doesn’t equal its own \lccode), hyphenation is abandoned unless \uchyph is positive. Ä Ä If a suitable starting letter is found, let it be in font f . Hyphenation is aban- doned unless the \hyphenchar of f is between 0 and 255, and unless a character of that number exists in the font. If this test is passed, TEX continues to scan forward until coming to something that’s not one of the following three “admissible items”: (1) a character in font f whose \lccode is nonzero; (2) a ligature formed entirely from characters of type (1); (3) an implicit kern. The first inadmissible item terminates this part of the process; the trial word consists of all the letters found in admissible items. Notice that all of these letters are in font f . Ä Ä If a trial word l1 . . . ln has been found by this process, hyphenation will still be abandoned unless n ≥ λ + ρ, where λ = max(1, \lefthyphenmin) and ρ = max(1, \righthyphenmin). (Plain TEX takes λ = 2 and ρ = 3.) Furthermore, the items immediately following the trial word must consist of zero or more characters, ligatures, and implicit kerns, followed immediately by either glue or an explicit kern or a penalty item or a whatsit or an item of vertical mode material from \mark, \insert, or \vadjust. Thus, a box or rule or math formula or discretionary following too closely upon the trial word will inhibit hyphenation. (Since TEX inserts empty discretionaries after explicit hyphens, these rules imply that already-hyphenated compound words will not be further hyphenated by the algorithm.) Ä Ä Trial words l1 . . . ln that pass all these tests are submitted to the hy- phenation algorithm described earlier. Hyphens are not inserted before lλ or after ln+1−ρ . If other hyphenation points are found, one or more discretionary items are inserted in the word; ligatures and implicit kerns are reconstituted at the same time. Appendix H: Hyphenation Ä Ä Since ligatures and kerns are treated in quite a general manner, it’s possible that one hyphenation point might preclude another because the ligatures that occur with hyphenation might overlap the ligatures that occur without hyphenation. This anomaly probably won’t occur in real-life situations; therefore TEX’s interesting approach to the problem will not be discussed here. Ä Ä According to the rules above, there’s an important distinction between im- plicit and explicit kerns, because TEX recomputes implicit kerns when it finds at least one hyphen point in a word. You can see the difference between these two types of kerns when TEX displays lists of items in its internal format, if you look closely: ‘\kern2.0’ denotes an implicit kern of 2 pt, and ‘\kern 2.0’ denotes an explicit kern of the same magnitude. The italic correction command \/ inserts an explicit kern. Ä Ä The control sequence \- is equivalent to \discretionary{\char h}{}{}, where h is the \hyphenchar of the current font, provided that h lies between 0 and 255. Otherwise \- is equivalent to \discretionary{}{}{}. Ä Ä So far we have assumed that TEX knows only one style of hyphenation at a time; but in fact TEX can remember up to 256 distinct sets of rules, if you have enough memory in your computer. An integer parameter called \language selects the rules actually used; every \hyphenation and \patterns specification appends new rules to those previously given for the current value of \language. (If \language is negative or greater than 255, TEX acts as if \language = 0.) All \patterns for all languages must be given before a paragraph is typeset, if INITEX is used for typesetting. Ä Ä TEX is able to work with several languages in the same paragraph, be- cause it operates as follows. At the beginning of a paragraph the “current language” is defined to be 0. Whenever a character is added to the current paragraph (i.e., in unrestricted horizontal mode), the current language is compared to \language; if they differ, the current language is reset and a whatsit node specifying the new current language is inserted before the character. Thus, if you say ‘\def\french{\language1...}’ and ‘mix {\french franc/ais} with English’, TEX will put whatsits before the f and the w; hence it will use language 1 rules when hyphenating franc/ais, after which it will revert to language 0. You can insert the whatsit yourself (even in restricted horizontal mode) by saying \setlanguagehnumberi; this changes the current language but it does not change \language. Each whatsit records the current \lefthyphenmin and \righthyphenmin. If all problems of hyphenation have not been solved, at least some progress has been made since that night, when according to legend, an RCA Marketing Manager received a phone call from a disturbed customer. His 301 had just hyphenated “God.” — PAUL E. JUSTUS, There’s More to Typesetting Than Setting Type (1972) The committee skeptically recommended more study for a bill to require warning labels on records with subliminal messages recorded backward. — THE PENINSULA TIMES TRIBUNE (April 28, 1982) 455 (page 456) I Index Appendix I: Index The author has tried to provide as complete an index as possible, so that people will be able to find things that are tucked away in obscure corners of this long book. Therefore the index itself is rather long. A short summary of the simpler aspects of TEX appears at the beginning of Appendix B; a summary of special symbols appears at the end of Appendix F; a summary of other special things appears under ‘tables’ below. Page numbers are underlined in the index when they represent the definition or the main source of information about whatever is being indexed. (Underlined entries are the most definitive, but not necessarily the easiest for a beginner to understand.) A page number is given in italics (e.g., ‘123 ’) when that page contains an instructive example of how the concept in question might be used. Sometimes both underlining and italics are appropriate. When an index entry refers to a page containing a relevant exercise, the answer to that exercise (in Appendix A) might divulge further information; an answer page is not indexed here unless it refers to a topic that isn’t included in the statement of the relevant exercise. Control sequence names that are preceded by an asterisk (*) in this index are primitives of TEX; i.e., they are built in. It may be dangerous to redefine them. Ã (visible space), 3, 420, 429; see also hspacei, spaces. *\Ã (control space), 8, 10, 19, 73, 74, 86–87, 154, 163, 167, 283, 285, 290, 323, 351, 381. # (hash mark), 38, 51, 113, 200–202, 203, 204–205, 228, 235, 236–240. \# ( # ), 38, 51, 356. ##, 203–205, 228, 359–362, 378–379. ###, 88. #{, 204, 401. (dollar sign), 4, 38, 51, 54, 86–88, 92, 127, 134–135, 185–186, 269, 283, 287, 293. \ ( ), 38, 51, 202, 309, 356., 86–89, 185, 186–196, 232, 287, 293, 375–376, 421. % (percent sign), 26, 38, 39, 43, 48, 51, 113, 124, 249, 337, 340, 343. \% ( % ), 38, 43–44, 51, 356. %%, 112–113. & (ampersand), 38, 51, 175–177, 190–196, 231–248, 282, 385–386. for preloaded formats, 25, 26, 344. \& ( & ), 38, 51, 53, 356. &&, 241–242, 361, 412. ’ (apostrophe or right quote), 3–5, 51, 130, 155, 201, 305, 324, 357, 394–395; see also octal. \’ (acute accent), 7–9, 52–53, 305, 335, 356, 420. ’’ ( ” ), 3–5, 24, 394–395. ‘ (reverse apostrophe or left quote), 3–5, 51, 132, 134, 305, 391, 394–395; see also alphabetic constant. \‘ (grave accent), 8, 52–53, 305, 356. ‘‘ ( “ ), 3–5, 24, 394–395. " (double quote or ditto mark), 52, 53, 134; see also hexadecimal. \" (dieresis or umlaut accent), 7, 9, 24, 25, 52–53, 55, 356. ( (left parenthesis), 51, 134, 140, 145–150, 345. \(, 409. ) (right parenthesis), 51, 134, 140, 145–150, 345. [ (left bracket), 51, 134, 146–148, 171, 408, 437. [], 28, 79, 302. [1], 23, 119. ] (right bracket), 51, 134, 146–147, 171, 345, 408, 437. { (left brace), 13–14, 19–21, 38, 51, 200–202, 203–204, 205–206, 216, 269, 275–276, 283, 286, 291, 330. \{ ( { ), 134, 146–147, 174–175, 361. {}, 19, 54, 82, 95, 114, 129, 130, 150, 169, 196, 242, 253, 262, 305, 315, 318, 351, 393. } (right brace), 13–14, 19–21, 38, 51, 200–202, 203–204, 205–206, 269, 275–276, 279, 301, 330. \} ( } ), 134, 146–147, 174–175, 361. 457 458 Appendix I: Index + (plus sign), 51, 132, 268. \+ (begin tabbed line), 231–234, 249, 339, 354. - (hyphen or minus), 4, 51, 93, 95, 127, 132, 268. *\- (discretionary hyphen), 95, 283, 287, 292, 455. --, ---, see en-dash, em-dash. ±, see \pm. ∓, see \mp. * (asterisk), 23, 25, 51, 99, 113, 116, 132–133, 154, 326. \* (discretionary ×), 173, 357. **, 23, 25, 344. / (slash), 51, 132, 146–147, 320, 430. *\/ (italic correction), 14, 64, 287, 292, 306, 382, 455. | (vertical line), 52, 53, 132, 146–147, 171, 174, 438. \| ( k ), 146–147, 171, 361, 435, 438. \ (backslash), 7, 38, 39, 40, 51, 146–147, 343, 436. \\, 38, 378, 418. < (less than sign), 52, 53, 133, 150, 154, 209. _ (greater than sign), 52, 53, 133, 150, 209. \> (medium space), 167, 171, 357. _ >, 45, 135, 369; see also \ge. hi, see angle brackets. , (comma), 51, 72–73, 134, 161–162, 172–174, 394–395, 430. \, (thin space), 5, 167–173, 305, 357, 409–410. . (period), 51, 72–73, 133–134, 149, 161, 345, 394–395, 430. space after, 73–75 ; 76. \. (dot accent), 52, 356. . . . , see \ldots, ellipses. ·. · · , see \cdots, ellipses. .. , see \vdots, ellipses. ; (semicolon), 51, 134, 161. \; (thick space), 167, 171, 357. : (colon), 51, 133–134, 155, 161, 174, 438. :=, 133. ? (question mark), 31, 51, 73, 161. ¿ (open question), 51. ! (exclamation point), 51, 72, 73, 75, 169. ¡ (open exclamation), 51. \! (negative thin space), 167, 169, 357. _ (underscore), 38, 51, 128–130, 134. \_ ( ), 38, 165, 356. ^ (hat), 38, 51, 128–130, 134, 369, 423. \^ (circumflex accent), 52–53, 356. ^^, 45, 47, 48, 368, 370, 423. ^^M (ASCII hreturni), 45, 249, 331, 343, 345, 348, 352, 380, 390–391, 421, 423. \^^M, 8, 305, 351. ~ (tilde), 38, 51, 343, 353; see also ties. \~ (tilde accent), 52, 356, 387. ↑↓, 135, 343, 368, 429; see also \uparrow, \downarrow. @ (at sign), 51, 98–99, 132, 134, 344, 364, 408, 414. @@, 98–99. \@ne, 345. \aa ( ˚ a ), 356. \AA ( ˚ A ), 356. abbreviations, 73–74, 340 ; see also macros. *\above (general fraction), 143, 152, 292, 444–445. *\abovedisplayshortskip, 189, 274, 348, 415. *\abovedisplayskip, 189, 190, 194, 274, 291, 348, 415. *\abovewithdelims, 152, 292, 444–445. absolute value, 146, 149, 171, 175. Acc atom, 158, 289, 443. *\accent (general accent), 9, 54, 86, 283, 286. accents (´  ¨ etc.), 7, 52–53, 339, 356, 357, 427–429. as ligatures, 46, 54. in math, 135–137, 141, 164–165, 359, 435, 443. on top of accents, 136. table, 52, 135, 339. \active (category 13), 241, 343, 395, 421. active character, 37, 40, 209, 241, 307, 377, 380–381, 394–395. active math character, 155, 289. active spaces, 381, 394, 421. \acute (math accent: x ´), 135, 359. acute accent (´), see \’, \acute. \address, 403–404, 407. *\adjdemerits, 98, 273, 314, 348. *\advance, 21, 118–119, 218, 256, 276, 355. \advancepageno, 256, 257, 362, 416. \ae ( æ ), vii, 17, 45–46, 52–53, 239, 356. \AE ( Æ ), 52–53, 356. *\afterassignment, 215, 279, 352, 364, 376, 401. *\aftergroup, 215, 279, 363, 374, 377, 379. ‘ain, see reverse apostrophe. Appendix I: Index al-Khwˆ arizmˆı, abu Ja‘far Muh.ammad ibn Mˆ usˆ a, 53. \aleph ( ℵ ), 9, 358, 435. Alice, 4, 387, 394. alignment displays, 190, 193, 291. halignment materiali, 282, 285. alignments, 231–249, 282, 302–303, 385–386, 392; see also tabbing. Alka-Seltzer, 404–405. all caps, see \uppercase. Allen, Todd Andrew, 377. allocation, 121–122, 346, 347. \allocationnumber, 346. \allowbreak, 174, 353, 396. \allowhyphens, 394, 395. \alpha ( α ), 127, 201, 358, 434. \Alpha, 434. alphabetic constants, 44–46, 215, 269, 270, 309, 367, 385. alternatives, see \cases. \amalg ( q ), 358, 436. American Mathematical Society, ii, vii. ampersand, 25, 38, 51, 175–177, 190–196, 231–248, 282, 344, 385–386, 428. AMS-TEX, 164, 420, 434. anatomy of TEX, 38–39, 46, 85, 267, 349, 373, 379, 385, 386, 456. \angle ( 6 ), 358, 435. angle brackets ( h i ), 59, 146–147, 150, 268, 420, 437; see also \langle, \rangle. angstrom unit, see \AA. \annotations, 403, 404, 407. answers to the exercises, 305–337. Antisthenes of Athens, 239. apostrophe, 3–5, 51, 130, 155, 201, 324; see also octal. \approx ( ≈ ), 128, 436. Arabic, 66. \arccos ( arccos ), 162, 361. Archytas of Taras, 239. \arcsin ( arcsin ), 162, 361. \arctan ( arctan ), 162, 361. Arenski˘ı, Anton Stepanovich, 410. \arg ( arg ), 162, 361. arguments, 33, 200–205, 263, 268, 375–380. Aristippus of Cyrene, 239. Aristophanes, 239. Aristotle, 35. arithmetic, 117–119, see \advance, \multiply, \divide. harithmetici, 276. arrays, 176–178, see matrices. arrows, 146–147, 182, 226, 437. \arrowvert ( | ), 150, 359. \Arrowvert ( k ), 150, 359. The Art of Computer Programming, 259–260. as is, see \obeylines, \obeyspaces, verbatim. ASCII, 3, 43–45, 49, 214, 343, 367, 371. hassignmenti, 275. assignments, 275–278, 373. \ast ( ∗ ), 436. asterisk, 23, 25, 51, 99, 113, 116, 132–133, 154, 326. \asymp ( ³ ), 436. at, 16–17, 60, 213, 277, 408, 414, 433. hat clausei, 277. at sign, 51, 98–99, 132, 134, 344, 364, 408, 414. AT&T, 247. atoms, 157–159, 170–171, 289–290, 441–447. table of atomic types, 158. *\atop, 143, 145, 152, 178, 292, 444. *\atopwithdelims, 152, 292, 324, 360, 444. author, typesetting by, 182, 412–413. auxiliary spaces, see ties. axis line, 150–152, 179, 443–447. \b (bar-under accent), 52, 356. Bach, Johann Sebastian, 408. Bach, P. D. Q., 410–411, 481. backslash, 7, 38, 39, 40, 51, 146–147, 343, 436. \backslash ( \ ), 38, 146–147, 359, 435, 436. backspacing, 66, 82–83, 222, 394–395, 418. Backus, John Warner, 268. Bacon, Francis, viscount St. Albans, 41. Bacon, Leonard, 1. bad breaks, avoiding, 27–30, 91–94, 173–174, 197. badness, 28–30, 97–99, 111–113, 302. *\badness, 214, 229, 271. hbalanced texti, 275, 276, 385. balancing columns, 386–388, 396–397, 417. \bar (math accent: x ¯), 135, 136. bar accent (¯), see \=, \bar. bar-under accent ( ), see \b. ¯ Barrett, Percy Reginald, 197. Barrough, Philip, 229. baseline, 15, 63, 77, 80–81, 150. *\baselineskip (normal vertical distance between baselines), 78–79, 80, 104, 194, 253, 256, 274, 281, 342, 349, 351–352, 409, 414–415. *\batchmode, 32, 277, 299, 336. Batey, Charles, 197. 459 460 Appendix I: Index beauty, 1. Beck, Simone, 233, 236. Beethoven, Ludwig van, 408, 410–411. Beeton, Barbara Ann Neuhaus Friend Smith, 483. \beginchapter, 418. *\begingroup, 21, 249, 262, 279, 380, 407, 419. \beginsection, 340–341, 355. *\belowdisplayshortskip, 189, 274, 348, 415. *\belowdisplayskip, 189, 190, 194, 274, 291, 348, 415. Bemer, Robert William, see TEX, ASCII. bent bars, see angle brackets. Bertholle, Louisette, 233, 236. \beta ( β ), 127, 434. \Beta, 434. \bf (use boldface type), 13–14, 164–165, 328, 351, 409, 414–415. \bffam, 351, 414–415. \bgroup (implicit {), 269, 351, 363, 382, 385, 407, 421. Bibby, Duane Robert, i. Biblical references, 303, 311. bibliographies, 4, 74, 93, 340–341. \big (largish delimiter), 147, 171, 320, 359, 360, 414–415. \Big (between \big and \bigg), 147, 175, 359, 360. big-O notation, 132, 161–162, 169. big point, 57, see bp. \bigbreak, 111, 116, 353, 363. \bigcap (large ∩), 147, 435. \bigcirc ( ° ), 436. \bigcup (large ∪), 147, 435. \bigg (large delimiter), 147, 175, 196, 327, 359, 360. \Bigg (larger than \bigg), 147, 175, 359, 360. \bigggl, \bigggr, 324. \biggl (\bigg left delimiter), 147, 149, 359, 437. \Biggl (\Bigg left delimiter), 147, 149, 359, 437. \biggm (\bigg middle delimiter), 147, 359. \Biggm (\Bigg middle delimiter), 147, 359. \biggr (\bigg right delimiter), 147, 149, 359. \Biggr (\Bigg right delimiter), 147, 149, 359. \bigl (\big left delimiter), 146–147, 149–150, 155, 171, 175, 359, 437. \Bigl (\Big left delimiter), 147, 359, 437. \bigm (\big middle delimiter), 147, 359, 171, 175. \Bigm (\Big middle delimiter), 147, 359. \bigodot (large ¯), 435. \bigoplus (large ⊕), 435. \bigotimes (large ⊗), 435. \bigr (\big right delimiter), 146–147, 149–150, 171, 175, 359. \Bigr (\Big right delimiter), 147, 359. \bigskip, 70, 109, 111, 115–116, 352, 355, 407, 410–412. \bigskipamount, 123, 349, 352–353, 363. \bigsqcup (large t), 435. \bigtriangledown ( 5 ), 436. \bigtriangleup ( 4 ), 436. \bigtype, 408–409, 411. \biguplus (large ]), 358, 435. \bigvee (large ∨), 435. \bigwedge (large ∧), 435. Bill, 387, 394. Bin atom, 158, 170–171, 289, 442–444, 446. binary operations, 132–133, 154–155, 164, 196, 358, 435, 436; see also Bin atom. binary search, 387–388. binomial coefficient, 143, see \choose. *\binoppenalty, 101, 174, 272, 322, 348, 446. black box, 64, 221, 222. blackboard bold (e.g., IR), 164, 434. blank line in input file, 24, 37, 47, 340–341, 381. blank space, see spaces. Blase B¨ ohning, Maria Dorothea, 248. block structure, see grouping. block style, 405–407. \bmit (boldface math italic), 156. \bmod ( mod ), 164, 322, 361. \body, 403–404, 407. Boehm, Peter James, 159. B¨ ohning, Jobst Heinrich, 248. B¨ ohning, Martin John Henry, 248. Bohning Knuth, Louise Marie, 248. boldface, 13, 156, 164–165, 386. book design, 412. book preparation, 303, 425. \bordermatrix, 177, 361. \bot ( ⊥ ), 435. *\botmark, 213, 258, 259–260, 262–263, 280. boundary item, 157, 442, 446. Bourbaki, Nicolas, 106. \bowtie ( ./ ), 358, 436. hboxi, 120, 222, 278, 282, 285, 290. Appendix I: Index *\box (use box register), 120–122, 151, 222, 278, 346, 354, 386, 387. \box255, 125, 253–258. hbox dimensioni, 271, 277. box displays, 66, 75, 79, 158–159, 302, 455. box memory, 300, 394. hbox or rulei, 281. hbox size assignmenti, 277. hbox specificationi, 222, 278. boxed control sequence names, 38. boxed material, 223, 420. boxes, 63–67, 77–83, 221–229. *\boxmaxdepth, 81, 113, 249, 255, 274, 348. bp (big point), 57, 270. © ª ), 360. \brace (notation like n k \braceld, \bracelu, \bracerd, \braceru (pieces of horizontal braces), 357. braces, 51, 216, 269, 275–276, 279, 283, 286, 289–291, 330, 345, 385–386. for arguments to macros, 20, 200–202, 203, 204, 205–206, 385–386. for grouping, 13–14, 19–21, 232, 248, 253. horizontal, 176, 225–226, 339. implicit, 269, see \bgroup, \egroup. in math formulas, 145–147, 174–176.   ), 150, \bracevert (  ¤ £ 359. ), 360. \brack (notation like n k brackets, 51, 134, 146–148, 171, 408, 437. \break (force line or page break), 94, 97, 106, 114, 193, 353. breakpoints, 96, 97–100, 110, 111–114, 394. avoiding bad, 27–30, 91–94, 109–111, 173–174, 197. discretionary, 95–96, 173, 287, 292, 357. forcing good, 94, 105, 109–111, 114. in displays, 195–197. in formulas, 173–174, 446–447. \breve (math accent: x ˘), 135. breve accent (˘), see \u, \breve. British pound sign, 54. brochures, 251. *\brokenpenalty, 104, 105, 272, 348. Brooks, Frederick Phillips, Jr., 365. Brown, Peter John, 425. \buildrel, 361, 437. built-up (extensible) characters, 442. built-up fractions, see \over. \bull ( ), 420. Bull, John, 239. \bullet ( • ), 133, 154, 355, 436. bulleted lists, 102, 105. business correspondence, 200, 403–408. by, 118, 276. \bye, 87–88, 340, 357. Byron, George Gordon No¨ el Byron, baron, vii. \c (cedilla accent), 24–25, 52, 356. \cal (calligraphic caps), 164, 351, 431, 434. calculus, 168–169, 180–181. camera alignment, 416–417. \cap ( ∩ ), 133, 436. capacity of TEX, 100, 300–301, 383. caps and small caps, 203. captions, 115. caret, 369. caron, see h´ aˇ cek. carriage return, 231, see hreturni, \cr. \cases ( { ··· ), 175, 362. ··· Caswell, Herbert Ernest, 413. *\catcode, 39, 134, 214, 271, 305, 343, 380–382, 384, 390–391, 421, 424. category codes, 37–40, 47, 48, 203–205, 209–210, 214, 381. table, 37. cc (cicero), 57, 270. \cdot ( · ), 133, 172, 319, 436. \cdotp, 358, 359, 438. \cdots ( · · · ), 172, 176, 180–181, 359, 438. cedilla accent (¸), 25, 52, 54, see \c. ceiling brackets ( d e ), 146–147, see \lceil, \rceil. centering, 71, 233, 236. \centering, 347, 348, 362. \centerline (make a centered line), 20, 24, 33, 71, 85, 101, 117, 232, 311, 340, 353. \cents ( c/ ), 140, 319. Ces aro, Ernesto, 53. Cha˘ıkovski˘ı, P¨ etr Il’ich, 410–411. *\char, 43–46, 76, 86, 155, 283, 286, 289, 340, 427, 452. hcharacteri, 289. character codes, 43–46, 367–370; see also category codes. hcharacter tokeni, 270. *\chardef, 44, 121, 155, 210, 214, 215, 272, 277, 336, 343, 345, 452. hchardef tokeni, 271, 272. Charles XII of Sweden, 92. Chaundy, Theodore William, 197. \check (math accent: x ˇ), 135. check accent (ˇ), see \v, \check. chemical typesetting, 179. Cherry, Lorinda Landgraf, 159. \chi ( χ ), 1, 434. Chicago, University of, Press, 125, 293, 418, 439. 461 462 Appendix I: Index Child, Julia, 233, 236. Children’s Television Workshop, ii. choice, four-way, 157, 292, ¡ ¢ 442. ), 139, 143, \choose (notation like n k 152, 178, 360. Christie Mallowan, Dame Agatha Mary Clarissa (Miller), 249. cicero, see cc. \circ ( ◦ ), 133, 323, 436. circles, see \circ, \bigcirc. circular quotation, 101. circumflex, 369, see hat. circumflex accent (ˆ), 52, 356, see \^. classes of math characters, table, 154. *\cleaders, 224, 225–226, 357, 374. \cleartabs, 234, 354. Close atom, 158, 170–171, 289, 443–444, 446. *\closein, 217, 280. *\closeout, 226–228, 254, 280, 422. \closing, 403–404, 407. closings, 134, 147, 154–155, 359, 437; see also Close atom. club lines, 104, 272, 398. *\clubpenalty, 104, 113, 272, 317, 348, 419. \clubsuit ( ♣ ), 435. cm (centimeter), 24, 57, 270. cmbx fonts, 60, 350, 413, 428, 433. cmex fonts, 157, 225, 350, 432–433. cmmi fonts, 350–351, 413–414, 430, 433. cmr fonts, 16–17, 60, 63–64, 76, 350, 413, 427, 433. cmsl fonts, 63–64, 350, 413, 428, 433. cmsy fonts, 157, 350–351, 413–414, 431. cmti fonts, 350, 413, 428, 433. cmtt fonts, 60, 350, 413–414, 429, 433. hcode assignmenti, 277. hcodenamei, 271. codes for characters, 43–46, 367–370. Coelho, Manuel Rodrigues, 239. coerce hdimeni to hnumberi, 270. coerce hgluei to hdimeni, 270. coerce hnumberi to hdimeni, 336. hcoerced dimeni, 270. hcoerced integeri, 269. hcoerced mudimeni, 270. collective signs, see large operators. colon, 51, 133–134, 155, 161, 174, 438. \colon ( : ), 134, 359, 438. color, 229. column vector, 177. column width, 29, 231, 257, 387, 417. \columns, 231, 354. comma, 51, 72–73, 134, 161–162, 172–174, 394–395, 430. commands, 267–293. comments, 26, 47, 337, 340. communication between macros, 211, 328–329, 375–376, 407–408. commutative diagram, 182. composing stick, 64–65. compound fraction, 143. compound matrix, 181. Computer Modern fonts, 16, 350, 427–438. computer programs, 38, 165, 234. concert programs, 408–412. conditionals, 206–208, 209, 210, 211, 240, 308, 384. \cong ( ∼ = ), 151, 360, 436. constants, 269, 270, 308. continued fractions, 142. hcontrol sequencei, 275, 277. control sequences, 7–11, 46, 199, 457. misspelled, 31–32. control space (\Ã), 8, 10, 19, 73, 74, 86–87, 154, 163, 167, 283, 285, 290, 351, 381. control symbols, 7–8, 46–47. control words, 7–8, 38, 46–47, 204. coordinates, 389. \coprod (large q), 435. *\copy (copy a box), 120, 151, 222, 278, 329, 374, 386, 407. c ), ii, 308, 339, 356. \copyright ( ° Cornet, Peeter, 239. Correa de Arauxo, Francisco, 239. correspondence, 200, 403–408. \cos ( cos ), 162, 361. \cosh ( cosh ), 162, 361. cost of a page break, 111–113, 124. \cot ( cot ), 162, 361. \coth ( coth ), 162, 361. *\count registers, 118–122, 207–208, 271, 276, 346–347, 379. \count0, 119, 207, 252–254, 362. *\countdef, 119, 121, 210, 215, 271, 277, 346–347. hcountdef tokeni, 271. Cowper, William, 35. *\cr (end of aligned row), 175–177, 190–197, 231–238, 245, 248, 275, 282, 351, 352, 385–386, 412, 418, 421. avoiding, 249. cramped styles, 140–141, 445. *\crcr (force \cr), 249, 275, 282, 361–362, 385, 412, 421. Crocker, Betty, 425. Appendix I: Index cross, see \dag ( † ), \times ( × ). crotchets, see brackets. \csc ( csc ), 162, 361. *\csname, 40–41, 213, 348, 375. \csname\endcsname, 46, 308. cube root, 130–131. Cummings, Edward Estlin, 49. \cup ( ∪ ), 133, 436. curly braces, see braces. current font, 13, 20, 154, 163, 213–214. current page, 112, 122–125, 278, 280. cyclic preambles, 241, 242, 246, 361, 412. Cyrillic characters, 370. \d (dot-under accent), 52–53, 356. \dag ( † ), 53, 117, 356, 438–439. \dagger († as binary operator), 436, 439. Dale, Robert William, 283. \danger, 419. dangerous bend, v–vi, 5, 15, 44–45, 70, 419. Danish characters, 45–46, 52–53, 370. \dash, 30. dashes, 4, 26, 30, 51, 93, 95. \dashv ( a ), 436. date, today’s, 406. *\day, 273, 349, 406. dd (didot point), 57, 270, 272. \ddag ( ‡ ), 117, 356, 438–439. \ddagger (‡ as binary operator), 436, 439. \ddot (math accent: x ¨), 135, 359. . \ddots ( . . ), 177, 359. \ddt (debugging aid), 248. De Vinne, Theodore Low, 107. *\deadcycles, 214, 255, 264, 271, 283, 401. debugging, 205, 248, 298–303, 347. decent lines, 97, 99. hdecimal constanti, 270. decimal points, 57, 134, 240. hdefi, 275. *\def, 44, 136, 199–208, 215, 275–276. default output routine, 253–255. default rule thickness, 443–447. default values of parameters, 348–349. *\defaulthyphenchar, 273, 348. *\defaultskewchar, 273, 348. defining a control sequence, 199–208. hdefinitioni, 275. hdefinition texti, 275. \deg ( deg ), 162, 361. degrees ( ◦ ), 180. *\delcode, 156, 214, 271, 290, 345. hdeletei (ASCII code 127), 37, 39, 343, 369. deleting tokens, 32, 215, 295–297. hdelimi, 289–290. delimited arguments and parameters, 203–205, 249, 263, 375–377, 407. *\delimiter, 156, 289–290, 359. *\delimiterfactor, 152, 273, 348, 446. delimiters, 145–150, 156–157, 171, 290, 437, 442. *\delimitershortfall, 152, 274, 348, 446. \delta ( δ ), 127, 434. \Delta ( ∆ ), 169, 186, 434. demerits, 94, 97–99, 273, 451. denominator, 141, 152, 179, 444–445. depth, 221, 224, 282, 337. depth of a box, 63–67, 77, 80–82, 225. Derek, Bo, 293. descenders, 63, 113, 319, 323. design size, 16–17, 213. \det ( det ), 162, 361. device-independent output, 23; see also .dvi. Diabelli, Antonio, 408. diagnostic form of lists, 66, 75, 79, 158–159, 302, 455. dialogs with the user, 217–218. \diamond ( ¦ ), 436. diamond leaders, viii. \diamondsuit ( ♦ ), 435. D´ıaz de la Pe˜ na, Maximiliano Antonio Tem´ıstocles, 384. Dick and Jane, 72–74, 76. Dictionaries, 259, 449–453. Didot, Fran¸cois Ambroise, 57. didot point, 57, see dd. dieresis (¨), 52, 53, 356, see \". diesis ( ‡ ), see \ddag. Dieter, Ulrich Otto, 14. hdigiti, 269. hdigit stringi, 57. digits, 51, 132, 435, 453. width of, 60, 241, 427. \dim ( dim ), 162, 361. hdimeni, 59, 61, 71, 118, 270, 271. hdimen parameteri, 271, 274, 276. *\dimen registers, 118–122, 271, 276, 346–347, 349, 360, 363, 395. hdimen variablei, 276. *\dimendef, 119, 215, 277, 346–347. hdimendef tokeni, 271. dimensions, 57–61. as arguments, 204, 362. Dionysius I of Syracuse, 239. diphthongs, see \ae, \oe. discardable items, 95, 110–112, 124, 393. *\discretionary, 95–96, 283, 286, 287, 292. 463 464 Appendix I: Index discretionary hyphens, 28, 95–96, 453, 455. discretionary multiplication signs, 173, 357. display math mode, 85–89, 289–293. display style, 140–142, 441–447. *\displayindent, 188, 190, 274, 291, 349. *\displaylimits, 144, 159, 292, 443. \displaylines, 194, 196, 362. displays, 87, 103, 139–145, 166–167, 185–197, 232, 241, 315. at beginning of paragraph, 316. non-centered, 186, 326, 375–376, 420–421. positioning of, 188–190. *\displaystyle, 141–142, 292, 362. *\displaywidowpenalty, 104, 272, 348. *\displaywidth, 188, 190, 274, 349. Disraeli [Beaconsfield], Benjamin, earl, 219. ditto mark, 53, 441. \div ( ÷ ), 436. *\divide, 118–119, 218–219, 276, 391, 397, 398, 417. \do, 344, 380, 423. dollar sign, 4, 38, 51, 54, 86–88, 92, 127, 134–135, 185–186, 283, 287, 293. Donnelley, Richard Robert, vii. \dospecials, 344, 380, 422–423. \dosupereject, 256, 364. \dot (math accent: x), ˙ 135. dot accent (˙), see \., \dot. dot-under accent ( . ), see \d. . \doteq ( = ), 361, 436. \dotfill (. . . . . . . . .), 244, 334, 335, 340–341, 357. dotless letters, 52–53, 136, 435. \dots ( . . . ), 173, 356; see also ellipses. double-column format, 257, 386–388, 417. double dagger, see \ddag, \ddagger. double dangerous-bend signs, vi, 419. double integrals, 169, 180. double quote mark, 52, 53, 134; see also hexadecimal. *\doublehyphendemerits, 98, 273, 348, 451. \downarrow ( ↓ ), 146–147, 182, 359, 437. \Downarrow ( ⇓ ), 146–147, 359, 437. \downbracefill (z }| {), 225–226, 331, 357. Doyle, Sir Arthur Conan, 401. *\dp, 120, 271, 316, 388–389, 417. dragon curve, 391. Drofnats, Revinu Jitis, 24, 27–28, 73–74, 404–406, 408, 410–412. Dudeney, Henry Ernest, 249, 334. Dull, Brutus Cyclops, 131, 173, 260. \dummy, 401. *\dump, 283, 286, 336, 344. Durant, William James, 239. .dvi, 23, 43, 60, 119, 213, 228, 254, 279, 280, 302, 367, 374. Dvoˇr´ ak, Anton´ın Leopold, 409. dx, 168. EBCDIC, 43. *\edef, 215–216, 275, 328, 348, 373–374. editing, 34, 139, 197. efficiency, 329, 333, 342, 345, 347, 383, 384, 394, 400, 423. \egroup (implicit }), 269, 351, 363, 382, 385, 407, 421. Ehlert, Ernst Fred, 248. Ehlert Bohning, Pauline Anna Marie, 248. \eightpoint, 415, 416. \eject (force page break), 24–25, 105, 109, 189, 353, 418, 419. elbows, see angle brackets. \ell (  ), 132, 435. ellipses ( · · · ), 73, 172–174, 176–177, 180–182, 245. Elphinstone, Mountstuart, 89. *\else, 207, 210, 213. em, 60, 154, 166, 214, 270, 352, 414, 433. em-dash ( — ), 4, 302. em quad, see \quad. embellished letters, see accents. emergency stops, 299–300. *\emergencystretch, 107, 274. Emerson, Ralph Waldo, 41. emphatics, see dot-under. hemptyi, 268. \empty, 263, 351, 378. empty discretionary, 95, 286. empty group, 19, 253, 305. empty line in input file, 24, 37, 47, 340–341, 381. at end of file, 217. empty line in output, 114, 316. empty page, 114. \emptyset ( ∅ ), 128, 435. en-dash ( – ), 4, 187, 252, 314. en quad, 71, see \enspace. *\end, 23, 26, 27, 87, 264, 283, 286, 299, 336, 403. end of an input file, 206, 214, 217. end of file line, see hreturni, \cr. end of file page, see hformfeedi. end of paragraph, 286, see \par. \endchapter, 418–419. *\endcsname, 40–41, 213, 283, 348, 375. endgame, 87, 264, 283. Appendix I: Index \endgraf, 262, 286, 331, 351, 407, 416, 419. *\endgroup, 21, 249, 262, 279, 380, 407, 419. *\endinput, 47, 214. \endinsert, 115–116, 363. \endletter, 403–404, 407. \endline, 351. *\endlinechar, 48, 273, 331, 348, 390–391. \endtemplate, 240. \enskip, 71, 352. \enspace, 202, 352, 419. enumerated cases, in formulas, 175. in separate paragraphs, 102, 340. within a paragraph, 92. enunciations, see \proclaim. epigraphs, 418–419, 425. \epsilon ( ² ), 1, 128, 434. \eqalign, 190–191, 193, 242, 326, 362. \eqalignno, 192–193, 194, 362. heqnoi, 293. *\eqno, 186–187, 189–191, 193, 293, 375–376. hequalsi, 275, 276–277. equals sign, 51, 133, 209, 226, 275, 376. equation numbers, 186–196. \equiv ( ≡ ), 133, 436. Erd˝ os, P´ al (= Paul), 53. *\errhelp, 275, 280, 347. *\errmessage, 216, 279–280, 347, 418. error messages, 30–33, 295–301, 308–309. error recovery, 31–32, 46, 215, 295–303, 309. *\errorcontextlines, 34, 273, 348. *\errorstopmode, 32, 33, 277, 299. es-zet ( ß ), see \ss. hescapei (ASCII code 27), 369. escape character, 7, 37, 421. *\escapechar, 40, 213, 228, 273, 308, 348, 377. \eta ( η ), 434. etc., 302. Eulerian numbers, 152. Evagoras of Salamis, 239. even-numbered pages, 252–253, 416. *\everycr, 275, 362. *\everydisplay, 179, 275, 287, 326. *\everyhbox, 275, 279. *\everyjob, 275. *\everymath, 179, 275, 287, 293, 326. *\everypar, 105, 215, 253, 262, 275, 282, 283, 333, 381, 407, 421. *\everyvbox, 275, 279. ex, 60, 154, 270, 356, 433. exception dictionary, 449, 452–453. exclamation point, 51, 72, 73, 75, 161, 169. \exercise, 10, 422. exercises, vii, 1–303. *\exhyphenpenalty, 96, 262, 272, 348. \exists ( ∃ ), 435. \exp ( exp ), 162, 361. *\expandafter, 40, 213, 215, 260, 308, 330, 348, 374–380. expansion of expandable tokens, 212–216, 238, 267, 373–374. avoiding, 216, 262–263, 377. explicit hyphens, 4, 93, 454. explicit kerns, 40, 280, 306, 454–455. exponents, see superscripts. extensible characters, 442. extension fonts, 157, 351, 432–433, 441, 447. extensions to TEX, 226, 228–229. eyestrain, reducing, 59. faces, 13, 17, 390. hfactori, 270. factorial, 169, 181. *\fam, 154–159, 273, 289–290, 346–347, 351, 358, 414–415. families, 153–159, 289–290, 346, 431, 442. hfamily assignmenti, 277. hfamily memberi, 271, 277. family tree, 248. family 0 (math roman fonts), 153–157, 351. family 1 (math italic fonts), 155–157, 351. family 2 (math symbol fonts), 157, 351, 431, 441, 447. family 3 (math extension fonts), 157, 351, 432–433, 441, 447. Fatal format file error, 299. feasible breakpoints, 99, 315. fences, see openings, closings, delimiters. ffl, see ligatures. *\fi, 207, 210, 213. Fibonacci, Leonardo, of Pisa, 166. fields of atoms, 158–159, 289–291. fil, 72, 118–119, 271, 348, 394. hfil dimeni, 271. hfil uniti, 271. \filbreak, 111, 353. hfile namei, 214, 216, 226, 277, 278. file names, 25, 214, 216–217, 226, 278. file pages, 343. file types, see .dvi, .fmt, .tfm, .tex, log file, terminal. fill, 72, 118–119, 271, 347. fill page with blank space, see \vfill. hfilleri, 276, 278, 280–282, 289. filll, 72, 118, 271, 332. *\finalhyphendemerits, 98, 106, 273, 348, 451. 465 466 Appendix I: Index *\firstmark, 213, 258, 259–260, 280. \fiverm, 153, 350, 351, 414–415. \flat ( [ ), 409, 435. floating insertions, 115–116, 125, 363. *\floatingpenalty, 123–125, 272, 281, 363. floor brackets ( b c ), 146–147, see \lfloor, \rfloor. flush left, 72, 142, 177, 181, 196. flush right, 71–72, 106, 142, 177, 196, 233, 419. .fmt, 39, 344. \fmtname and \fmtversion, 364. \folio (typeset page number), 252–253, 362, 406, 416. hfonti, 213, 214, 271, 277. *\font, 16–17, 60, 210, 213, 214–215, 271, 276. hfont assignmenti, 277. font metric files, 46, 433. hfont rangei, 271. hfontdef tokeni, 271. *\fontdimen, 76, 157, 179, 214, 271, 277, 355–356, 375, 390, 433, 441, 447. *\fontname, 213, 214. fonts, 13–17; see also Computer Modern fonts. \footins, 256, 363, 396–399, 416. \footline, 252, 256, 340–341, 362. \footnote, 82, 116, 251, 256, 340, 363, 382, 416. \footnoterule, 256, 364. footnotes, 105, 116–117, 121, 125, 173, 416–417. short, 395–400. \forall ( ∀ ), 435. forbidden control sequence, 206. Ford, Patrick Kildea, 293. foreign languages, 45–46, 52–54, 370, 387, 449, 451. form letters, 200, 207–209. format file, 25–26, 39, 283, 344. format-independent documents, 194, 203. formats, 11, 39, 200, 403–425, 434. hformfeedi (ASCII code 12), 343, 369. formulas, 127–199. Foss, Sam Walter, 439. fractions, 67, 139–143, 152, 170, 179, 186, 332, 444–445. huge, 196. slashed form, 67, 139–140, 233, 236. Fraktur, 164, 434. Franklin, Benjamin, 65. French, 54, 340–341, 455. \frenchspacing, 74, 340, 351, 381, 401. Frescobaldi, Girolamo, 239. front matter, 413. \frown ( _ ), 436. full stop, see period. \fullhsize, 257. \fullline, 257. funny space, 377. *\futurelet, 207, 215, 262, 277, 363, 375–377, 423. \futurenonspacelet, 376. Galilei, Galileo, 101. galley file, 303, 425. Gamble, James, 38. \gamma ( γ ), 127, 434. \Gamma ( Γ ), 127, 169, 358, 434. \gcd ( gcd ), 162, 192, 361. *\gdef, 206, 215, 275, 352, 407. \ge ( ≥ ), 9, 45, 175, 318, 361, 438. hgeneral texti, 276, 277, 279, 280, 287, 292. generalized fraction, 152, 157, 292, 444–445. generic coding, 194, 203. generic matrix, 177, 245. \geq ( ≥ ), 318, 436. German, 52, 96, 451. German black letters, see Fraktur. \getfactor, 375. \gets ( ← ), 361, 438. \gg ( À ), 436. Gibbon, Edward, 117. *\global, 21, 119, 206, 218, 232, 256, 275, 301, 307, 320, 346. hglobal assignmenti, 179, 277. *\globaldefs, 238, 273, 275. glue, 63, 69–83, 95, 110, 157, 222–225, 302, 412. above and below displays, 189–190, 194. at top of page, 113–114, 124, 256. between aligned columns, 237–239, 247, 392. between lines, see interline glue. between paragraphs, 79, 104–105, 262, 282, 342, 406, 417. between words, 74–76, 356, 393–394, 433. hgluei, 71, 118, 271. \glue, 75, 79, 302. hglue parameteri, 271, 274, 276. glue set, 79, 302. glue set order, 77, 79, 81, 97. glue set ratio, 77, 79, 81, 97. hglue variablei, 276. goal height, 112–114, 123–125. Goethe, Johann Wolfgang von, 183. Appendix I: Index \goodbreak, 111, 116, 353. Grandmaster, 253. \grave (math accent: x ), 135. grave accent (), see \‘, \grave. greater than or equal, see \ge. greater than sign, 52, 53, 133, 150, 209. Greek, 127–128, 137, 156, 319, 358, 430, 434. Green, Walter, 244. grouping, 13–14, 19–21, 119–120, 122, 200, 201, 241, 259, 279, 283, 286, 291, 301, 375, 378, 385, 453. characters for, 39–40, 381–382. implicit, 115, 148, 194, 253, 287, 292, 293. guide words, 259. \H (long Hungarian umlaut), 52, 53, 356, 420. H&J, see hyphenation, line breaking, setting glue. h´ aˇ cek accent (ˇ), see \v, \check. halftones, 228. *\halign, 117, 190, 193, 194, 235–249, 282, 286, 291, 302, 326, 352, 361–362, 386, 392. compared to tabbing, 235. Halmos, Paul Richard, 183. Hamza, see apostrophe. \hang, 355, 419. *\hangafter, 102, 103–104, 273, 348–349, 419. *\hangindent, 102, 262, 274, 349, 407. hanging indentation, 79, 102–103. hanging punctuation, 394–395. Hardy, Godfrey Harold, 321. harpoons, 437. hash mark, 38, 51, 113, 200–202, 203, 204–205, 228, 235, 236–240. Hassler, Hans Leo, 239. hat, 38, 51, 128–130, 134, 369, 423. \hat (math accent: x ˆ), 135–136, 164. hat accent (ˆ), see \^, \hat, \widehat. *\hbadness, 29, 272, 302, 348, 387–388, 401. \hbar ( ¯ h ), 169, 358, 435. hbox (box with horizontal list inside), 64. *\hbox, 64–67, 77, 86, 93, 151, 159, 163, 175, 179, 185–186, 221, 222, 278, 282, 388–389. \headline, 252–253, 255, 362, 406. \heartsuit ( ♥ ), 435. Hebrew, 66. height, 221, 224, 282, 337. height of a box, 63–67, 77, 80–82, 225. help messages, 32, 280, 295–296. hhex digiti, 269. hhexadecimal constanti, 269. hexadecimal notation, 43, 44, 45, 47–48, 154, 219, 336, 420. *\hfil, 71–72, 194, 235–237, 283, 285, 290, 397. *\hfill, 71–72, 142, 177, 194, 233, 283, 285, 290. *\hfilneg, 72, 100, 233, 283, 285, 290, 397. *\hfuzz, 30, 274, 302, 348, 387–388. \hglue, 352. \hideskip, 347, 348, 354. \hidewidth, 243, 245, 247, 325, 354. higher-level languages for composition, 203. Highton, Albert H., 481. Hilbert, David, 167. *\hoffset, 251, 274, 342. *\holdinginserts, 125, 273, 400. Holmes, Thomas Sherlock Scott, 401. \hom ( hom ), 162, 361. Hombert, Humbert, 401. Honeywell Information Systems, 1. \hookleftarrow ( ←- ), 358, 437. \hookrightarrow ( ,→ ), 358, 430, 437. hooks, see \subset, \supset. horizontal braces, 176, 225–226, 339. hhorizontal commandi, 283. horizontal lists, 64, 94–95. horizontal mode, 85–89, 105, 285–287. hhorizontal mode materiali, 278. hhorizontal rulei, 281. horizontal rules, 24, 64, 221–226, 246, 282. hhorizontal skipi, 285. Hornschuch, Hieronymus, 483. Howard, Jane Temple, 21. \hphantom, 178, 211, 360. *\hrule, 24, 64, 85, 221–225, 246, 281–282, 286, 357, 420, 421. ), 244, 252, 357, 412. \hrulefill ( *\hsize, 26–27, 60, 102, 188, 237, 251, 257, 274, 340–341, 348, 387, 406, 407, 413, 415, 417. *\hskip, 71, 86, 168, 283, 285, 290, 314. *\hss, 71, 82–83, 233, 283, 285, 290, 442. *\ht, 120, 271, 388–389, 417. Hungarian umlaut (˝), see \H. hyphen, 4, 51, 93, 95, 132, 292. hyphen.tex, 364, 453. hyphenation, 28, 39, 96, 306, 314, 394–395, 414, 424, 449–455. *\hyphenation, 277, 419, 452–453, 455. hhyphenation assignmenti, 277. *\hyphenchar, 95, 214, 271, 273, 277, 286, 351, 395, 414, 454, 455. 467 468 Appendix I: Index *\hyphenpenalty, 96, 101, 272, 348, 451. \i ( ı ), 52–53, 356. I can’t go on, 299. \ialign, 354. IBM Corporation, vii. identifiers in programs, 38, 165, 234. *\if, 209, 210–211, 307, 377, 379. *\ifcase, 210, 349, 373, 390, 406. *\ifcat, 209, 210, 307, 377. *\ifdim, 209, 353, 387, 417. *\ifeof, 210, 217. \iff ( ⇐⇒ ), 163, 361, 438. *\iffalse, 210, 211, 260–261, 348, 385–386. *\ifhbox, 210, 392, 399. *\ifhmode, 209, 363. *\ifinner, 209. *\ifmmode, 209, 215, 240, 353, 356, 360, 423. *\ifnum, 208, 209, 218–219. *\ifodd, 207, 209, 416, 418–419. *\iftrue, 210, 211, 260–261, 348. \ifundefined, 40. *\ifvbox, 210. *\ifvmode, 209. *\ifvoid, 210, 256. *\ifx, 210, 215, 307, 384, 375–377, 418. ignored characters, 37, 390. *\ignorespaces, 279, 333, 355, 424. ! Illegal unit, 295. illustrations, 115–116. fitting copy around, 101. \Im ( = ), 435. \imath ( ı ), 136, 435. *\immediate, 226–228, 280, 422, 423. implicit braces, 269, see \bgroup, \egroup. implicit characters, 269, 277, 309, 351, 376–377. implicit kerns, 306, 454, 455. in (inch), 24, 57, 270. \in ( ∈ ), 128, 147, 436. \inaccessible, 297. inch, 57–58. incomplete conditionals, 206. *\indent, 86, 94, 101, 263, 282, 286, 291, 355. indentation, 86, 222, 282. hanging, 79, 102–103. indention, see indentation. indexes, 261–263, 392–394, 423–425, 481. indices, see subscripts. \inf ( inf ), 162, 361. inferiors, see subscripts. infinite badness, 97, 107, 111, 229, 317. infinite glue, 71–72, 118–119, 256, 313, 332. infinite loop, 299, 301, 383. infinite penalty, 97, 111, 254–256, 264, 286, 400. \infty ( ∞ ), 9, 318, 435. inhibiting expansion, 216, 262–263, 377. INITEX, 39, 41, 76, 157, 283, 336, 343–345, 453. Inner atom, 158, 170, 289, 443, 445–446. *\input, 7, 9, 25–27, 47, 199, 214, 217, 380, 382–383, 403, 422. input/output commands, see \input, \read, \write, \message, \dump. input/output streams, 346, see \openin, \openout. input stack, 300, 374. *\inputlineno, 214, 271. *\insert, 95, 122–125, 259, 280–281, 363, 416, 424, 454. inserting text online, 31. insertions, 110, 115–117, 122–125, 256, 335. *\insertpenalties, 111, 114, 123–125, 214, 254, 256, 271. \int (large ∫ ), 144, 168–169, 192, 358, 435. hinteger constanti, 269–270. hinteger parameteri, 271, 272–273, 276. hinteger variablei, 276. integral signs, see \int, \smallint. multiple, 169, 180. inter-column spacing, 237–239, 247, 392. interacting with TEX, 31–34, 217–218, 228, 295–299. hinteraction mode assignmenti, 277. \interdisplaylinepenalty, 193, 349, 362. \interfootnotelinepenalty, 349, 363. interline glue, 78–79, 80, 104, 105, 221, 245, 263, 281–282, 335, 352, 409. *\interlinepenalty, 104, 272, 363, 406, 419. internal box-and-glue representation, 66, 75, 79, 158–159, 302, 455. internal character codes, 43–46, 367–370. hinternal dimeni, 271. hinternal gluei, 271. hinternal integeri, 271. hinternal mugluei, 271. hinternal quantityi, 279. Internal Revenue Service, 200, 208–209, 244, 404. hinternal uniti, 270. internal vertical mode, 85, 87–89, 222, 278–283. interrupts, 33, 299, 383. interword spacing, 74–76, 356, 393–394, 433. Interwoven alignment preambles, 299. hintimate assignmenti, 277. Appendix I: Index invalid characters, 37, 45. \iota ( ι ), 325, 434. Isocrates, 239. \it (use italic type), 13–14, 165, 231–232, 332, 351, 409, 414–415, 419, 428. italic corrections, 14, 64, 287, 306, 441, 455. italic letters with descenders, 319. italic type, 13–14, 100, 127, 409, 428, 430. \item, 102–103, 117, 340–342, 355, 416, 419. \itemitem, 102, 342, 355. iteration, see \loop. \itfam, 351, 414–415. ÄIur’ev, Serge˘ı Petrovich, 53. \j (  ), 52, 356. Jevons, William Stanley, 5. \jmath (  ), 136, 435. *\jobname, 213, 214, 336. Johnson, Samuel, 89. \joinrel, 358. jokes, vi, 303, 449. \jot, 194, 242, 349, 362. Joyce, James Augustine, 100. justification, see setting glue, line breaking. Justus, Paul E., 455. \kappa ( κ ), 128, 434. \ker ( ker ), 162, 361. *\kern, 10, 40, 66, 75, 87, 168, 256, 263, 280, 306, 389, 394–395, 416, 424, 454–455. Kernighan, Brian Wilson, 159. kerns, 4, 66, 75, 95–97, 110, 157, 168, 280, 286, 306, 444, 454–455. Key Index, 392–394. keyboards, 3, 5, 43–46, 368–370. keywords, 61, 71, 268, 337, 370. Knuth, Donald Ervin, i, ii, vii, 74, 92, 211, 259, 337, 340–341, 412–413, 424–425. Knuth, Nancy Jill Carter, iii, 125, 418. K¨ ochel, Ludwig, Ritter von, 409. l after fil, 271, 337. £, see pound sterling. \l ( Ãl ), 52–53, 356. \L ( L Ã ), 52–53, 356. \lambda ( λ ), 176, 434. \Lambda ( Λ ), 323, 434. Lamport, Leslie B., 137. \land ( ∧ ), 133, 361, 438. \langle ( h ), 146–147, 150, 156, 359, 437. *\language (hyphenation method), 273, 346, 455. large delimiters, 145–150, 442. large operators, 144–145, 154–155, 358, 435; see also Op atom. *\lastbox, 222, 278, 354, 392, 398, 399. *\lastkern, 214, 271. *\lastpenalty, 214, 271. *\lastskip, 214, 223, 271, 392. LATEX, 137. \lbrace ( { ), 146–147, 359, 437. \lbrack ( [ ), 146–147, 351, 369, 437. *\lccode, 41, 214, 271, 345, 452–454. \lceil ( d ), 146–147, 359, 437. \ldotp, 358, 359, 438. \ldots ( . . . ), 73, 172–174, 177, 180–181, 199–201, 359, 438. \le ( ≤ ), 9, 45, 133, 162, 318, 361, 438. leaders, 222, 223–226, 228, 280–282, 285, 290, 357, 392–394. hleadersi, 281. *\leaders, 95, 110, 223, 224, 225, 357, 392–394. leading, see \baselineskip, \vskip. \leavevmode, 313, 333, 356, 408, 420. Lee, Marshall, 17. *\left, 148–150, 155–157, 171, 196, 292, 437. left brace, 13–14, 19–21, 38, 51, 200–202, 203–204, 205–206, 216, 269, 275–276, 283, 286, 291, 330. hleft bracei, 275. left bracket, 51, 134, 146–148, 171, 408, 437. left delimiters, see openings. left-hand pages, 252–253, 416. left parenthesis, 51, 134, 140, 145–150, 345. left quote, 3–5, 132, 134, 305, 394–395; see also alphabetic constant. \leftarrow ( ← ), 226, 437. \Leftarrow ( ⇐ ), 226, 437. \leftarrowfill (←−−−−−−), 357. \leftharpoondown ( ) ), 437. \leftharpoonup ( ( ), 437. *\lefthyphenmin, 273, 364, 454, 455. \leftline, 101, 257, 259–260, 326, 353. \leftrightarrow ( ↔ ), 437. \Leftrightarrow ( ⇔ ), 437. *\leftskip, 100, 274, 317, 407, 419. Legendre symbol, 152. Leontief, Wassily Wassily, 265. \leq ( ≤ ), 318, 358, 436. \leqalignno, 192, 194, 362. *\leqno, 187, 189, 293, 375–376. Lesk, Michael Edward, 247. less than or equal, see \le. less than sign, 52, 53, 133, 150, 209. *\let, 206–207, 215, 277, 307, 309, 352, 376. hlet assignmenti, 277. letterformat.tex, 403, 406–408. 469 470 Appendix I: Index letterheads, 407. letters, 7–8, 37, 41, 45–46, 51, 132, 157, 344, 370. \lfloor ( b ), 146–147, 359, 437. \lg ( lg ), 162, 361. \lgroup, 150, 176, 359, 437. \lhook, 358. Liang, Franklin Mark, 449. library of macros, 199, 382–384, 425. lies, vii, 303. ligatures, 4, 19, 46, 51, 54, 75, 95, 165, 286, 302, 381, 427, 444, 454. \lim ( lim ), 162, 163, 361. \liminf ( lim inf ), 162, 163, 178, 361. *\limits, 144, 159, 292, 359, 443. limits above and below operators, 144–145, 149, 179. \limsup ( lim sup ), 162, 163, 178, 361. Lincoln, Abraham, 11. \line, 72, 77, 101, 224, 232, 252, 255–257, 353, 412. line breaking, 97–100, 173–174, 392–395, 398–400. line breaks, avoiding bad, 27–30, 91–94, 173–174, 197. forcing good, 94, 114. line rules, see \hrule, \vrule. hlinefeedi (ASCII code 10), 369. *\linepenalty, 98, 272, 314, 316, 348. lines of input, 24, 46–48, 340. *\lineskip, 78–80, 104, 194, 274, 281, 349, 351–352. *\lineskiplimit, 78–80, 104, 194, 274, 281, 349, 351–352, 362. list macros, 378–380. \listing, 380, 391. \ll ( ¿ ), 431, 436. Llanfair P. G., 451. \llap, 82–83, 189, 340–341, 353, 355, 381, 416–417, 422. \lmoustache, 150, 359, 437. \ln ( ln ), 162, 186, 361. \lnot ( ¬ ), 361, 438. local, 19–21, see grouping. Locke, John, 303. \log ( log ), 162, 169–170, 361. log file, 10, 28, 66, 226, 303, 347. logical operators, see \land, \lor, \lnot. logo, 1, 8, 412, see \TeX. *\long, 205–206, 210, 275, 331, 375, 378, 382. long formulas, 195–197. \longindentation, 407. \longleftarrow ( ←− ), 358, 437. \Longleftarrow ( ⇐= ), 358, 437. \longleftrightarrow ( ←→ ), 358, 437. \Longleftrightarrow ( ⇐⇒ ), 358, 437. \longmapsto ( 7−→ ), 358, 437. \longrightarrow ( −→ ), 325, 358, 437. \Longrightarrow ( =⇒ ), 358, 437. looking ahead, 207, 376–377. \loop, 217–219, 352, 373–374, 387, 417. loose lines, 97, 99, 302. *\looseness, 103–104, 109, 273, 342, 349. \lor ( ∨ ), 133, 361, 438. low-resolution printer, 59. *\lower, 66, 80, 151, 179, 285, 290. *\lowercase, 41, 215, 279, 307, 345. lowercase letters, 9, 268, 370, 453. \lq ( ‘ ), 5, 48, 351, 369, 395. Luckombe, Philip, 447. lxix, 420. \[email protected], 347. \[email protected], 353. machine-independence, 58; see also .dvi. Macro, Nævius Sertorius, 219. macro arguments and parameters, 33, 200–205, 249, 263, 362, 363, 375–380, 407. hmacro assignmenti, 275. macro conventions, 121, 346, 364. macron accent (¯), see \=, \bar. macros, 199–219, 373–401. to save typing in math, 136, 199–200, 324. *\mag, 60, 270, 273, 348. \magnification, 17, 59–60, 364, 403–404. magnified output, 16–17, 59–60, 403, 433. \magstep, 17, 59–60, 349, 403–404. \magstephalf, 17, 349, 403. mail, 403–408. main vertical list, 85, 110, 112, 125, 253–254, 281. \maintoks, 262. \makefootline, 255–257, 364. \makeheadline, 255, 257, 364. \makelabel, 403, 404–405, 408. manfnt, 44, 408, 414. manmac.tex, 413–425. \manual, 44, 414, 419–420. \mapsto ( 7→ ), 128, 358, 437. \mapstochar ( 7 ), 358. \margin, 415, 424. marginal hacks, 82, 105, 400, 415, 424. margins, see \hsize, \narrower. *\mark, 95, 157, 216, 258–263, 280, 417, 454. marks, 95, 110, 157, 213, 258–263. markup commands, see control sequences. Appendix I: Index math accents, 135–137, 141, 164–165, 359, 435, 443. hmath atomi, 291. hmath characteri, 289. math character codes, 154–157. hmath fieldi, 289. math fonts, 157, 351, 430–433, 441, 447. math formulas, how to type, 127–197. math italic, 164–165, 409, 430, 433. math lists, 157–159, 441–446. math mode, 85–89, 127, 157, 289–293. math spacing table, 170–171. hmath symboli, 289. math symbols, 127–128. construction of, 151, 178, 358–361. table of, 434–438. math-off, 95–97, 287, 447. math-on, 95, 97, 287, 447. *\mathaccent, 157, 170, 291, 359, 443. *\mathbin, 155, 291, 361. *\mathchar, 155, 289. *\mathchardef, 155, 199, 214, 215, 272, 277, 289, 336, 394. hmathchardef tokeni, 271. *\mathchoice, 151, 157, 292. *\mathclose, 155, 291, 322, 359. *\mathcode, 134, 154–155, 214, 271, 289, 319, 326, 344. mathematical expressions, 127–197. Mathematical Reviews, 106, 392–394. hmathematical skipi, 290. mathematical style, 166–167, 182–183. \mathhexbox, 356. *\mathinner, 155, 171, 199, 291, 359. *\mathop, 155, 178, 291, 324–325, 361. *\mathopen, 155, 291, 322, 359. *\mathord, 88–89, 155, 291. \mathpalette, 151, 360. *\mathpunct, 155, 291. *\mathrel, 155, 291, 359–361. \mathstrut, 131, 178, 360. *\mathsurround, 97, 162, 274, 305, 314, 323, 353, 447. matrices, 176–178, 181; see also alignments. \matrix, 176–178, 182, 325, 361. \max ( max ), 162–163, 170–171, 361. *\maxdeadcycles, 255, 273, 348. *\maxdepth, 112–114, 123–125, 255, 262–263, 274, 348, 400, 415. \maxdimen, 58, 188, 262–263, 347, 348. maximum legal dimension, 58. maximum legal integer, 118. *\meaning, 213–215, 336, 382. measure, see \hsize. \medbreak, 111, 113, 353, 355, 419, 422. *\medmuskip (medium math space), 167–168, 274, 349, 446. \medskip (medium extra vertical space), 70, 79, 102, 109, 111, 352, 410–412. \medskipamount, 349, 352–353, 355, 407. \medtype, 408–411. membership, see \in, \ni, \notin. memory space, 100, 300–301, 342, 345, 347, 383, 384, 394, 400. *\message, 216, 217–218, 227–228, 279, 308, 328, 343–344, 355, 418. opqrstuq, 420, 427, 442, 483. metric units, 57–60. \mid ( | ), 174, 436. \midinsert, 116, 340–341, 363. migration, 105, 117, 259, 280–281, 282, 286, 287. \min ( min ), 162–163, 170–171, 361. minus, 71, 271, 337. minus sign, 4, 51, 127, 132, 226, 268. ! Missing something, 296–297, 337. \mit (math italic family), 164, 351, 430, 434. *\mkern, 168, 280, 442. mm (millimeter), 57, 270. mod, 164, 322, 361. \models ( |= ), 358, 436. modes, 46, 85–89, 175, 267–293. modes.tex, 88–89. money, 54, 140, 208–209. *\month, 273, 349, 406. Morris, William, 107. moustaches, 150. mouth, see anatomy of TEX. *\moveleft, 80–81, 282, 287. *\moveright, 80–81, 221, 282. Moxon, Joseph, 287. Mozart, Johann Chrysostom Wolfgang Gottlieb (= Theophilus = Amadeus), 409. \mp ( ∓ ), 133, 436. *\mskip, 168, 290, 442. mu (math unit), 168, 270, 442. \mu ( µ ), 162, 434. hmu uniti, 270. hmudimeni, 270. hmugluei, 118, 167–168, 271. hmuglue parameteri, 271, 274, 276. hmuglue variablei, 276. Muir, Cockburn, 283. Muirhead, James, 21. multicolumn format, 257, 396–397, 417. multiple integrals, 169, 180. 471 472 Appendix I: Index *\multiply, 118–119, 218, 276, 349, 391, 398. \multispan, 243, 246–247, 334, 354. Munster, 55. hmushrinki, 271. music, 408–412. *\muskip registers, 118, 168, 271, 276. *\muskipdef, 119, 215, 277. hmuskipdef tokeni, 271. hmustretchi, 271. \nabla ( ∇ ), 435. names, 73, 92. \narrower, 100, 340–341, 355. National Science Foundation, vii. \natural ( \ ), 435. natural width, 69. Naur, Peter, 268. \ne ( 6= ), 9, 45, 133, 318, 361, 438. \nearrow ( % ), 437. \neg ( ¬ ), 435. negated relations, 436–437. negative dimensions, 66, 222. \negthinspace, 332, 352. \neq ( 6= ), 318, 358, 438. nesting (i.e., groups inside groups), 20–21, 210, 385. new symbols, 151, 178, 358–361. \newbox, 121, 346, 347, 353, 394, 417. \newcount, 121, 218, 346, 347, 349, 418. \newdimen, 121, 346, 347, 349, 415. \newfam, 121, 157, 346, 347, 351. \newhelp, 346, 347. \newif, 211, 218, 348, 354, 375, 416, 423. \newinsert, 121, 122, 346, 347, 363, 415. \newlanguage, 346, 347. *\newlinechar, 228, 273, 348. \newmuskip, 121, 346, 347. \newread, 121, 216, 346, 347. \newskip, 121, 346, 347, 349, 394, 414. \newtoks, 121, 212, 262, 346, 347, 401. \newwrite, 121, 227, 346, 347, 422–423. \next, 352. \ni ( 3 ), 436. \ninepoint, 15, 414, 419. \ninerm, 15, 413. \ninesl, 15, 413. No room, 347. *\noalign, 176, 191, 193, 237, 246, 249, 282, 285, 286. *\noboundary, 283, 286, 290. \nobreak (inhibit line or page break), 97, 109, 174, 193, 335, 353, 394, 407. *\noexpand, 209, 213, 215, 216, 348, 377, 424. *\noindent, 86, 188, 262–263, 283, 286, 291, 340–341, 355, 419. \nointerlineskip, 79–80, 255, 331, 352, 389. *\nolimits, 144, 159, 292, 358, 361. hnon-macro assignmenti, 275. nonaligned leaders, 224–226. \nonfrenchspacing, 74, 351. *\nonscript, 179, 290, 442, 446. *\nonstopmode, 32, 277, 299. \nopagenumbers, 251–252, 362, 406, 409. norm symbol, see absolute value, vertical line. hnormal dimeni, 270. hnormal integeri, 269. hnormal mudimeni, 270. \normalbaselines, 325, 349, 351, 414–415. \normalbaselineskip, 349, 414–415. \normalbottom, 363. \normallineskip, 349, 351. \normallineskiplimit, 349, 351, 362. Norwegian characters, 45–46, 52–53, 370. \not ( 6 ), 133, 358, 436–437. \notin ( ∈ / ), 360, 437. nth, 323. \nu ( ν ), 128, 163, 434. nucleus, 158–159, 289–292, 441–446. \null, 311, 332, 351. hnulli (ASCII code 0), 37, 39, 48, 343, 369. null control sequence, 46, 308. null delimiter, 149–150, 152, 156, 345, 360, 362. null set, see \emptyset. *\nulldelimiterspace, 150, 274, 348, 442. *\nullfont, 14, 153, 271, 433. hnumberi, 44, 118, 269–270, 272, 309, 349. *\number, 40–41, 213, 214, 252, 406, 424. number sign, see hash mark. numbered footnotes, 121, 125. numerals, see digits, roman numerals. numerator, 141, 152, 179, 444–445. hnumeric variablei, 276. numerical tables, 240–241. \nwarrow ( - ), 437. O versus 0, 132. \o ( ø ), 356. \O ( Ø ), 356. \oalign, 356. obelisk or obelus, 53. \obeylines, 94, 249, 262, 342, 352, 380–382, 407, 419. \obeyspaces, 254, 308, 342, 352, 380–381, 394, 421. Appendix I: Index oblique, see slanted. hoctal constanti, 269. hoctal digiti, 269. octal notation, 43, 44, 155, 420. odd-numbered pages, 252–253, 416. \odot ( ¯ ), 436. \oe ( œ ), 52, 356. \OE ( Œ ), 52, 53, 356. Office of Naval Research, vii. \offinterlineskip, 245–247, 312, 352, 416. \oint (large ∫◦), 358, 435. \oldstyle, 351. oldstyle numerals, 430, 435. \omega ( ω ), 323, 358, 434. \Omega ( Ω ), 358, 434. \omicron, 434. \ominus ( ª ), 436. *\omit, 240, 243–244, 246–247, 282. one half, 141, 186. hone optional spacei, 269–270. online interaction, see interacting with TEX. \ooalign, 356. Op atom, 158–159, 170–171, 289, 442–444. Open atom, 158, 170–171, 289, 442–444, 446. open intervals, 171. openface, see blackboard bold. *\openin, 216–217, 280. openings, 134, 147, 154–155, 359, 437; see also Open atom. *\openout, 226–228, 254, 280, 422, 423. \openup, 194, 237, 242, 362. \oplus ( ⊕ ), 9, 154, 436. optimization of macros, 342, 345, 348. hoptional assignmentsi, 286. hoptional byi, 276. hoptional signi, 57. hoptional signsi, 269. hoptional spacesi, 268, 269–271. hoptional truei, 270. *\or, 210, 213, 406. Ord atom, 158, 170–171, 289, 358, 442–446. ordinary symbols, 132, see Ord atom. Ore, Øystein, 53. organists, 239. organs, 38–39, 46, 85, 267, 373, 456. orphan, see widow word. Osbourne, Lloyd, 67. \oslash ( ® ), 436. \other, 421. other character, 37. \otimes ( ⊗ ), 9, 436. *\outer, 206, 210, 275, 354, 357, 418–419, 422. *\output, 125, 253, 254–257, 275, 364, 370, 417. output routines, 21, 112, 251–264, 417. when invoked, 122, 125, 281. *\outputpenalty, 125, 254–255, 273, 349, 400, 417. *\over, 139–141, 148, 152, 292, 437, 444–445. Over atom, 158, 289, 443. \overbrace, 176, 225, 359. overfull boxes, 27–30, 94, 229, 238, 302–303, 307, 400. avoiding, 107. *\overfullrule, 274, 307, 348. overlaps, 82–83, 386. \overleftarrow, 359. *\overline, 130–131, 136, 141, 170, 291, 443. overloading, 54, 243. \overrightarrow, 226, 359. *\overwithdelims, 152, 292, 444–445. \owns ( 3 ), 361, 438. \P ( ¶ ), 53, 117, 356, 438–439. \[email protected], 347, 348. \[email protected], 361. page breaks, avoiding bad, 109–111, 189, 193. forcing good, 109–111; see also \eject. page builder, 110–114, 122–125, 281. when exercised, 122, 280–283, 286–287. page format, modifying, 251–253. page make-up, 109, see output routines. page numbers, 21, 23, 119, 207, 251–253. \pagebody, 255–257, 364. \pagecontents, 256, 364. *\pagedepth, 114, 123, 214, 271. *\pagefilllstretch, 114, 214, 271. *\pagefillstretch, 114, 214, 271. *\pagefilstretch, 114, 214, 271. *\pagegoal, 114, 123, 214, 271. \pageinsert, 115, 363. \pageno, 252, 256, 340, 362, 406. *\pageshrink, 114, 123, 214, 271. *\pagestretch, 114, 214, 271. *\pagetotal, 114, 123, 214, 271. *\par, 47, 86–87, 100, 135, 202, 249, 262, 283, 286, 340, 351, 380–381. forbidden in arguments, 205, 207. paragraph, implied beginning of, 85–86, 283. implied end of, 24, 86, 286. last line of, 99–100. shape parameters reset, 103. paragraph sign, 53. \parallel ( k ), 436. hparameter texti, 203, 275. 473 474 Appendix I: Index parameters, see macro arguments and parameters. parameters, numeric, 119, 342; see also \fontdimen. default values, 348–349. table, 272–274. parentheses, 51, 129, 134, 140, 145–150, 345, 437. roman, in italic text, 409–411. *\parfillskip, 100, 188, 274, 286, 307, 315, 332, 348, 394, 419. *\parindent, 86, 100, 101–102, 105, 262, 274, 282, 286, 291, 342, 348, 355, 394, 406, 415. *\parshape, 101–102, 214, 271, 277, 283, 315, 349, 374. *\parskip, 79, 104–105, 262, 274, 282, 342, 348, 355, 406, 417. \partial ( ∂ ), 147, 435. Pascal, Blaise, 101–102. \path, 390–391. *\patterns, 277, 453, 455. patterns for hyphenation, 449–453. *\pausing, 273, 303. Paxton, William Hamilton, 425. pc (pica), 57, 270, 415. penalties, 95–100, 110–114, 189. infinite, 97, 111, 286, 400. negatively infinite, 97, 111–112, 114, 254–256, 264, 400. *\penalty, 79, 97, 110–111, 174, 280, 353. \penalty-’10000000000, 264. percent sign, 26, 38, 39, 43, 48, 51, 113, 124, 249, 337, 340. period, 51, 72–73, 133–134, 149, 161, 345, 394–395, 430. space after, 73–75 ; 76. periodic preambles, 241–242, 244, 246, 361, 412. Perlis, Alan J., 365. \perp ( ⊥ ), 358, 436. \phantom, 131, 178, 211, 360, 412. \phi ( φ ), 128, 148, 434. \Phi ( Φ ), 323, 434. Philips, Peter, 239. philosophers, 100, 239. hphysical uniti, 270. \pi ( π ), 9, 87, 137, 148–149, 434. \Pi ( Π ), 9, 324, 434, 435. piano, 17. pica, 57, 413, see pc. pictures, 228–229. pieces of symbols, 145, 432, 442. pilcrow, see \P. plain.tex, 342–364. plain TEX format, 10–11, 343–364. summary, 339–342. \plainoutput, 255, 364. Plass, Michael Frederick, 340–341. Plato, 1, 239. plus, 71, 271, 337. hplus or minusi, 268. plus sign, 51, 132, 268. \pm ( ± ), 133, 358, 436. \pmatrix, 176, 323, 362. \pmod (notation like (mod p)), 164, 322, 361. \pnt, 395. pocket-size, 59. poem, 94. points (printers’ units), 15, 57–58. points with arbitrary coordinates, 389. Polish characters, 52–53. P´ olya, Gy¨ orgy (= George), 7. poor man’s bold, 386. *\postdisplaypenalty, 189–190, 272. poultry, 236–237. pound sign, see hash mark. pound sterling, 54, 428. powers of ten, 293. powers of two, 293. \Pr ( Pr ), 162, 323, 361. preambles, 206, 235–249. \prec ( ≺ ), 436. \preceq ( ¹ ), 436. *\predisplaypenalty, 189–190, 272, 348. *\predisplaysize, 188, 190, 274, 349. hprefixi, 275. \preloaded, 350, 413. preloaded formats, 25–26, 39, 283, 344. Presume, Livingstone Irving, 74. *\pretolerance, 96, 107, 272, 317, 348, 364, 394, 451. pretty-printed programs, 165, 234. *\prevdepth, 79–80, 89, 271, 281, 282. prevdepth ignored, 88–89. *\prevgraf, 103, 188, 190, 214, 271. \prime ( 0 ), 130, 155, 357, 435. prime numbers, 148–149, 218. primitive, 9–11, 267, 342, 457. private control sequences, 344, 364, 414. \proclaim, 202–203, 206, 340–341, 355. Procter, William Alexander, 38. \prod (large Π), 180–181, 435. programming with TEX, 217–219, 387–388. programs, for computers, 38, 165, 234. for music, 408–412. Appendix I: Index proofreading, 59, 303. proper names, 73, 92. \propto ( ∝ ), 436. prototype row, 238, 302–303. Prætorius [Schultheiss], Michael, 239. \ps, 403, 404, 407. pseudo parameters, 119, 349. \psi ( ψ ), 325, 434. \Psi ( Ψ ), 434. psychologically bad breaks, 91–93. pt (printer’s point), 24, 57–58, 268–270. Punct atom, 158, 170–171, 289, 442–443, 446. punctuation, 14, 51, 72–76, 321, 394–395. in formulas, 134, 154–155, 161, 358–359, 438; see also Punct atom. \qquad, 166, 185, 352. quad, 60, 166–168, 177, 433. \quad, 94, 166–167, 185, 232–233, 352. quad left, see flush left. quad middle, see \break. quad right, see flush right. quarter circles, 389–391. question mark, 51, 73, 161. Quick, Jonathan Horatio, 298. quotation marks, 3–5, 24, 394–395. quotations, 100, 418–419, 425. quotes within quotes, 5. IR, see blackboard bold. Rad atom, 158, 289, 443. *\radical, 157–159, 291, 443. ragged bottom margins, 111, 253, 256, 398. ragged left margins, 392–394. ragged right margins, 29–30, 101, 261–262, 355–356, 392–394. \raggedbottom, 111, 253, 363, 406. \raggedcenter, 107. \raggedright, 29–30, 76, 101, 107, 115, 262, 356, 396, 407. *\raise, 66–67, 80, 151, 179, 193, 285, 290, 408. \rangle ( i ), 146–147, 150, 359, 437. Raper, Matthew, 61. \rbrace ( } ), 146–147, 359, 437. \rbrack ( ] ), 146–147, 351, 369, 437. \rceil ( e ), 146–147, 359, 437. \Re ( < ), 435. *\read, 215, 217–218, 276, 346, 401. recent contributions, 112, 125, 281. recovery from errors, 30–34, 295–303. recursion, 219, 268, 301, 379, 391, 397. infinite, 299, 301, 383. reduction, 16. reference marks, 116–117. reference point of a box, 63–64, 77, 80–82, 388–389. hregisterdefi, 277. registers, 117–122, 212, 214, 346–348. registration marks, 416. Reid, Brian Keith, 371, 404–406. Rel atom, 158, 170–171, 289, 442–444, 446–447. hrelationi, 209. relations, 133–134, 147, 154–155, 358, 436, 437; see also Rel atom. *\relax, 23, 25, 71, 240, 276, 279, 307, 353. \relbar ( − ), 358. \Relbar ( = ), 358. *\relpenalty, 101, 174, 272, 322, 348, 446. \removelastskip, 353. \repeat, 217–219, 352. repeating commands, see \loop. reserved characters, 37–38, 51–52, 134. reserved words, 61, 71, 268, 337, 370. restricted horizontal mode, 85, 87–89, 285–287. r´ esum´ e, 253. hreturni (ASCII code 13), 23, 39, 43, 45, 46, 48, 249, 331, 343, 345, 369, 380. \hreturni, 8, 305, 351. reverse apostrophe, 3–5, 51, 132, 134, 391, 394–395; see also alphabetic constant. reverse slash, see backslash. Reviewer, Ann Arbor, 106. \rfloor ( c ), 146–147, 359, 437. \rgroup, 150, 176, 359, 437. \rho ( ρ ), 128, 325, 434. \rhook, 358. *\right, 148–150, 155–157, 171, 196, 292, 437. right brace, 13–14, 19–21, 38, 51, 200–202, 203–204, 205–206, 269, 275–276, 279, 301, 330. hright bracei, 275. right bracket, 51, 134, 146–147, 171, 345, 408, 437. right delimiters, see openings. right-hand pages, 252–253, 416. right justification, 71. right parenthesis, 51, 134, 140, 145–150, 345. right quote, 3–5, 51, 130, 155, 201, 305, 324, 394–395; see also octal. \rightarrow ( → ), 226, 437. \Rightarrow ( ⇒ ), 226, 437. 475 476 Appendix I: Index \rightarrowfill (−−−−−−→), 226, 357. \rightharpoondown ( + ), 437. \rightharpoonup ( * ), 437. *\righthyphenmin, 273, 364, 454, 455. \rightleftharpoons ( * ) ), 360–361, 437. \rightline, 101, 317, 340–341, 353. *\rightskip, 100–101, 274, 317, 356, 393, 421. \rlap, 82–83, 189, 247, 319, 353, 389, 416. \rm (use roman type), 13–15, 154, 163, 320, 351, 364, 409, 414–415, 419, 427. \rmoustache, 150, 359. roman letters in math, 162–164. roman numerals, 40–41, 252, 256. uppercase, 374. roman parentheses in italic text, 409–411. roman type, 13–17, 51–55, 127, 162–165, 427. *\romannumeral, 40–41, 213, 214, 252. Root, Waverley Lewis, 55. \root, 130–131, 179, 325, 360. rounding, 58, 119. \rq ( ’ ), 5, 48, 351, 369, 395. rule boxes, 24, 64, 221–225, 281–282, 285, 291. hrule dimensioni, 282. hrule specificationi, 282. rule thickness, 143, 179, 221, 447. ruled tables, 245–248, 392. rulers, 58. runaways, 205–206, 297. running headlines, 253, 258–260, 416. running the program, 23–35. Russian characters, 370. \S ( § ), 53, 117, 356, 438–439. Sally, Baby, 72–76. sample line for tabbing, 232–234. sample pages for book design, 412–413. save size, 300–301, 374, 399–400. save stack buildup, 301, 346. \sb, 135, 357, 369. \sc (use SMALL CAPS type), 414–415. scaled, 16–17, 60, 277, 350, 433. scaled points, 57–58, 270. Scandinavian letters, 45–46, 52–53. Schickele, Prof. Peter, 410–411, 481. scratch control sequence, 352. scratch registers, 122, 346. Scribe, 371, 404. script letters, 164, 434. script size, 140, 153, 442. script style, 140–142, 441–447. *\scriptfont, 153, 168, 213, 271, 321, 351, 414–415, 441–442. scriptscript size, 140, 145, 153, 442. scriptscript style, 140–142, 441–447. *\scriptscriptfont, 153, 168, 213, 271, 351, 414–415, 441–442. *\scriptscriptstyle, 141–142, 179, 292. *\scriptspace, 274, 348, 445–446. *\scriptstyle, 141–142, 145, 179, 292. *\scrollmode, 32, 277. \searrow ( & ), 437. \sec ( sec ), 162, 361. section number sign, see \S. Selden, John, 11. selection, see \cases. semicolon, 51, 134, 161. sentences, 72–76. Sesame Street, 61. set macro, 379. set notation, 147, 174–175. *\setbox, 66–67, 77, 81, 120, 276, 386–392. *\setlanguage, 287, 455. \setminus ( \ ), 436. \settabs, 231–234, 354, 355. setting the glue, 70, 77, 81, 388. \setupverbatim, 380–381, 391. \sevenrm, 15, 153, 350, 351, 414–415. *\sfcode, 76, 214, 271, 286, 321, 345, 351. shadow boxes, 66. Shakespeare, William, 17, 55, 337. hshape assignmenti, 277. hshape dimensionsi, 277. \sharp ( ] ), 409, 435. sharp S ( ß ), see \ss. sharp sign, see hash mark. Shaw, George Bernard, 107, 229. Sheridan, Richard Brinsley Butler, 265. shifted output, see \hoffset, \voffset. shilling sign, see slash. *\shipout, 227, 253–254, 279, 300, 302. shortest paths, 99. hshorthand definitioni, 277. *\show, 10, 215, 279, 299. *\showbox, 66–67, 121, 234, 279. *\showboxbreadth, 273, 302, 303, 348. *\showboxdepth, 79, 273, 302, 303, 348. \showhyphens, 364, 452. *\showlists, 88–89, 95, 112, 125, 158–159, 279, 293. *\showthe, 121, 215, 279. shriek, see exclamation point. hshrinki, 271. shrinkability, 69–71, 75, 409. Appendix I: Index side conditions, 166–167, 185–186. \sigma ( σ ), 195–196, 434. \Sigma ( Σ ), 165, 434, 435. sigma signs, see \sum. \signed, 106. \sim ( ∼ ), 133, 436. \simeq ( ' ), 133, 436. hsimple assignmenti, 276. \sin ( sin ), 162, 361. \sinh ( sinh ), 162, 361. sinkage, 413. size switching, 15, 408, 414–415. sizes of type for mathematics, 140, 153. \skew, 136, 359. *\skewchar, 214, 271, 273, 277, 351, 414, 430, 431, 443. *\skip registers, 118–122, 271, 276, 346–347, 349, 352, 363, 394. *\skipdef, 119, 215, 277, 346–347. hskipdef tokeni, 271. skipping space, see glue. \sl (use slanted type), 13–15, 165, 351, 409, 414–415, 419. slant of a font, 375, 433. slanted type, 13, 63–64, 100. slash, 51, 132, 146–147, 320, 430. \slash (/ with break allowed), 93, 353. slashed form of fractions, 139–140. Slavic h´ aˇ cek accent, see \v. \slfam, 351, 414–415. slides, 59. slurs, see \smile, \frown. small caps, 414. \smallbreak, 111, 353, 421. \smallint ( ∫ ), 358, 435. \smallskip, 70, 78, 100, 109, 111, 181, 340–341, 352, 355, 410–412. \smallskipamount, 349, 352–353. \smalltype, 408–411. \smash, 131, 178, 327, 360. \smile ( ^ ), 436. solidus, see slash. sophisticated spacing, 74. sp (scaled point), 57, 118–119, 270, 398, 400. \sp (superscript), 135, 357, 369. hspacei (ASCII code 32), 39, 43, 46, 343. \hspacei, see \Ã (near the beginning). \space, 254, 272, 306, 351, 380, 406. space after a constant, 208, 272. space factor, 76, 285–287, 306, 380, 395. hspace tokeni, 268, 269, 282, 285, 290, 376–377. *\spacefactor, 76, 271, 285, 363, 433. spaces, 3, 5, 8–9, 19, 37, 40, 47–48, 127, 204, 232, 272, 297, 299, 319, 336. as active characters, 254, 380–381. *\spaceskip, 76, 274, 317, 356, 429. spacing, see glue. in formulas, 162, 167–171. \spadesuit ( ♠ ), 358, 435. *\span, 215, 238, 243, 244, 245, 248, 249, 282, 330, 385. Spanish ligatures, 51, 381, 427. spanned columns in tables, 243–245. spanned rows in tables, 249. *\special, 216, 226, 228–229, 280. special characters, 37–38, 43–46, 51–52, 134, 367–371. hspecial dimeni, 271, 277. hspecial integeri, 271, 277. special symbols for math, 128, 434–438. Spivak, Michael David, 137. % split, 124. split insertion penalty, 124. *\splitbotmark, 213, 259, 280. *\splitfirstmark, 213, 259, 280. *\splitmaxdepth, 124, 274, 281, 348, 363, 417. *\splittopskip, 124, 274, 281, 348, 363, 397, 417. spread, 77, 222, 238, 278. springs, 70. \sqcap ( u ), 133, 436. \sqcup ( t ), 133, 436. \sqrt, 130–131, 141, 145, 157, 169–170, 360, 443. \sqsubseteq ( v ), 436. \sqsupseteq ( w ), 436. \square ( ), 151. square brackets, see brackets. square bullet ( ), 420. square root, see \sqrt. squeeze routine, 188. squiggle accent (˜), see \~, \tilde, \widetilde. squint print, 59. \ss ( ß ), 52, 356. stack positions, 300–301, 374, 399–400. stacked fractions, see \over. \star ( ? ), 436; cf. asterisk. states, 46–48. sterling, 54, 428. Stevenson, Robert Louis Balfour, 67. Stirling numbers, see \brace, \brack. stomach, see anatomy of TEX. stopping TEX, see \end. 477 478 Appendix I: Index story.tex, 24, 26, 30–31. Stout, Rex Todhunter, 401. hstretchi, 271. stretchability, 69–71, 75, 409. *\string, 40–41, 213–214, 215, 348, 377. \strut, 82, 142, 178, 240, 246–247, 316, 329, 333, 353, 396, 400, 421. \strutbox, 316, 353, 396, 414–415. struts, 82, 125, 131, 142, 178, 245–247, 255, 329, 416, 422, 423. style change items, 157, 442. style-independent documents, 194, 203. styles of math formatting, 140–141, 441–447. styles of math writing, 166–167, 182–183. subformulas, 129, 171, 173. hsubscripti, 291. subscripts, 15, 128–131, 133, 150, 158–159, 163, 179, 289–291, 343. \subset ( ⊂ ), 133, 436. \subseteq ( ⊆ ), 133, 436. \succ ( Â ), 436. \succeq ( º ), 436. \sum (large Σ), 139, 144–145, 148–149, 358, 432–433, 435. \sum0 , 181, 324–325. summary of plain TEX, 339–342. summation, see \sum. \sup ( sup ), 162, 361. \supereject, 116, 254, 256, 257, 353, 407. superiors, see superscripts. hsuperscripti, 291. superscripts, 128–131, 133, 150, 158–159, 179, 289–291, 343. suppressed-L, 52–53. \supset ( ⊃ ), 436. \supseteq ( ⊇ ), 436. √ \surd ( ), 358, 435. surd signs, see \radical, \sqrt. Swanson, Ellen Esther, 197. \swarrow ( . ), 437. Swedish characters, 52–53, 370. Sweelinck, Jan Pieterszoon, 239. ´ Swierczkowski, StanisÃlaw SÃlawomir, 53. Swift, Jonathan, 5. symbol fonts, 157, 351, 431, 433, 441, 447. symbolic box format, 66, 75, 79, 158–159, 302, 455. symbols in math, table, 434–438. syntax rules, 268–269. System Development Foundation, vii. Szeg˝ o, G´ abor, 7. \t (tie-after accent), 52–53, 356. htabi (ASCII code 9), 8, 45, 343, 369, 391. \htabi, 8, 351. \tabalign, 354, 355. tabbing, 231–234, 339, 354. compared to \halign, 235. tables, see alignments, tabbing. tables of contents, 120, 226. tables of TEX trivia: accents (non-math), 52, 339. atomic types, 158. category codes, 37. character codes, 367–369. default values, 343–345, 348–349. \fontdimen parameters, 433, 447. keywords, 61. math accents, 135. math classes, 154. math spacing, 170–171. math symbols, 434–438. parameters, 272–275. units of measure, 57. \tabs, 234, 354. *\tabskip, 215, 237–239, 244, 247, 274, 282, 285, 354. tabskip glue, 237–239, 245, 302–303, 392. Tacitus, Publius Cornelius, 219. tags, see equation numbers. tail recursion, 219. \tan ( tan ), 162, 361. \tanh ( tanh ), 162, 361. \tau ( τ ), 1, 434. Tchaikovsky, see Cha˘ıkovski˘ı. telephone numbers, 408. templates, 235–236, 240–243. \tenex, 350, 351, 361, 414–415. \tenpoint, 15, 414, 418. \tenrm, 15, 27–28, 45, 153, 252, 335, 350, 351, 414. \tensl, 15, 350, 351, 414. tensor notation, 130, 169. \tensy, 179, 350, 351, 414. terminal, input from, 217–218. output to, 217–218, 226–228, 279–280. TEX, 1. TEX, bad puns on, 1, 11, 63, 153, 161, 225, 229, 262, 305, 340–341, 373. pronunciation of, 1. TeX, 1. \TeX ( TEX ), 8–10, 19, 66–67, 204, 225, 340–341, 356, 418, 419. .tex, 25, 217, 226. TeX capacity exceeded, 300–301. Appendix I: Index TEX Grandmasters, 253. TEX Users Group, vii, 408, 483. TEX78, vii. texput, 23. text between aligned displays, 193. text size, 140, 153, 442. text style, 140–142, 441–447. *\textfont, 153, 168, 188, 213, 271, 351, 414–415, 441–442. \textindent, 117, 355. *\textstyle, 141–142, 292, 326. .tfm (font metric files), 401, 433, 442. *\the, 214–215, 216, 373, 375, 422. theorems, 111, 202–203, 340–341, 355. \theta ( θ ), 128, 162, 325, 434. \Theta ( Θ ), 434. *\thickmuskip (thick math space), 167–168, 274, 349, 446. thin spaces, 161, 167–173, 305, 409. *\thinmuskip (thin math space), 167–168, 274, 349, 446. \thinspace, 5, 10, 305, 311, 352, 409. This can’t happen, 299. Thor, Arthur Uther, 24, 117, 200, 253. three-column output, 257, 396–398. three dots, see ellipses. tie-after accent, see \t. ties, 25, 73–74, 91–93, 104, 161, 167, 173, 353, 404. tight lines, 97, 99, 302. tilde, 38, 51, 91–92, see ties. \tilde (math accent: x ˜), 135, 164. tilde accent (˜), see \~, \tilde, \widetilde. *\time, 273, 349. \times ( × ), 133, 436. Times Tribune, Peninsula, 455. Titelouze, Jehan, 239. to, 77, 217, 222, 238, 276, 278. \to, 134, 361, 438. \today, 406. token list parameters and registers, 212, 215, 275, 373. token lists, as displayed by TEX, 228, 329, 382. htoken parameteri, 275. htoken variablei, 212, 276. tokens, 38–41, 46–48, 203–207. *\toks, 212, 215, 262, 276. *\toksdef, 212, 215, 277, 347, 378. htoksdef tokeni, 271. *\tolerance, 29–30, 91, 94, 96, 107, 272, 317, 333, 342, 348, 364, 451. \top ( > ), 435. \topglue, 340, 352. \topins, 256, 363, 364. \topinsert, 115–116, 251, 363. *\topmark, 213, 258, 259–260, 280. *\topskip, 113–114, 124, 256, 274, 348. Trabb Pardo, Luis Isidoro, 92. \tracingall, 121, 303, 364. *\tracingcommands, 88–89, 212, 273, 299. *\tracinglostchars, 273, 301, 348, 401. *\tracingmacros, 205, 212, 273, 329. *\tracingonline, 121, 212, 273, 303. *\tracingoutput, 254, 273, 301–302. *\tracingpages, 112–114, 124, 273, 303. *\tracingparagraphs, 98–99, 273, 303. *\tracingrestores, 273, 301, 303. *\tracingstats, 273, 300, 303, 383. transcript, see log file. transparencies, 59. \triangle ( 4 ), 435. \triangleleft ( / ), 436. \triangleright ( . ), 436. triangular quotation, 101–102. tricky macros, 41, 261–263, 354, 360, 361, 373–401, 421. true, 59–60, 270, 407–408. truth, vi, 267. Tschichold, Jan, 83. \tt (use typewriter type), 13, 53, 113, 165, 340–341, 351, 380–382, 414–415, 429. \ttfam, 351, 414–415. \ttglue, 414–415, 421. \ttraggedright, 356. TUGboat, vii, 425, 483. turtle commands, 390–391. Twain, Mark (= Clemens, Samuel Langhorne), 83, 451. two-column format, 257, 386–388, 417. two-line displays, 196. type size switching, 15, 408, 414–415. typefaces, 13, 17, 427. typewriter type, 13, 53, 165, 356, 420–421, 429. \u (breve accent), 52–53, 356. *\uccode, 41, 214, 271, 345, 348, 377, 394. *\uchyph, 273, 348, 454. umlaut accent (¨), see \", \ddot. unbreakable spaces, see ties. \uncatcodespecials, 380. \undefined, 384. undelimited parameters, 203–204, 376–377. Under atom, 158, 289, 443. \underbar, 244, 323, 353. \underbrace, 176, 225–226, 359. 479 480 Appendix I: Index underfull box, 29, 94, 238, 302–303, 397, 400, 417, 452. *\underline, 130–131, 141, 291, 443. underlined text, 178; see also \underbar. underscore (the character ‘_’), 38, 51, 128–130, 134, 165. *\unhbox, 120, 283, 285, 354, 356, 361, 399. *\unhcopy, 120, 283, 285, 353. hunit of measurei, 268, 270. units of measure, 57–61, 270. in formulas, 169. table, 57. *\unkern, 280. unmatched left brace, 216; see also runaways. *\unpenalty, 280. unset box, 240, 302–303. hunsigned dimeni, 270. hunsigned mudimeni, 270. hunsigned numberi, 269. *\unskip, 222–223, 280, 286, 313, 392, 418–419. *\unvbox, 120, 254, 282, 286, 354, 361, 363, 364, 392, 399, 417. *\unvcopy, 120, 282, 286, 361. \up, 408. \uparrow ( ↑ ), 146–147, 182, 359, 437. \Uparrow ( ⇑ ), 146–147, 359, 437. \upbracefill (| {z }), 225–226, 357. \updownarrow ( l ), 146–147, 359, 437. \Updownarrow ( m ), 146–147, 359, 437. \uplus ( ] ), 436. *\uppercase, 41, 215, 217, 279, 307, 345, 348, 374, 377, 394. uppercase letters, 9, 64, 268, 370. Greek, 127, 164, 434. roman numerals, 374. \upsilon ( υ ), 434, 483. \Upsilon ( Υ ), 434. Ursa Major, 389. User, Ben Lee, 74, 80, 100, 140, 164, 186, 187, 193, 221, 296, 410–411. \v (check accent), 52, 356. *\vadjust, 95, 105, 109, 110, 117, 259, 281, 317, 393, 454. *\valign, 249, 283, 285–286, 302, 335, 397. Vall´ ee Poussin, Charles Louis Xavier Joseph de la, 92. van der Waerden, Bartel Leendert, 92. van Leunen, Mary-Claire, 425. \varepsilon ( ε ), 128, 434. hvariable assignmenti, 276. variable family, 154, 289, 358–359. variables in formulas, 132, 358, 434–435; see also Ord atom. \varphi ( ϕ ), 128, 147, 434. \varpi ( ), 434. \varrho ( % ), 128, 434. \varsigma ( ς ), 434, 483. \vartheta ( ϑ ), 128, 434. *\vbadness, 272, 348, 397, 417. vbox (box with vertical list inside), 65. *\vbox, 65, 80–82, 103, 151, 193, 222, 278, 388–389. Vcent atom, 158, 290, 443. *\vcenter, 150–151, 159, 170, 193, 222, 242, 290, 361, 443. \vdash ( ` ), 436. . \vdots ( .. ), 177, 359. \vec (math accent: ~ x ), 135; see also \overrightarrow. vectors, 177, 199–201; see also \vec. \vee ( ∨ ), 133, 436. verbatim copying, 422–423. verbatim listing, 48, 380–382, 391, 420–421. \vert ( | ), 146–147, 150, 359, 438; cf. \mid. \Vert ( k ), 117, 146–147, 150, 359, 186. hvertical commandi, 286. vertical line (the character ‘|’), 52, 53, 132, 146–147, 171, 174, 438; see also vertical rules. vertical lists, 64, 110. vertical mode, 85–89, 267–283. hvertical mode materiali, 278. hvertical rulei, 281. vertical rules, 64, 151, 221–226, 285, 291, 392. hvertical skipi, 281. very loose lines, 97, 99. *\vfil, 71, 72, 111, 256, 281, 286, 417. *\vfill, 24, 25, 71, 72, 256–257, 281, 286. \vfilll, 72. *\vfilneg, 72, 111, 281, 286. \vfootnote, 117, 363. *\vfuzz, 274, 348. \vglue, 352, 408. vinculum, see \overline. virgule, see slash, 51. visible space, 3, 420, 429. *\voffset, 251, 252–253, 274, 342, 406. void, 120, 210. \[email protected], 347, 348. Voltaire, de (= Arouet, Fran¸cois Marie), 447. \vphantom, 178–179, 211, 321, 360.

Appendix I: Index

*\vrule, 64, 86, 151, 221–222, 224, 245–247, 281–282, 283, 357, 392, 420. *\vsize, 113–114, 251, 253, 255, 274, 340–341, 348, 400, 406, 413, 415, 417. *\vskip, 24, 71, 85, 191, 281, 286. *\vsplit, 124, 222, 259, 278, 397, 417. *\vss, 71, 72, 255, 281, 286. *\vtop, 81–82, 151, 222, 278, 333. Walter’s worksheet, 244. Walton, Izaak, 67. Watson, John Hamish, M.D., 401. *\wd, 120, 271, 388–389, 391, 417. \wedge ( ∧ ), 133, 436. Weierstrass p, see \wp. weird error, 298. Welsh, 239, 451. Westing, Arthur Herbert, 246. whatsits, 95, 110, 157, 226–229. \widehat (math accent: b x ), 136, 359, 433. \widetilde (math accent: e x ), 136, 359. widow lines, 104, 272, 398. widow words, 104. *\widowpenalty, 104, 113, 272, 348. width, 221, 224, 282, 337. width of a box, 63–67, 77, 80–82, 225. wiggle, see \sim. Winograd, Terry Allen, 425. Wischmeyer Ehlert, Clara Louise, 248. withdelims, 152, 156.

\wlog, 347. Wolfe [Holmes], Nero, 401. \wp ( ℘ ), 435. \wr ( o ), 436. wreath product, see \wr. *\write, 215, 216, 226–228, 254, 280, 346, 377, 422, 424. ×, see \times, \*. x-height, 54, 60, 433, 443, 445–447. *\xdef, 215–216, 275, 373, 418, 424. Xenophon, 239. \xi ( ξ ), 434, 447. \Xi ( Ξ ), 434. *\xleaders, 224. *\xspaceskip, 76, 274, 317, 356, 429, 433. \xyzzy, 379. *\year, 41, 273, 349, 406. Yellin, Frank Nathan, 401. \[email protected], 347, 348. \[email protected], 347, 348. \zeta ( ζ ), 434. 1/2, 67, 332. 1/2, in unslashed form, 141, 186. h4-bit numberi, 271. h8-bit numberi, 271, 276–278. h15-bit numberi, 271, 277, 289, 291. h27-bit numberi, 271, 289, 291.

Important works such as histories, biographies, scientific and technical text-books, etc., should contain indexes. Indeed, such works are scarcely to be considered complete without indexes. An index is almost invariably placed at the end of a volume and is set in smaller type than the text-matter. Its subjects should be thoroughly alphabetized. The compiling of an index is interesting work, though some authors are apt to find it tedious and delegate the work to others. The proofreader who undertakes it will find that it is splendid mental exercise and brings out his latent editorial capability. — ALBERT H. HIGHTON, Practical Proofreading (1926) Important references are given in boldface. Italicized numbers indicate fleeting references, whereas numbers in parentheses refer to mere implications or unwarranted extrapolations. Asterisks are used to identify particularly distasteful passages. — PROF. PETER SCHICKELE, The Definitive Biography of P. D. Q. Bach (1976)

481

(page 482)

J Joining the TEX Community

Appendix J: Joining the TEX Community This appendix is about grouping of another kind: TEX users from around the world have banded together to form the TEX Users Group (TUG), in order to exchange information about common problems and solutions. A newsletter/journal called TUGboat has been published since 1980, featuring articles about all aspects of TEX and METAFONT. TUG has a network of “site coordinators” who serve as focal points of communication for people with the same computer configurations. Occasional short courses are given in order to provide concentrated training in special topics; videotapes of these courses are available for rental. Meetings of the entire TUG membership are held at least once a year. You can buy TEX T-shirts at these meetings. Information about membership in TUG and subscription to TUGboat is available from {\obeylines \TeX\ Users Group P.O. Box 9506 Providence RI 02940\kern.05em-9506, USA. } Don’t delay, write today! That number again is TEX Users Group P.O. Box 9506 Providence RI 02940-9506, USA.

[The printer] should refuse to employ wandering men, foreigners who, after having committed some grievous error, can easily disappear and return to their own country. — HIERONYMUS HORNSCHUCH, ’Oρθoτ υπoγραφ´ ιας (1608) An author writing an article for publication in TUGboat is encouraged to create it on a computer file and submit it on magnetic tape. — BARBARA BEETON, \title How to Prepare a File \cr For Publication in TUGboat \cr (1981)

483

#### E-Book Information

• Volume Info: Volume A

• Year: 1,991

• Pages: 494

• Pages In File: 494

• Language: English

• Topic: 69

• Library: Ihtik

• Identifier: 9780201134476,0-201-13447-0

• Ddc: 686

• Org File Size: 3,212,050

• Extension: pdf

### Related Documents

Donald E. Knuth

Donald E. Knuth

Donald E. Knuth

##### The Texbook (computers & Typesetting Series, Volume A) [PDF]

Donald Ervin Knuth

Donald E. Knuth

Donald E. Knuth