AI Study Notebook AI-generated
The METAFONTbook
Donald Knuth
On this page
The METAFONTbook — Chapter-by-Chapter Outline
Author: Donald E. Knuth First published: 1986 (Addison-Wesley, as Volume C of Computers and Typesetting) Edition covered: The 2021 "Jubilee Edition" (Addison-Wesley), incorporating all changes from the TeX tune-up of 2021. The chapter structure and titles are identical across all printings since 1986; the jubilee edition is the most current. Earlier notable printings include the 2000 Millennium edition and a 2012 update that incorporated software changes from 2002 and 2007. ISBN 0-201-13444-6 (softcover), 0-201-13445-4 (hardcover).
Central thesis
METAFONT is a programming language whose purpose is not to describe the outline of a letterform but to encode the intelligence underlying that letterform — the designer's implicit knowledge about how each part of the character should respond to changes in size, resolution, weight, or style. A single METAFONT program can therefore generate not one font but an entire family of fonts, each adapted to specific conditions, by varying numerical parameters rather than re-drawing every glyph.
The book's organizing argument is that a typeface is best understood as a meta-design: a set of equations and constraints relating geometric quantities, from which specific instances are derived by choosing parameter values. This is what makes METAFONT a language for mathematical typography rather than a drawing tool. Curves are not drawn by specifying control points by hand; they are solved for from geometric constraints. Pen shapes, stroke widths, serif sizes, and even the degree of curvature in letter bowls are all named quantities that flow consistently through every character in the font.
Knuth introduces METAFONT not just as a reference tool but as a tutorial, structured so that a motivated reader can write a working font by Chapter 5 and understand the full language by Chapter 27. The book contains 462 exercises (with all answers in Appendix A), making it as much a course as a manual.
How can one capture, in mathematical terms, the intelligence that distinguishes a coherent typeface from a collection of arbitrary shapes?
Chapter 1 — The Name of the Game
Central question
What is METAFONT, and what does the "meta" prefix mean in the context of type design?
Main argument
From specific design to meta-design. A conventional type designer creates a fixed set of shapes — one drawing per character per size. Knuth argues that this approach throws away all the knowledge about why the shapes are what they are. A meta-font instead encodes that knowledge: it describes how a letter would change if the designer's underlying intentions changed, treating design choices as algebraic parameters rather than committed measurements.
The algebra of design. Simple algebraic relationships give METAFONT its generative power. If the stroke width of a roman letter is expressed as a fraction of the cap height, then changing one parameter adjusts every character in the font consistently. The chapter uses this idea to explain why leaving certain decisions as unknowns, to be resolved later by the system, is more powerful than specifying everything up front.
METAFONT in relation to TeX. The chapter positions METAFONT as the companion to TeX: TeX typesets documents, but the fonts it uses must come from somewhere. METAFONT produces those fonts — generating both bitmaps (GF files) and metric information (TFM files) that TeX needs. The design of Computer Modern, Knuth's own typeface for TeX, is the primary worked example throughout the book.
Readable conventions. Knuth signals the book's pedagogical style: every chapter ends with exercises, solutions appear in Appendix A, and difficult material is marked with arrows. The chapter establishes the invitation — the reader need not be a type designer or a mathematician to proceed, only willing to think precisely.
Key ideas
- The "meta" in METAFONT means a parameterized description rather than a fixed description.
- A meta-font is one program that generates many fonts by varying design parameters.
- Parametric design separates what the design is from which instance is rendered.
- Computer Modern (cmr10, cmr12, etc.) is Knuth's primary illustration of meta-font design in practice.
- METAFONT produces both bitmap output (GF/PK files) and font metric files (TFM) consumed by TeX.
- The book is structured as an incremental tutorial, with all 462 exercises answered in Appendix A.
Key takeaway
METAFONT's name captures its central claim: a font program encodes the intelligence of a design, not just one realization of it, giving designers a mathematical language for entire font families rather than individual bitmaps.
Chapter 2 — Coordinates
Central question
How does METAFONT specify the locations of points in a character outline?
Main argument
Cartesian coordinates and the z-notation. METAFONT works in a two-dimensional plane. Points are specified by pairs of coordinates (x, y). Knuth introduces the shorthand z1 = (x1, y1), z2 = (x2, y2), and so on — the z-notation — so that both the pair and its components are always available without explicit decomposition.
Mediation and interpolation. The mediation operator t[z1, z2] expresses a point that is fraction t of the way from z1 to z2. When t = 0, the result is z1; when t = 1, it is z2; when t = 1/2, it is the midpoint. This single construct replaces elaborate trigonometric formulas for proportional positioning and becomes one of the most-used operations in font design.
Vector arithmetic. Points can be added and subtracted as vectors, and scaled by numeric factors. The chapter shows how to describe the skeleton of simple shapes — a diagonal line, a horizontal bar, a simple polygon — using these operations, establishing the geometric vocabulary that every later chapter builds on.
First complete example: the hex symbol. Knuth works through a complete drawing of a hexagonal asterisk-like symbol, demonstrating how six symmetric points can be specified using mediation and rotation rather than explicit trigonometry. This establishes the pattern of worked examples that runs throughout the book.
Key ideas
- Points in METAFONT are pairs
(x, y)with the z-notationzk = (xk, yk)giving shorthand access. - The mediation operator
t[A, B]interpolates linearly between two points. - Vector addition, subtraction, and scalar multiplication are primitive operations.
- All coordinates in METAFONT are internally stored as fixed-point numbers in units of scaled points (sp), giving very fine resolution.
- The coordinate system has its origin at the lower-left of the character box; positive y goes up.
- Even at this early stage, Knuth encourages parameterizing point positions rather than hard-coding specific numbers.
Key takeaway
The coordinate chapter gives designers the vocabulary to place and relate points precisely, with the mediation operator providing a clean algebraic replacement for explicit proportional geometry.
Chapter 3 — Curves
Central question
How does METAFONT draw smooth curves, and what control does the designer have over their shape?
Main argument
Cubic Bézier curves via the recursive midpoint algorithm. METAFONT's curves are cubic Bézier splines. Rather than asking the designer to specify Bézier control points directly (which is not intuitive for letterform design), METAFONT accepts a sequence of points through which the curve should pass and computes the internal control points automatically. The underlying mathematics is derived from the principle that the "nicest" curve through a sequence of points minimizes a measure of curvature energy — an approach Knuth attributes to work by John Hobby.
The path operator ... Points connected by .. instruct METAFONT to find a smooth curve through them. The algorithm chooses directions and velocities at each knot so that the curve is as smooth as possible. Connecting the last point back to the first with ..cycle closes the path.
Tension. The tension parameter controls how tightly the curve is pulled toward the straight line between knots. The default tension is 1. Higher tensions produce a curve that hugs the chord more closely; lower tensions produce more loopy curves. tension infinity gives a straight line. The syntax is z1..tension 2..z2.
Curl. At the endpoints of an open path, the curl parameter controls the rate of change of direction. curl 1 (the default) gives a natural endpoint; curl 0 forces the curve to arrive tangent to the line from the preceding knot; curl infinity forces it in horizontally or vertically.
Explicit directions. The designer can override the algorithm's choice at any knot by specifying a direction in curly braces: {right}, {up}, {dir 45}, or {z2-z1}. This gives precise control over where the curve is heading at each specified point without requiring explicit Bézier control points.
Key ideas
- METAFONT curves are cubic Bézier splines, but specified through on-curve points rather than off-curve handles.
- The
..connector triggers the Hobby/Knuth algorithm to solve for smooth control points automatically. ..cyclecloses a path with C1 (smooth direction) continuity.- Tension governs how closely a curve segment approaches the straight line between its endpoints.
- Curl governs endpoint behavior on open paths.
- Curly-brace direction specifications override the automatic solver at any knot.
- The
--connector (two dashes) creates straight line segments.
Key takeaway
METAFONT's curve model lets designers think in terms of through-points and desired curvature behavior rather than low-level Bézier handles, with a built-in optimization algorithm filling in the geometric details.
Chapter 4 — Pens
Central question
How does METAFONT model the physical act of drawing with a pen, and how are different stroke qualities produced?
Main argument
The pen as a convex shape. In METAFONT, a pen is a convex polygon or ellipse. When a path is drawn with a pen, the result is the union of all copies of the pen shape translated to each point along the path — a kind of Minkowski sum. A circular pen produces strokes of uniform width; an elliptical pen produces strokes that vary in width depending on direction, mimicking a broad-edge calligraphy nib.
pickup and circular pens. The pickup pencircle scaled w command selects a circular pen of diameter w. Drawing any path with this pen produces strokes with uniform thickness w. The command draw z1..z2..z3 draws a curve of that uniform width.
fill and region-based drawing. Rather than drawing a stroke, fill colors the interior of a closed path. The unfill command erases a region by filling it with the background color, enabling donut-shaped regions (fill the outer boundary, unfill the inner hole).
The broad-edge pen and penpos. For authentic calligraphic strokes where width varies with direction, the chapter introduces penpos. The penpos1(b, theta) command defines two points — z1l (left edge) and z1r (right edge) — that are b apart at angle theta from the horizontal. Connecting the left-edge points and right-edge points separately and then filling the enclosed region produces strokes that naturally thicken on horizontal movements and thin on vertical ones, exactly as a broad-nib pen does.
penstroke. The penstroke command automates the penpos-based approach: it draws the left-edge path, connects it to the reversed right-edge path, and fills the result, producing a calligraphic stroke in one command.
Key ideas
- A METAFONT pen is a convex region; stroking a path sweeps that region along the path.
pickup pencircle scaled wselects a circular pen of widthw.fill pathfills the interior of a closed path;unfillpunches a hole.penposassigns width and angle at each named point, creating left and right edge points.penstrokedraws and fills a penpos-defined stroke automatically.- Pen shapes can be any convex polygon, not just circles or ellipses.
Key takeaway
METAFONT's pen model bridges mathematical curves and physical calligraphy: circular pens produce monolinear strokes while broad-edge penpos constructions generate the naturally varying widths of classical lettering.
Chapter 5 — Running METAFONT
Central question
How does a designer actually execute METAFONT, and what are the commands needed to produce visible output?
Main argument
Interactive and batch modes. METAFONT can be run interactively — the user types commands and sees immediate results — or in batch mode by providing an input file. The chapter explains the startup sequence: METAFONT loads a base (usually plain.mf), then processes a user file.
The mode and magnification setup. Before processing a font file, the designer typically sets two parameters: the mode (which describes the target output device — its resolution and write-white vs. write-black characteristics) and the magnification (how large the bitmaps should be relative to the design size). The command line mf '\mode=laserwriter; mag=1.0; \input myfont' is the standard incantation.
showit and shipit. During interactive design, showit displays the current character on the screen; shipit outputs the character to the GF file. The chapter emphasizes the distinction between proofing (high-resolution output for visual inspection of design details) and production running (device-specific bitmaps at the target resolution).
Design-size units vs. pixel units. METAFONT uses two unit systems. Sharped quantities (written w#, h#, etc.) are design-time measurements in printer's points or other device-independent units. At runtime these are converted to pixel units based on mode and magnification. The # suffix signals that a value belongs to the design space, not the rendered space. This separation is what allows one METAFONT source to generate correctly sized bitmaps at any resolution.
Output: GF and TFM files. Each run produces a GF file (Generic Font, containing bitmap images of each character) and a TFM file (TeX Font Metric, containing width, height, depth, italic correction, ligature, and kerning data). The GF file is converted to the more compact PK format by the gftopk utility.
Key ideas
- METAFONT reads a base file (
plain.mf) then a user input file. - Mode selects device parameters; magnification scales the design to the target size.
showitpreviews the current glyph on-screen;shipitwrites it to the GF file.- Sharped quantities (e.g.,
u#) are device-independent design units; unstarred quantities are pixel values. - METAFONT emits two output files per run: a GF bitmap file and a TFM metric file.
- The
gftopkprogram converts GF to the more compact PK format used by DVI drivers.
Key takeaway
Running METAFONT means choosing a device mode and magnification, then executing a program that simultaneously generates bitmaps for rendering and metric data for typesetting, with the two unit systems (design-time and pixel-time) cleanly separated by the # convention.
Chapter 6 — How METAFONT Reads What You Type
Central question
What are the lexical rules of METAFONT, and how does the system tokenize its input?
Main argument
Input categories. Every character in a METAFONT input file belongs to one of sixteen categories, ranging from letters, digits, and operators to comment markers and escape characters. The category assignments determine how the scanner breaks the input stream into tokens.
Tokens. METAFONT recognizes four kinds of tokens: symbolic tokens (strings of letters and underscores), numeric tokens (decimal fractions), string tokens (text between quote marks), and spark tokens (special single characters like =, ;, ,). Adjacent letters form a single symbolic token; adjacent digits and a decimal point form a numeric token; each punctuation character is its own spark.
Case sensitivity. METAFONT is case-sensitive in the sense that it distinguishes uppercase and lowercase letters in symbolic tokens. Z1 and z1 are different variable names.
Spaces and comments. Spaces between tokens are mostly insignificant (except to separate adjacent alphabetic tokens). The % character begins a comment that runs to the end of the line.
Lookahead and the input processor. Knuth describes how METAFONT's scanner performs one-character lookahead and uses a two-phase input processor: a first pass handles line ends and special characters, a second pass groups characters into tokens. This chapter lays the formal foundation for understanding why certain token combinations are valid and others produce errors.
Key ideas
- METAFONT input is divided into categories (letter, digit, operator, etc.) before tokenization.
- The four token types are: symbolic, numeric, string, and spark.
- Symbolic tokens are sequences of letters/underscores; they are case-sensitive.
%introduces a line comment.- Spaces separate tokens but are otherwise not significant.
- Understanding tokenization is essential for writing macro definitions that behave predictably.
Key takeaway
METAFONT's lexical rules are simple but precise: knowing how the scanner forms tokens explains why certain programming constructs work and others cause surprising errors.
Chapter 7 — Variables
Central question
What kinds of data can be stored in METAFONT variables, and how are they named and declared?
Main argument
Types. METAFONT has eight data types: numeric (fixed-point real numbers in the range approximately ±4096), pair (a point, i.e., a pair of numerics), path, pen, picture, transform, boolean, and string. A variable can hold any of these, and its type is determined by declaration.
Variable names and subscripts. Variable names can be compound: x1, x2, y.left, z[k] are all valid. The subscript notation z[k] generates a new variable for each numeric value of k, making it easy to define families of related points (e.g., z1 through z12 for twelve reference points in a glyph).
Declaration syntax. Variables must be declared before use (in a type-safe sense): numeric a, b; pair z1, z2; path p; etc. The plain METAFONT base pre-declares common variable families.
The whatever construct. The keyword whatever generates a fresh, anonymous numeric unknown — a powerful shortcut for introducing a dummy variable in an equation without naming it explicitly. This is used heavily in path intersection and constraint expressions.
Variable tokens vs. internal quantities. Some METAFONT names are internal quantities that affect the system's behavior rather than user-defined values (e.g., currentpen, currentpicture, tolerance). The chapter distinguishes these from ordinary user variables.
Key ideas
- METAFONT is strongly typed with eight data types: numeric, pair, path, pen, picture, transform, boolean, string.
- Subscripted variables (
z1,z[k]) allow families of related quantities. - Type declarations (
numeric,pair, etc.) must precede use. whateverintroduces an anonymous unknown useful in constraint equations.- Internal quantities control METAFONT's system behavior and have reserved names.
- Fixed-point arithmetic limits numeric values to approximately ±4096 with precision of 1/65536.
Key takeaway
METAFONT's type system and subscript notation give font designers a clean way to organize the dozens of reference points and design quantities needed to specify a complete character set.
Chapter 8 — Algebraic Expressions
Central question
How does METAFONT evaluate mathematical expressions, and what operators are available?
Main argument
Numeric expressions. METAFONT supports the standard arithmetic operators (+, -, *, /) on numeric values. It also provides a rich library of mathematical functions: sqrt, floor, ceiling, round, trigonometric functions (sind, cosd), and the abs and max/min operators. All arithmetic is fixed-point with approximately five decimal digits of precision.
Pair and path expressions. Operators apply to pairs component-wise: (1,2) + (3,4) = (4,6). Scalar multiplication scales both components: 2*(1,2) = (2,4). The rotated and scaled operators apply transformations directly within expressions: z1 rotated 45 rotates the vector z1 by 45 degrees.
String and boolean expressions. String concatenation uses &. Boolean expressions use =, <, >, <=, >=, <>, and the logical operators not, and, or.
Operator precedence. METAFONT has a strict precedence hierarchy among three levels of binary operators (primary, secondary, tertiary), with unary operators binding most tightly. Understanding this hierarchy is essential for writing expressions that behave as intended without excessive parentheses.
The mediation operator in expressions. The [t,u] mediation notation generalizes to expressions: t[a,b] means (1-t)*a + t*b for any pair of compatible values. Used heavily for interpolating between design extremes.
Key ideas
- Standard arithmetic (
+,-,*,/) plussqrt,floor,round, trig functions. - All numeric arithmetic is fixed-point; very large or very small values overflow.
- Pair arithmetic is component-wise; scalar multiples scale both components.
rotated,scaled,shiftedare built-in operators on pairs and paths.&concatenates strings;=tests equality on any type.- Operator precedence has three levels (primary, secondary, tertiary).
Key takeaway
METAFONT's expression language is a miniature algebra system tuned for geometric computation, providing both the familiar arithmetic operators and domain-specific operators like rotation and scaling directly in expression syntax.
Chapter 9 — Equations
Central question
How does METAFONT's equation-solver work, and why is it more powerful than simple assignment?
Main argument
The constraint-based programming model. The most distinctive feature of METAFONT is that the designer can state relationships among quantities rather than computing values imperatively. An equation like x1 + x2 = w (where w is known) leaves x1 and x2 as unknowns until another equation constrains them further. METAFONT maintains a system of linear equations and solves it incrementally as new equations are added.
Linear equations only. METAFONT's built-in solver handles linear equations in numeric unknowns. Nonlinear relationships must be expressed through explicit programs or approximations. Within this constraint, the solver is complete: any consistent linear system will eventually resolve all unknowns.
The equation accumulation process. When the designer writes x1 = x2 + 5, METAFONT notes the constraint. When later x2 = 10 is established, the system immediately propagates to determine x1 = 15. The designer can rely on this automatic propagation throughout a glyph program, listing constraints in any order.
Redundancy and inconsistency. If the same equation is stated twice (e.g., x1 = 5 and x1 = 5), METAFONT ignores the redundancy. If contradictory equations are given (x1 = 5 and x1 = 6), METAFONT reports an error. Slightly inconsistent equations (within the tolerance parameter) are accepted as approximately equal.
Design implications. This equation model allows font programs to specify geometric constraints declaratively — "the center of the stem is at the midpoint of the em-square," "the top of the ascender is twice the x-height" — letting the solver determine all coordinates rather than the designer computing them manually.
Key ideas
- METAFONT's
=operator adds a constraint to the equation system; it does not assign. - Any consistent linear system over numeric unknowns will be solved automatically.
- Constraints can be stated in any order; the solver propagates as new equations arrive.
- Redundant equations are accepted; inconsistent equations trigger an error.
- Near-inconsistencies within
toleranceare silently rounded. - The model encourages a declarative, geometry-first style of font programming.
Key takeaway
The equation system is METAFONT's most powerful and distinctive feature: designers state geometric relationships and let the solver compute actual coordinates, rather than hand-calculating every point position.
Chapter 10 — Assignments
Central question
When should a designer use assignment (:=) rather than equation (=), and what is the difference?
Main argument
Equation vs. assignment. The = operator adds a constraint that holds for the lifetime of the current scope. The := operator is an assignment that overwrites the current value of a variable unconditionally, even if the variable was previously known. The distinction is crucial: equations are for design constraints (which should remain consistent), while assignments are for procedural state changes (loop counters, accumulated values).
When to use each. If x1 is an unknown and the designer writes x1 := 5, the unknown is replaced with the value 5. If x1 was already known (say, 7), := changes it to 5 — something = would flag as an inconsistency. This makes := the appropriate operator for variables that change during computation (e.g., updating a running total in a loop).
Interaction with equations. Once a variable has been assigned with :=, it becomes a known value and can participate in equations for other unknowns. But assigning to a variable that is already entangled in a chain of linear equations may fail or produce unexpected results, because the solver has already incorporated that variable's dependency.
save and scoping. The save command, discussed more fully in Chapter 17, saves the current state of a variable so that := changes inside a group are undone when the group ends. This is the mechanism for local variables.
Key ideas
:=is imperative assignment; it overwrites the current value of any variable.=is a constraint declaration; it fails if inconsistent with existing constraints.- Use
=for geometric relationships that define a design; use:=for procedural values that change. - Assigning to a variable that is part of an unsolved equation system can cause subtle problems.
savecombined with:=provides true local variable semantics inside groups.
Key takeaway
The assignment/equation distinction reflects the two programming styles METAFONT supports: the declarative constraint-solving style for design geometry, and the imperative procedural style for control flow — each using a different operator for its natural purpose.
Chapter 11 — Magnification and Resolution
Central question
How does METAFONT scale a design to produce correctly sized bitmaps for a specific output device?
Main argument
Design size and pixel size. A METAFONT font file describes a typeface at an abstract design size (e.g., 10 points). The actual number of pixels per character depends on both the output device's resolution (pixels per inch) and the magnification factor that scales the design to the desired print size. The relationship is: pixels_per_em = resolution × design_size × magnification / 72.27.
Mode definitions. The output device is described by a mode, a set of METAFONT internal variables (primarily pixels_per_inch and blacker) set in a mode file. Common modes include proof (very high resolution for visual inspection), smoke (similar but inverted for use with black paper), and device-specific modes like laserwriter. Knuth refers users to the modes.mf file maintained by the METAFONT community for a comprehensive library of device modes.
Sharped vs. unsharped units. Design quantities are declared as sharped (w# := 0.5pt#), meaning they are in device-independent printer's points. At runtime, METAFONT multiplies sharped values by hppp (horizontal pixels per point) or vppp (vertical pixels per point) to obtain pixel values. This multiplication happens at the moment a sharped variable is converted to a plain numeric for the first time.
The beginchar macro. Every character definition begins with beginchar(code, w#, h#, d#), which sets the character's width, height, and depth in sharped (design-size) units and converts them to pixel dimensions. This macro is the bridge between the abstract design and the target device.
Proof mode for design work. During font development, running at proof resolution (typically 2601.72 dpi, giving 36 pixels per point) produces enlarged bitmaps suitable for inspecting subtleties of shape. Production runs at the target device's actual resolution.
Key ideas
- Magnification scales a design-size font to the actual bitmap size needed.
- The formula
pixels_per_em = resolution × design_size × magnification / 72.27governs output size. - Device modes (
laserwriter,proof,smoke) set resolution and device characteristics. - Sharped quantities are design-unit values; they convert to pixels via
hpppandvpppat runtime. beginchar(charcode, w#, h#, d#)begins each character definition and establishes its bounding box.- Proof mode produces high-resolution output for visual quality control during design.
Key takeaway
The magnification and mode system is the bridge between the abstract mathematical description in a METAFONT source file and the concrete pixel grids of real output devices, with sharped units ensuring that one source file correctly generates bitmaps at any resolution.
Chapter 12 — Boxes
Central question
How does METAFONT define and communicate the metric dimensions of a character — its width, height, depth, and italic correction — to TeX?
Main argument
The character box. Every character occupies a rectangular box defined by four dimensions: w (width, the horizontal advance), h (height, from the baseline to the top of the bounding box), d (depth, from the baseline down to the bottom), and ic (italic correction, used to adjust spacing when italic text is followed by upright text). These correspond to the internal METAFONT variables charwd, charht, chardp, and charic.
beginchar and endchar. The beginchar macro (at the start of each character) sets w, h, and d from the design-unit values passed as arguments. The endchar macro (at the end) ships the finished bitmap and writes the metric data to the TFM file. Everything drawn between beginchar and endchar contributes to the character's bitmap.
Baseline and coordinate origin. The coordinate origin (0,0) is at the lower-left of the character box, at the intersection of the baseline and the left edge. The right edge is at (w, 0). Ascenders extend above y = h; descenders below y = 0 (i.e., at negative y values, bounded by -d).
Italic correction. For italic and slanted fonts, the rightmost ink often extends beyond the width w. The italic correction ic stores this extra distance, allowing TeX to insert it between an italic letter and a following upright character (e.g., \textit{f}\/).
Font-wide parameters with fontdimen. Beyond per-character metrics, METAFONT can declare font-wide spacing parameters via the fontdimen command, storing values like x-height, quad width, inter-word spacing, and extra space in the TFM file's parameter table for TeX's typesetting algorithms to use.
Key ideas
- The four character dimensions are width (
charwd/w), height (charht/h), depth (chardp/d), and italic correction (charic/ic). beginchar(code, w#, h#, d#)opens a character definition and sets its box.endcharships the bitmap to the GF file and writes metrics to the TFM file.- The coordinate origin is at the baseline-left corner; ascenders use positive y, descenders negative y.
fontdimenwrites font-wide spacing parameters (x-height, em-size, etc.) to the TFM file.
Key takeaway
The character box is the interface between METAFONT's drawing commands and TeX's typesetting algorithms: four numbers per character tell TeX how much space each glyph occupies and how to position adjacent characters.
Chapter 13 — Drawing, Filling, and Erasing
Central question
What are the fundamental commands for placing ink on a character's bitmap, and how do they combine?
Main argument
draw and fill. The two primary rendering commands are draw (stroke a path with the current pen) and fill (fill the interior of a closed path). draw moves the pen shape along the path; fill colors all pixels inside the closed curve. For a circular pen of width zero, draw is equivalent to fill on a closed path.
undraw and unfill. The erasure counterparts are undraw (erase along a path with the current pen) and unfill (erase the interior of a closed path). These set pixels to background (white) rather than foreground (black). This enables composite shapes: fill an outer region, then unfill an inner cutout.
filldraw and unfilldraw. These commands combine stroking and filling: filldraw fills the interior and draws the outline simultaneously, useful for shapes with a filled interior and a separate outline thickness. The result is slightly different from filling and drawing in sequence because the pen extends slightly outside the filled region.
cutdraw and clipping. METAFONT provides clipping operations that restrict drawing to the interior of a region, allowing partial fills and masking effects.
addto for picture combination. For complex characters built from multiple strokes, the addto command combines picture variables, allowing a designer to build up a character in stages and then assemble the pieces.
Key ideas
draw pathstrokes the path with the current pen;fill closedpathfills the interior.undrawandunfillerase rather than draw, enabling cutout shapes.filldrawcombines fill and draw in one command.- Pictures can be accumulated with
addto, allowing modular character construction. - Drawing order matters: later operations overwrite earlier ones on the same pixel.
- The current pen (set by
pickup) determines stroke width for alldrawcommands.
Key takeaway
METAFONT's drawing model is a pixel-based layered system: fill and draw commands place ink; undraw and unfill remove it; and the sequence of operations determines the final bitmap.
Chapter 14 — Paths
Central question
What is the full path syntax of METAFONT, and how are complex curves and compound paths constructed?
Main argument
Path construction operators. A path in METAFONT is a sequence of points (or sub-paths) connected by one of several joining operators: -- (straight line), .. (smooth curve via the automatic algorithm), ... (ultra-smooth curve with relaxed endpoint conditions), and --- (for joining with a given direction). These can be freely mixed in a single path expression.
The automatic direction algorithm in depth. Chapter 3 introduced the .. operator; Chapter 14 examines it more carefully. The algorithm (due to John Hobby) finds directions at each knot that minimize a curvature energy functional, producing curves that look like they were drawn by a skilled drafter. The details of how tension and curl modify this algorithm are worked out fully.
Sub-path extraction. The subpath (t1, t2) of p expression extracts the portion of path p between parameter values t1 and t2. This is the key operation for trimming curves, computing intersections, and building complex composite paths.
Path length and time. Every path has a parametric time running from 0 to length p (the number of segments). The point t of p expression evaluates the position at time t; direction t of p gives the tangent direction; penoffset d of q gives the appropriate offset of pen q in direction d.
Intersection. The intersectiontimes operator returns the times at which two paths cross. Combined with subpath, this enables building paths that end exactly at an intersection — critical for constructing overlapping strokes and compound shapes.
Building complex outlines. The chapter shows how to combine subpaths, reversed paths (reverse p), and direction-controlled connections to build the outline of a complete letterform from smaller geometric pieces.
Key ideas
--gives straight segments;..gives smooth Bézier curves;...gives super-smooth curves.subpath (t, u) of pextracts a portion of a path by parameter time.point t of panddirection t of pevaluate position and tangent at timet.intersectiontimesfinds where two paths cross, returning the time on each.reverse preverses the parametric direction of a path.length preturns the number of Bézier segments in a path.
Key takeaway
The full path calculus — construction, extraction, intersection, and direction queries — gives METAFONT designers a complete toolkit for specifying exactly the curve shapes that letterform design demands.
Chapter 15 — Transformations
Central question
How does METAFONT apply geometric transformations (rotation, scaling, translation, slanting) to paths and pictures?
Main argument
The transform type. A transformation in METAFONT is an affine mapping of the plane: it can translate, rotate, scale (uniformly or non-uniformly), shear, and reflect. Internally it is a six-element matrix (t1, t2, t3, t4, t5, t6) representing the standard 2×3 affine transform matrix.
Shorthand operators. METAFONT provides readable operators for common transformations:
shifted (dx, dy)— translation by(dx, dy).scaled s— uniform scaling by factors.xscaled sx/yscaled sy— non-uniform scaling in x or y.rotated theta— rotation bythetadegrees counter-clockwise.slanted s— horizontal shear (x += s*y), the standard way to produce italic fonts from roman programs.reflected about (z1, z2)— reflection across the line fromz1toz2.zscaled z— complex multiplication byz, combining rotation and scaling.
Composing transformations. Transformations can be composed by the transformed operator: p transformed (t1 transformed t2) applies t1 first, then t2. This enables building up complex motions from elementary ones.
Transforming points and paths. Any pair or path expression can be followed by a transformation operator. z1 rotated 90 gives the point 90° counter-clockwise from z1. p scaled 0.5 shrinks path p by half. Applying transformations within expressions (rather than as separate assignment steps) keeps programs concise.
Application to font design: slant. The most important practical use of transformations in METAFONT is slanted s for producing italic or oblique variants of a roman font. By slanting all paths by a factor s = tan(angle), the roman program generates an oblique family member without separately defining every character.
Key ideas
- Transformations are affine maps with six parameters.
- Shorthand operators:
shifted,scaled,xscaled,yscaled,rotated,slanted,reflected,zscaled. rotated thetais counter-clockwise bythetadegrees.slanted sapplies a horizontal shear: x_new = x + s*y.- Transformations compose:
transformed (t1 transformed t2). - Any path, pair, or picture can be transformed directly in an expression.
Key takeaway
METAFONT's transformation system lets a single glyph description generate multiple design variants — slanted for italic, scaled for different sizes, reflected for symmetry — turning geometric operations into font-design shortcuts.
Chapter 16 — Calligraphic Effects
Central question
How does METAFONT produce the variable-width strokes of traditional calligraphy, where stroke thickness depends on direction?
Main argument
The skeleton and the broad nib. Traditional broad-edge calligraphy is built on a concept well-suited to METAFONT: the designer draws the skeleton (the central path of a stroke) and the pen (a broad ellipse or polygon at a fixed angle) determines the actual ink boundary. Where the skeleton goes horizontal, the full width of the nib appears; where it goes vertical, only the nib's thin dimension shows.
penpos in depth. Each penpos call defines a point on the skeleton together with a pen width and angle at that point. penpos1(b, theta) sets z1l (the left edge of the stroke at point 1) and z1r (the right edge), each offset by b/2 from z1 in the direction perpendicular to angle theta. The skeleton point z1 is implicitly the midpoint between z1l and z1r.
Building the fill region. After placing penpos points along the entire stroke, the designer draws the left-edge path (z1l..z2l..z3l) and the right-edge path, connects the two ends, and fills the resulting closed region. This produces a stroke whose width varies naturally because different skeleton segments have different penpos widths.
Thick-thin contrast. The defining aesthetic of broad-edge calligraphy — thick horizontals, thin verticals — emerges automatically from a fixed nib angle (say 30°) applied consistently. Changing the nib angle globally shifts the entire weight distribution across the alphabet, producing different calligraphic styles from the same skeleton data.
The penstroke shorthand. The penstroke command takes a path defined in terms of penpos points and automatically constructs the filled outline: it draws the left-edge path, appends the reversed right-edge path, and fills the whole. This makes calligraphic strokes as easy to write as simple curves.
Key ideas
- Broad-edge calligraphy is modeled as a skeleton path traced by an angled nib.
penpos k(b, theta)places left and right edge points atzkwith breadthband nib angletheta.- The left-edge path (
zklpoints) and right-edge path (zkrpoints) are drawn separately and filled. - Thick-thin contrast arises from the nib angle: the stroke is thickest perpendicular to the nib angle.
penstrokeautomates the construction: draw penpos-based path → auto-fill.- This approach underlies Knuth's Computer Modern roman letters.
Key takeaway
METAFONT's calligraphic model encodes the craft knowledge of the broad-edge pen algebraically: the skeleton captures where the designer's hand moves, the penpos angle and breadth capture how the nib produces ink, and the fill region captures the visible stroke.
Chapter 17 — Grouping
Central question
How does METAFONT manage local scope, and how can the designer make temporary changes that are automatically undone?
Main argument
begingroup and endgroup. METAFONT's grouping construct wraps a sequence of statements in a scope boundary. Any variables saved inside a group revert to their previous state when the group ends. Groups can be nested, and they are the fundamental mechanism for local variable management in macros.
The save command. Within a group, save x pushes the current value (and type) of variable x onto a stack. At the end of the enclosing group, x is restored to the saved value. Without save, assignments inside a group persist after the group ends.
Groups as expressions. In METAFONT, begingroup ... expr endgroup evaluates to the value of expr. This is one of the most powerful features: a group can compute an intermediate value, make temporary changes to global state, and return a result — all in a single expression. This is how macros return values (see Chapter 18).
Interaction with equations. Equations established inside a group are not saved and restored — only variable bindings are. This means a constraint stated inside a group persists globally. Designers must be careful not to state permanent constraints inside groups that they expect to be scoped.
clearxy, cleardraw, and related resets. Several plain-base utility macros use grouping internally to save and restore the equation environment (clearxy clears all pending x/y equations) or the picture state (cleardraw resets the current drawing). These are implemented via groups and save.
Key ideas
begingroup ... endgroupcreates a local scope.save xinside a group causesxto revert to its pre-group value when the group ends.- A group can return a value:
begingroup ... value endgroupis an expression. - Equations established inside a group persist globally (only variable bindings are restored).
- Grouping is the foundation of macro local variables.
- Groups can be nested to arbitrary depth.
Key takeaway
METAFONT's grouping system provides the local scope that macro programming requires: save inside begingroup/endgroup ensures that macros can use internal variables without polluting the global namespace.
Chapter 18 — Definitions (also called Macros)
Central question
How does METAFONT define reusable named operations (macros), and what parameter-passing modes are available?
Main argument
def and its parameter types. A METAFONT macro is defined with def name params = body enddef. Parameters are enclosed in parentheses and can be of three kinds: expression parameters (expr a) receive the value of any expression; suffix parameters (suffix s) receive a variable name (useful for subscript-generating macros); and text parameters (text t) receive an arbitrary token sequence, unevaluated.
vardef for variable-like macros. When a macro should behave like a variable (participate in subscript notation, be on the left side of an equation), it is defined with vardef rather than def. vardef z@# = (x@#, y@#) enddef makes every zk (for any subscript k) expand to the pair (xk, yk).
Operator-level macros. Four additional definition forms create macros that behave like operators at specific precedence levels: primarydef, secondarydef, tertiarydef, and def with the of keyword. These allow the designer to invent new infix operators like rotatedaround or reflectedabout.
Delimited and undelimited parameters. Parameters can be delimited (enclosed in explicit brackets) or undelimited (absorbing tokens freely). Undelimited parameters grab tokens according to strict syntactic rules and are used for operator-style macros.
Recursive macros. METAFONT macros can be recursive. A macro that calls itself enables algorithms like recursive subdivision for drawing fractals or tree-like structures.
Key ideas
def name (params) = body enddefdefines a macro with typed parameters.- Parameter types:
expr(value),suffix(variable name),text(token sequence). vardefmakes macros behave like subscriptable variable families.primarydef,secondarydef,tertiarydefdefine infix operators at specified precedence levels.- Macros can be recursive.
- The body is wrapped in an implicit group, providing local scope for internal variables.
Key takeaway
METAFONT's macro system is a full procedural abstraction facility: typed parameters, operator-level definitions, recursive calls, and grouping combine to let designers build layered libraries of reusable font-design operations.
Chapter 19 — Conditions and Loops
Central question
How does METAFONT implement conditional execution and iteration?
Main argument
if/elseif/else/fi. METAFONT's conditional is if boolean_expr: ... elseif boolean_expr: ... else: ... fi. The elseif chain replaces nested if statements. Like all METAFONT control structures, the conditional can appear inside expressions and macro bodies.
for loops. A for loop iterates a variable over a range or list: for k = 1 upto n: ... endfor iterates k from 1 to n; for k = 0 step 0.1 until 1: ... endfor provides explicit step control. The loop variable is local to the loop body.
forsuffixes loops. forsuffixes s = a, b, c: ... endfor iterates a suffix parameter over a list of variable names, making it easy to apply the same operation to a list of named points.
forever and exitif. An unconditional forever: ... endfor loop repeats indefinitely until an exitif condition statement triggers, at which point the loop exits. This is METAFONT's while loop.
Loop bodies as token sequences. METAFONT loops do not execute in the usual procedural sense — they expand textually at read-time (in METAFONT's case, during interpretation). This means loops can generate path syntax, equation sequences, or other token patterns that are then evaluated, giving them unusual power for path construction.
Key ideas
if ... elseif ... else ... fiis the conditional;elseifchains replace nesting.for k = a upto b: ... endforiterates with step 1.for k = a step s until b: ... endforprovides arbitrary step.forsuffixes s = name, name, ...: ... endforiterates over variable names.forever: ... exitif cond; ... endforis the while-loop pattern.- Loop bodies can generate METAFONT syntax tokens, enabling path-building loops.
Key takeaway
METAFONT's control flow is minimal but sufficient: if/fi for conditionals, three flavors of for for iteration, and forever/exitif for open-ended loops — all of which can appear inside expressions and macros.
Chapter 20 — More About Macros
Central question
What advanced macro techniques does METAFONT support, and how are they used in the plain base?
Main argument
Lookahead and scanning. Some METAFONT primitives scan their argument list with lookahead before deciding how to interpret it. The chapter explains how METAFONT's two-phase input processing (first pass converts the input stream to tokens; second pass parses and executes) interacts with macro expansion, giving macros the ability to conditionally absorb different amounts of input depending on what follows.
The scantokens primitive. scantokens takes a string and re-processes it as METAFONT token input, effectively allowing runtime code generation. This is the mechanism behind some of the more sophisticated plain-base macros that construct variable names dynamically.
expandafter. The expandafter token causes the following macro to be expanded before the token preceding it is processed. This enables advanced macro sequencing that would otherwise be impossible given METAFONT's single-pass token processing.
Building the plain base. Chapter 20 examines how the plain.mf base file is constructed: it defines beginchar, endchar, penpos, penstroke, and dozens of utility macros using the techniques from Chapters 17–19. Understanding the plain base demystifies the many macros that appear automatically available in every METAFONT program.
Style and the let command. The let command gives a new name to an existing token without copying the macro body. This allows the designer to rebind primitives or create aliases. Combined with def, let enables careful management of the base namespace.
Key ideas
scantokens stringre-processes a string as METAFONT input, enabling code generation.expandaftercontrols macro expansion order for advanced sequencing.- The plain base (
plain.mf) is itself a METAFONT program that defines the standard library. let new = oldcreates a new name for an existing macro or primitive.- Most
plain.mfmacros are implemented usingdef,vardef,save, and grouping. - Understanding the plain base is the key to writing efficient, portable METAFONT programs.
Key takeaway
Advanced METAFONT macro programming — scantokens, expandafter, let — gives the designer the tools to build sophisticated meta-programming abstractions, and the chapter reveals how these tools underlie the plain base that every METAFONT programmer already uses.
Chapter 21 — Random Numbers
Central question
How does METAFONT generate random numbers, and what design uses do they serve?
Main argument
The uniformdeviate function. uniformdeviate x returns a pseudo-random number uniformly distributed in the interval [0, x). This is the building block for all other randomness in METAFONT: random displacements, random sizes, and random choices.
The normaldeviate function. normaldeviate returns a random number drawn from an approximately normal (Gaussian) distribution with mean 0 and standard deviation 1, generated by the ratio method. This is useful for simulating the natural variation of handwritten letterforms — jitter that follows a bell-curve distribution rather than being uniformly random.
randomseed. The random sequence is determined by the internal variable randomseed. Setting randomseed := n reproduces the same sequence, enabling repeatable designs. Each METAFONT run automatically initializes randomseed to a different value, so two runs of the same program produce different random outputs unless the seed is fixed.
Design applications. The chapter discusses using randomness to add controlled imperfection to fonts (simulating typewriter irregularity, distressed type, or hand-lettering) and to automate exploration of a design space (generating many random variations of a parameterized font for design experiments).
Key ideas
uniformdeviate xproduces a random real number in[0, x).normaldeviateproduces a Gaussian random number (mean 0, std 1).randomseedsets the seed; the same seed reproduces the same sequence.- Random numbers enable simulation of handwriting variation and typewriter imperfection.
- Randomness can drive design exploration: generating many parameterized variants automatically.
Key takeaway
METAFONT's random number facilities add controlled stochasticity to a system otherwise devoted to precise geometric constraint — useful for simulating natural letterform variation and for automated design exploration.
Chapter 22 — Strings
Central question
What is the string data type in METAFONT, and how are strings used in font programming?
Main argument
String literals and operations. A string in METAFONT is a finite sequence of ASCII characters, written in double quotes: "Hello". Strings are concatenated with &: "ab" & "cd" = "abcd". The length s function returns the number of characters; substring (i, j) of s extracts characters from position i to j-1.
ASCII conversion. The ASCII s function returns the ASCII code of the first character of string s as a number. The inverse char n converts an ASCII code back to a single-character string. These functions allow METAFONT programs to iterate over character codes and generate systematic glyph definitions.
Font labeling. The primary use of strings in font design is to label characters with their names and to set font-identification variables like font_identifier, font_coding_scheme, font_extra_space. These string values appear in the TFM file's header and identify the font to downstream software.
show and diagnostic strings. The show command outputs a value to the log file or terminal for debugging. show z1 shows a pair; show "hello" shows a string. String formatting via & decimal n (converting a number to its string representation) is the main way to produce informative debug output.
Key ideas
- Strings are sequences of ASCII characters in double quotes.
&concatenates strings;length,substring,ASCII,charare the main operations.ASCII "A"returns 65;char 65returns"A".- Font identification strings (
font_identifier,font_coding_scheme) appear in the TFM header. show exprwrites values to the log for debugging.- String operations enable systematic iteration over character codes in font programs.
Key takeaway
Strings in METAFONT serve two distinct purposes: font identification (labeling the output TFM file for downstream software) and debugging (producing diagnostic output during development).
Chapter 23 — Online Displays
Central question
How can a designer see METAFONT's output interactively during a design session?
Main argument
Screen windows. METAFONT supports on-screen display of glyph images during an interactive session. The display picture on window command renders a picture in a numbered screen window, allowing the designer to observe the current state of a character without waiting for a full GF file to be produced and converted.
showit and shipit. The showit command (from the plain base) calls the screen display mechanism for the current character. The shipit command finalizes the character and adds it to the output GF file. A typical interactive design loop involves alternating between modifying equations, calling showit to preview, and eventually calling shipit to commit.
System dependencies. Online display is inherently system-dependent: it requires METAFONT to be compiled with support for the host windowing system (historically X Window System on Unix). On systems without window support, showit is a no-op. The chapter is careful to note that the online display facility is optional — the core language runs identically with or without it.
numspecial and the display protocol. METAFONT communicates with the display system via special and numspecial commands that embed instructions in the output stream. These can also carry information to post-processing programs (e.g., gftodvi for hardcopy proofs).
Key ideas
display picture on wshows a picture in screen windoww.showit(plain base) displays the current character;shipitcommits it to the GF file.- Online display requires system-specific windowing support; it is optional.
special stringandnumspecial nembed directives in the GF file for post-processors.- Interactive design loop: modify →
showit→ adjust →shipit.
Key takeaway
Online displays close the feedback loop between mathematical specification and visual result, though the facility is system-dependent and the language functions identically without it.
Chapter 24 — Discreteness and Discretion
Central question
How does METAFONT manage the transition from the continuous mathematical world of its equations to the discrete pixel grid of real output?
Main argument
The fundamental tension. METAFONT's geometry is continuous — paths are cubic curves, coordinates are real numbers — but output bitmaps are discrete grids of on/off pixels. Naive conversion of continuous geometry to pixels produces distracting irregularities: strokes that should be symmetric look slightly different on each side; stems that should align with the grid straddle pixel boundaries.
"Good" x and y values. Knuth introduces the concept of "good" coordinates: integers or half-integers that, when converted to pixels, land exactly on pixel boundaries. Designing characters so that critical points fall on good values ensures that symmetrical features are rendered symmetrically and that strokes have consistent pixel widths.
hround and vround. The hround and vround macros round a value to the nearest half-integer in the horizontal or vertical direction respectively, adjusting for the blacker parameter of the current mode. These are used in every serious METAFONT font to ensure that stem widths and heights come out to exact pixel counts.
Stochastic rounding and flex. For features that should not snap to the pixel grid (e.g., curves that pass smoothly through a region), the chapter discusses flex, which adds sub-pixel perturbations to reduce the visual effect of pixel-grid rounding on smooth curves.
Resolution independence and its limits. While METAFONT's parametric approach is resolution-independent in principle, the rounding adjustments are not — they depend on the current mode's hppp and vppp. A font that looks good at 300 dpi may need different hround/vround values than one at 600 dpi. This is why the sharped/unsharped unit distinction from Chapter 11 is essential.
Key ideas
- Continuous geometry must be mapped to a discrete pixel grid, introducing rounding decisions.
- "Good" coordinates are integers or half-integers that align with pixel boundaries.
hround xandvround ysnap values to the nearest half-integer, compensating forblacker.- The
blackermode parameter adjusts how much ink pixels are darkened for a given device. flexadds small perturbations to smooth curves to reduce pixel-grid artifacts.- Proper discretization requires mode-specific adjustment, so fonts should use
hround/vroundthroughout.
Key takeaway
The chapter on discreteness is where abstract mathematics meets physical printing reality: producing fonts that look correct at real device resolutions requires deliberate rounding decisions built into every design, not just mathematical precision.
Chapter 25 — Summary of Expressions
Central question
What is the complete formal syntax of METAFONT expressions?
Main argument
This chapter is a reference summary rather than a tutorial. It systematically enumerates every form of expression in the METAFONT language, organized by type and precedence level. The chapter covers:
Primary expressions: literals (numeric, pair, string), variable references, function applications (sqrt, floor, abs, ASCII, char, decimal, length, etc.), parenthesized expressions, and group expressions.
Secondary expressions: primary expressions modified by unary operators at the secondary level (transformed, scaled, shifted, rotated, slanted, etc.).
Tertiary expressions: secondary expressions combined by binary operators (+, -, *, /, **, & for string concatenation, path concatenation operators).
Boolean expressions: comparisons (=, <>, <, >, <=, >=), containment tests (known, unknown, numeric, pair, etc.), and logical connectives (not, and, or).
The summary includes the formal grammar rules that resolve precedence and ambiguity, making this chapter the definitive reference for writing expressions that behave exactly as intended.
Key ideas
- The chapter organizes all expression forms by type and precedence level.
- Three precedence levels (primary, secondary, tertiary) plus boolean expressions.
- Every operator is listed with its operand types and result type.
- This chapter is the reference companion to Chapters 8 and 15.
- Formal grammar rules resolve ambiguity for edge cases.
Key takeaway
Chapter 25 is the language reference for expressions — the authoritative specification that disambiguates every edge case in METAFONT's rich expression syntax.
Chapter 26 — Summary of the Language
Central question
What is the complete formal syntax of the METAFONT language, including all statement forms and program structure?
Main argument
This is the full language reference chapter, companion to Chapter 25. It enumerates all statement types, program-level constructs, and the full grammar:
Statements: equation, assignment, declaration, path drawing commands (draw, fill, undraw, unfill), display, show, save, let, interim, newinternal, and erasing.
Program structure: a METAFONT program is a sequence of statements separated by semicolons. Special statements for font production include beginchar/endchar, fontdimen, ligtable, charlist, extensible, and special/numspecial.
The ligtable command. One of the most important statements for font production, ligtable specifies ligature and kerning information: which pairs of characters should be replaced by ligatures (e.g., f + i → fi) and how much extra or reduced space should be inserted between specific character pairs (kerning). This data is written directly into the TFM file and used by TeX's typesetting algorithms.
charlist and extensible. charlist specifies a chain of successively larger variants of a character (e.g., three sizes of a left parenthesis). extensible specifies how a character can be built up from top, middle, bottom, and repeated components to any desired size (e.g., an arbitrarily tall left brace). Both commands write data to the TFM file.
Key ideas
- All statement forms are enumerated: equations, assignments, drawing commands, declarations, font commands.
ligtablespecifies ligatures and kern pairs, both written to the TFM file.charlistspecifies size variants of a character;extensiblespecifies arbitrarily tall characters.fontdimensets global font parameters (x-height, em-width, etc.) in the TFM header.- The full grammar resolves every syntactic ambiguity.
Key takeaway
Chapter 26 is the complete language reference for METAFONT programs, covering every statement form from simple equations to the font-metric commands that connect METAFONT output to TeX's typesetting engine.
Chapter 27 — Recovery from Errors
Central question
When METAFONT reports an error, what does each diagnostic mean and how should the designer respond?
Main argument
METAFONT's error handling philosophy. METAFONT, like TeX, is designed to recover from errors and continue processing rather than aborting at the first problem. When an error occurs, METAFONT prints a diagnostic message identifying the problem, shows the relevant input context, and offers the user a chance to insert correction tokens, delete tokens, or continue.
Categories of errors. The chapter organizes METAFONT's error messages into categories: syntax errors (malformed expressions or statements), type errors (wrong type of argument), equation inconsistencies (contradictory constraints), overflow errors (values exceeding the fixed-point arithmetic range), and font errors (bad character codes, inconsistent metric data).
Reading the error output. Knuth explains METAFONT's error message format: the ! prefix, the message text, the l.N line number, the ...context... excerpt showing where in the input the error was detected, and the ? prompt for interactive recovery commands.
Interactive recovery. At the ? prompt, the designer can type ? for help, press <return> to continue, type I token to insert a token, type D to enter the debugger, E to open the editor at the error location, or X to quit. This interactive recovery model follows TeX's philosophy and uses the same command set.
erasing mode. The erasing picture variable is set to a mode in which all drawing operations are erased rather than drawn — a useful debugging technique to see the structure of a design without its ink.
Key ideas
- METAFONT recovers from errors and continues rather than aborting.
- Error messages include
!prefix, message text, line number (l.N), and input context. - Interactive recovery:
?for help,<return>to continue,Ito insert tokens,Xto quit. - Common error categories: syntax, type mismatch, equation inconsistency, overflow.
- Equation inconsistency errors mean two contradictory constraints were stated; check for typos.
- Overflow usually means a coordinate exceeded approximately ±4096 scaled points.
Key takeaway
METAFONT's error recovery system follows TeX's philosophy of resilient continuation: the designer is given full diagnostic context and interactive options to correct mistakes without restarting from scratch.
The book's overall argument
- Chapter 1 (The Name of the Game) — establishes the meta-font concept: a font is a parameterized design, not a fixed set of bitmaps, and encoding the designer's intelligence algebraically is more powerful than encoding specific shapes.
- Chapter 2 (Coordinates) — introduces the geometric vocabulary: Cartesian coordinates, the z-notation for points, the mediation operator for interpolation, and vector arithmetic as the foundation of all geometric description.
- Chapter 3 (Curves) — adds smooth curves to the vocabulary: METAFONT's automatic cubic-Bézier algorithm, tension and curl for controlling shape at knots and endpoints, and explicit direction overrides.
- Chapter 4 (Pens) — introduces the pen model: circular pens for monolinear strokes, fill/unfill for region rendering, and the penpos/penstroke calligraphic model for variable-width broad-edge strokes.
- Chapter 5 (Running METAFONT) — explains the practical execution environment: modes, magnification, sharped units, the GF/TFM output files, and the interactive design workflow.
- Chapter 6 (How METAFONT Reads What You Type) — establishes the lexical rules: token categories, symbolic/numeric/string/spark tokens, and the two-phase input processor.
- Chapter 7 (Variables) — defines the type system: eight data types, subscripted variable families, the
whateveranonymous unknown. - Chapter 8 (Algebraic Expressions) — presents the expression language: arithmetic, geometric operators, operator precedence, and mediation as a unifying interpolation tool.
- Chapter 9 (Equations) — introduces the constraint-solving engine: linear equations accumulate, the solver propagates, redundancy is tolerated, inconsistency is flagged — enabling a declarative style of font programming.
- Chapter 10 (Assignments) — clarifies the equation/assignment distinction:
=declares a persistent constraint;:=overwrites imperatively — each suited to a different programming style. - Chapter 11 (Magnification and Resolution) — connects the abstract design to real devices: magnification, mode definitions, sharped-unit conversion via
hppp/vppp, and thebegincharmacro. - Chapter 12 (Boxes) — defines the character box: four dimensions (
charwd,charht,chardp,charic) written to the TFM file, plus font-widefontdimenparameters. - Chapter 13 (Drawing, Filling, and Erasing) — presents the full rendering command set:
draw,fill,undraw,unfill,filldraw,addto— with pixel-layering semantics. - Chapter 14 (Paths) — provides the full path calculus: joining operators, sub-path extraction, path-time queries, intersection, and the operations for constructing complex letterform outlines.
- Chapter 15 (Transformations) — adds the affine geometry toolkit:
shifted,scaled,rotated,slanted,reflected— enabling font variants from a single source. - Chapter 16 (Calligraphic Effects) — makes broad-edge calligraphy systematic:
penposassigns breadth and angle;penstrokegenerates the filled outline; variable stroke width emerges naturally from the nib model. - Chapter 17 (Grouping) — provides local scope:
begingroup/endgroupwithsavefor temporary variable states, and groups-as-expressions for value-returning sequences. - Chapter 18 (Definitions) — presents the full macro system:
def/vardefwith typed parameters (expr,suffix,text), operator-level definitions, and recursive macros. - Chapter 19 (Conditions and Loops) — adds control flow:
if/fi, threeforvariants, andforever/exitif— all expressible inside macro bodies and path expressions. - Chapter 20 (More About Macros) — covers advanced macro techniques:
scantokens,expandafter,let, and the plain base as a worked example of large-scale METAFONT programming. - Chapter 21 (Random Numbers) — introduces stochasticity:
uniformdeviateandnormaldeviatefor controlled imperfection and automated design exploration. - Chapter 22 (Strings) — covers the string type: concatenation, substring, ASCII conversion, and the font-identification string variables written to the TFM header.
- Chapter 23 (Online Displays) — closes the interactive feedback loop:
display/showitfor on-screen preview,special/numspecialfor GF file annotations. - Chapter 24 (Discreteness and Discretion) — resolves the continuous/discrete tension: "good" coordinates,
hround/vroundfor pixel-grid alignment, andblackerfor device-specific ink adjustment. - Chapter 25 (Summary of Expressions) — provides the formal expression grammar: every operator organized by type and precedence level.
- Chapter 26 (Summary of the Language) — provides the complete language grammar: all statement forms plus font-metric commands (
ligtable,charlist,extensible). - Chapter 27 (Recovery from Errors) — completes the practical guide: how to read METAFONT's diagnostics and use interactive error recovery.
Common misunderstandings
Misunderstanding: METAFONT is a drawing program like Illustrator or Inkscape.
METAFONT is a programming language for describing fonts through mathematical constraints and equations. It has no graphical interface. The designer writes programs whose output is bitmaps and metrics, not interactive vector drawings.
Misunderstanding: METAFONT and TeX are the same thing.
TeX is a typesetting engine for documents. METAFONT is a font description language for producing the bitmap fonts and metric files that TeX consumes. They are companion systems designed together but entirely separate in function.
Misunderstanding: METAFONT equations work like programming assignments.
METAFONT's = operator declares a constraint in a linear equation system; it does not compute a value left-to-right. x1 = x2 + 5 is a relationship that binds both variables simultaneously, not an instruction to compute x1 from x2. This is the most fundamental conceptual shift the book asks of readers with programming backgrounds.
Misunderstanding: METAFONT produces scalable outline fonts (PostScript/TrueType).
METAFONT produces bitmap (raster) fonts at a specified resolution. It does not produce PostScript Type 1 or TrueType outline fonts directly. The system is mathematically parametric at the source level (the program can be re-run at any resolution), but each run produces fixed bitmaps rather than device-independent outlines.
Misunderstanding: Knuth intended METAFONT to replace human type designers.
Knuth's meta-font concept was about encoding a designer's intelligence, not replacing it. The parametric model requires a skilled designer to define the parameter space; once defined, the computer can generate consistent instances, but the creative design decisions remain human.
Misunderstanding: Computer Modern uses only a few parameters.
Computer Modern is governed by over 60 distinct design parameters per style variant — controlling stem width, serif length, x-height, superness of bowls, dot shape, and many more subtleties. The parametric model is not a simplification of the design; it is an articulation of all the design choices that a skilled type designer makes implicitly.
Central paradox / key insight
METAFONT's deepest insight is that a font is a program, not a picture.
The conventional way to create a typeface is to draw each character individually — a process that encodes the designer's decisions in the final shapes but discards the reasoning behind those decisions. Knuth observed that this is exactly analogous to writing a numerical program by inlining all the constants rather than declaring variables: the result works for one case but cannot be adapted.
The meta-font concept inverts this: instead of storing the results of design decisions, store the decisions themselves as equations and parameters. The computer then derives the specific shapes by solving the equations — just as a compiler derives machine code from source. The font is the program; the bitmaps are the compiled output.
This leads to the central paradox: a METAFONT source file does not describe any specific font — it describes infinitely many fonts, one for each valid assignment of parameter values and mode settings. Computer Modern Roman 10pt at 300 dpi and Computer Modern Roman 12pt at 600 dpi are both outputs of the same source program, run with different parameters. The source is, in Knuth's phrase, a meta-font.
"If you give a man a fish, he can eat for a day. If you teach a man to fish, he can eat for a lifetime. If you write a METAFONT program for a fish, all the fish in the sea are yours." — paraphrasing Knuth's analogy between recipe generalization and parametric font design.
Important concepts
Meta-font
A font program parameterized by design variables, capable of generating entire families of specific font instances by varying those parameters. The opposite of a fixed glyph description.
GF file (Generic Font)
METAFONT's primary bitmap output format: a run-length encoded file containing the pixel images of all shipped characters, annotated with size information. Converted to the compact PK format by gftopk for use by DVI drivers.
TFM file (TeX Font Metric)
The metric output file produced by every METAFONT run: contains per-character width, height, depth, and italic correction, plus font-wide spacing parameters (fontdimen), ligature/kern data (ligtable), and header information. Read by TeX to lay out text without needing the bitmaps.
Sharped units (#)
Design-size quantities declared in device-independent printer's points. A variable w# stores the abstract design value; at runtime METAFONT multiplies by hppp to obtain pixels. Enables one METAFONT source to generate correctly scaled output at any resolution.
Mode
A set of METAFONT parameters characterizing an output device (resolution in pixels per inch, write-white vs. write-black, blacker value). Specified before running a font program; determines how sharped units convert to pixels and how the output bitmaps should be inked.
Mediation operator (t[A, B])
Linear interpolation: produces the point fraction t of the way from A to B. 0[A,B] = A, 1[A,B] = B, 1/2[A,B] = midpoint. Generalizes to any pair of compatible values (numbers, pairs, paths).
Tension
A parameter controlling how closely a Bézier curve segment follows the chord between its endpoints. Default tension = 1 gives the natural smooth curve; higher tensions pull the curve toward the straight line; tension infinity gives a straight segment.
Curl
A parameter controlling the curvature of a Bézier curve at an open-path endpoint. curl 1 (default) gives a natural end; curl 0 gives a zero-curvature (flat) end; curl infinity forces a horizontal or vertical tangent.
penpos
A macro that places left and right edge points for a broad-edge calligraphic stroke at a named skeleton point. penpos k(b, theta) sets zkl and zkr at distance b/2 from zk in the direction perpendicular to angle theta.
ligtable
A METAFONT statement that specifies ligature replacements (e.g., f+i → fi) and kern adjustments (small extra or reduced spaces between specific character pairs) for the TFM file. Used by TeX's line-breaking and character-spacing algorithms.
Hround / vround
Macros that round a design-unit value to the nearest half-integer pixel coordinate, adjusting for the device's blacker parameter. Used throughout serious METAFONT fonts to ensure stems and other critical features land on pixel boundaries.
beginchar / endchar
The plain-base macros that delimit each character definition. beginchar sets the character code and box dimensions; endchar ships the bitmap to the GF file and writes metrics to the TFM file.
Computer Modern
The typeface family designed by Knuth using METAFONT as the default font for TeX. Governed by over 60 design parameters per variant; the primary worked example throughout The METAFONTbook demonstrating what parametric font design achieves in practice.
References and Web Links
Primary book and edition information
- Knuth, Donald E. Computers and Typesetting, Volume C: The METAFONTbook. Addison-Wesley, 1986. ISBN 0-201-13444-6 (softcover).
METAFONT source (mfbook.tex) — the canonical chapter/appendix list
- mfbook.tex on CTAN (Utah mirror) — the TeX source of The METAFONTbook itself; chapter and appendix titles verified here.
Background and overview
- Metafont — Wikipedia — overview of METAFONT's history, relationship to TeX, and technical characteristics.
- Computers and Typesetting — Wikipedia — edition history and series overview.
- History of TeX and METAFONT creation (HistoryofInformation.com)
The concept of a meta-font
- Knuth, Donald E. "The Concept of a Meta-Font." Visible Language 16(1), 1982.
Technical documentation and tutorials
- METAFONT for Beginners (Geoffrey Tobin, CTAN) — introductory tutorial covering practical use.
- Chapter 11: Introducing MetaFont, from Making TeX Work (Norman Walsh) — practical guide to running METAFONT and managing modes/magnification.
- Metafont examples (Andries Brouwer, TU/e) — worked examples of METAFONT code.
- Some METAFONT Techniques (TUGboat paper)
- Font utilities — Proofing with METAFONT — explains proof mode and hardcopy proof generation.
TeX font metrics (TFM)
- TeX font metric — Wikipedia — formal description of TFM file format, ligature/kern table structure, and extensible characters.
Computer Modern and parametric font design
- Computer Modern — Wikipedia — description of the typeface designed with METAFONT.
- Parametric type design in the era of variable and color fonts (arXiv 2025) — contemporary research situating METAFONT within the history of parametric type.
- CTAN Computer Modern source files — the actual METAFONT source for Computer Modern.
TeX Users Group
- TeX Users Group (TUG) — the community organization referenced in Appendix J; publishes TUGboat.
- 25 Years of TeX and METAFONT (TUGboat keynote) — retrospective on the systems' impact.