Algorithmadvanced
TeX math layout algorithm
Also called TeX Appendix G algorithm.
Lay out a formula by turning a math list into boxes recursively, with styles that shrink sub and superscripts and font parameters for their shifts.
- Time
- Θ(n) worst · best
- Space
- O(n) extra
- Where
- n = the number of nodes of the formula
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Full proofCode in 1 languages
- Origin
- Donald E. Knuth, 1984
The math layout algorithm of TeX turns a formula, given as a tree of atoms, into a box of a known width, height and depth. It works from the inside out: it sets the parts of a fraction or the scripts of a symbol first, in a smaller style, and then places them with shifts that come from font parameters, such as the height of a superscript or the gap above a fraction bar. Each rule moves the parts apart until fixed clearances hold, so that a superscript never touches a subscript and a numerator never touches the bar. TeX uses its own rules and the parameters of its math fonts, not the shaping rules of OpenType or the Unicode text algorithms; see text shaping for that other model.
In plain words
A formula is built from small pieces. For , the 2 is printed smaller and higher than the x. For a fraction, the top part goes above a bar and the bottom part below it.
The algorithm builds the inner pieces first, so it knows how big they are. Then it decides how far up or down to move each piece. The font gives the normal distances. If two pieces would come too close, the algorithm pushes them apart.
Pieces inside other pieces get smaller, but only down to a smallest size, so that they stay readable.
The problem
A formula here is a tree with four kinds of nodes:
- a character, with a width, height and depth from the font;
- a row, a sequence of formulas set side by side;
- a fraction with a numerator, a denominator and a rule thickness (the default thickness of the font, or 0 for
\atop); - scripts: a nucleus with a superscript, a subscript or both.
The style is one of (display, text, script and scriptscript), each in a normal and a cramped form (, , , ). Cramped styles raise superscripts less; they are used under a bar and in subscripts. With the styles numbered , , up to , TeX computes the style of each part with integer arithmetic:
| part | style | example |
|---|---|---|
| superscript | , , | |
| subscript | , | |
| numerator | , , | |
| denominator | , |
and use the text size of the font, the script size and the scriptscript size. The font gives, for each size, the parameters named (x-height), to (num1, num2, num3, denom1, denom2), to (sup1, sup2, sup3, sub1, sub2), and (sup_drop, sub_drop) and (the axis height, the height of the fraction bar), and the rule thickness . The output is a box with its width, height and depth, and the shift up of the numerator or superscript and the shift down of the denominator or subscript.
The algorithm
The layout of a character is its box, and the layout of a row puts the boxes of its parts side by side. Scripts use rule 18 of appendix G (lines L1 to L12) and fractions use rule 15 (lines L13 to L20), each after the layout of its parts in their styles. Here means the parameter at the size of the current style .
SCRIPTS(nucleus box z, superscript, subscript, style s)- 1
if the nucleus is a single character then u ← 0; v ← 0 - 2
else t ← the size of the scripts; u ← h(z) − sup_drop(t); v ← d(z) + sub_drop(t) - 3
if there is no superscript then - 4
x ← the subscript set in sub(s), plus the script space - 5
v ← max(v, sub1, h(x) − 4σ5/5); return z followed by x lowered by v - 6
x ← the superscript set in sup(s), plus the script space - 7
u ← max(u, sup3 if s is cramped, else sup1 if s = D, else sup2, d(x) + σ5/4) - 8
if there is no subscript then return z followed by x raised by u - 9
y ← the subscript set in sub(s), plus the script space; v ← max(v, sub2) - 10
c ← 4ξ8 − ((u − d(x)) − (h(y) − v)) - 11
if c > 0 then v ← v + c; c ← 4σ5/5 − (u − d(x)); if c > 0 then u ← u + c; v ← v − c - 12
return z followed by x raised by u over y lowered by v FRACTION(numerator, denominator, θ, style s)- 13
if θ is the default then θ ← ξ8 - 14
x ← the numerator set in num(s); z ← the denominator set in denom(s); center the narrower one - 15
if s is D or D' then u ← num1; v ← denom1 else v ← denom2; u ← num2 if θ ≠ 0, else num3 - 16
if θ = 0 then c ← 7ξ8 if s is D or D', else 3ξ8; δ ← half(c − ((u − d(x)) − (h(z) − v))); if δ > 0 then u ← u + δ; v ← v + δ - 17
else c ← 3θ if s is D or D', else θ; δ ← half(θ) - 18
δ1 ← c − ((u − d(x)) − (σ22 + δ)); if δ1 > 0 then u ← u + δ1 - 19
δ2 ← c − ((σ22 − δ) − (h(z) − v)); if δ2 > 0 then v ← v + δ2 - 20
return x raised by u, a rule of thickness θ on the axis, z lowered by v, with null delimiters on both sides
Line L2 hangs the scripts of a big nucleus, such as a fraction, from its top and bottom, instead of from the baseline. Lines L10 and L11 keep at least between the superscript and the subscript, and they push the subscript down first, since a high superscript looks worse. Lines L18 and L19 keep a clearance between each part and the bar, and the bar is centered on the axis, so fractions line up with the minus sign and the plus sign. Here half is rounded up for odd , as in TeX.
Example
The font of this example is a toy font with made-up values in units of 0.1 point, loosely in the range of a 10 point font: x-height 43, sup1 41, sup2 36, sup3 29, sub1 15, sub2 25, , and script space 5. The characters x, 1 and 2 have heights 43, 64 and 64 at text size, and the script size is 7/10 of that, so a script 1 or 2 has height 44.
| formula | style | first , | gap | final , |
|---|---|---|---|---|
| 36 | ||||
(sup3) |
29 | |||
| 15 | ||||
| 36, 25 | 36, 25 | |||
| 29, 25 | 34, 26 |
In the last row, line L11 first moves the subscript down by 6, to . The bottom of the superscript is then at 29, below , so both scripts move up by 5: and . The gap stays 16. In the text style the superscript is high enough already.
For in style , with num2 39, denom2 34, axis height 25 and : the clearances to the bar are and , both at least , so and , and the box has height and depth 34. In style the same fraction uses num1 and denom1 and its parts are set in and at text size, so it is much taller.
Correctness
The style formulas give the table of The TeXbook, which can be checked on all eight styles. The box of a script stack has height and depth , because the kern between the scripts is chosen to make the gap exact; this is the box that TeX builds. Each correction step only adds to a gap: line L11 adds the missing amount to the gap between the scripts and then moves both scripts by the same amount, and lines L16, L18 and L19 add the missing amount (or twice half of it) to a gap to the bar. So the clearances hold at the end. The recursion is on proper subformulas, so it ends. The full proof is in the proof file below.
Proof: The script and fraction rules give the boxes and clearances of TeXfull
We use the formulas, the styles and the pseudocode of the page. The styles are numbered , , , , , , , , so a style is cramped exactly when its number is odd. Write for the default rule thickness, for the x-height and for the axis height of the current size. A box has a width , a height above the baseline and a depth below it. A box raised by has its top at and its bottom at ; a box lowered by has its top at and its bottom at .
Lemma 1 (the styles). The formulas of the page, , , and , give the table of The TeXbook: a superscript of or is set in , of or in , cramped when the style is cramped; a subscript is set in the cramped form of the same style as the superscript; a numerator of is in , of in , of or in , cramped when the style is; a denominator is the cramped form of the numerator style.
Proof. There are eight styles, and the four formulas can be evaluated on each. For , , so , which is or , and . For , and . For , keeps the parity and moves one size class down; for it is . is with the parity bit set, since is with the parity bit set.
Lemma 2 (the sizes of the result). For scripts with both parts, the result is the nucleus followed by a box of width , height and depth ; with only a superscript, the box raised by ; with only a subscript, the box lowered by . For a fraction, the result has height , depth and width , where is the null delimiter space. These are the boxes that TeX builds.
Proof. With both scripts, TeX stacks , a kern and , and lowers the stack by . The stack has height and depth , so after the shift its height is and its depth is . For a fraction, TeX sets the height of the stack to and its depth to directly. Each null delimiter is an empty box of width , height 0 and depth 0, moved so that its center is on the axis, which is a shift up by ; it reaches the height and the depth . The width and the other cases are sums and maxima of the parts.
Lemma 3 (the clearances). Let be the superscript and the subscript, both set. After line L11, the gap between the bottom of the superscript and the top of the subscript is at least . For a fraction with a rule of thickness and in display styles, otherwise, after lines L18 and L19 the gap between the bottom of the numerator and the top of the rule, , and the gap between the bottom of the rule and the top of the denominator, , are both at least . For , after line L16 the gap is at least in display styles and otherwise.
Proof. Scripts: let be the gap before line L10 and . If , nothing changes and . If , line L11 adds to , which adds to the gap, so it becomes . The second step adds the same amount to and subtracts it from , which leaves the gap the same. Rule: line L18 adds to when , and the first gap is before it, so it is after it. Line L19 changes only and so does not undo this, and the same argument gives the second gap. No rule: let be the gap and . If then , since , so . If , both shifts grow by , the gap grows by , and so it is . Here for odd and for even , so for all integers .
Theorem. The layout terminates on every formula. Its boxes have the sizes of Lemma 2, its scripts and fractions use the styles of Lemma 1, and they satisfy the clearances of Lemma 3. With the same font parameters, these are the sizes and shifts that rules 15 and 18 of The TeXbook, appendix G, give for formulas with these parts.
Proof. Each call of the layout on a formula calls itself only on its proper subformulas (the parts of a row, the numerator and the denominator, the nucleus and the scripts), so the recursion depth is at most the height of the formula tree, and it terminates. The rest follows from Lemmas 1 to 3, since each line of the pseudocode is the step of rule 15 or rule 18 with the same name (15a to 15d and 18a to 18f) and computes the same shifts from the same parameters of the current size, and of the script size for the drops.
Complexity. Each node of the formula is laid out once, by its parent, and each rule does work besides the calls on its parts, or for a row of parts. So the time is for a formula with nodes, and the extra space is the recursion depth, in the worst case.
Complexity
Each node is laid out once by its parent, with work per fraction and per script node and for a row of parts. So the time is for a formula with nodes. The extra space is the depth of the recursion, in the worst case and the nesting depth of the formula in general.
Properties
- Bottom-up. A part is set before its parent, so the parent knows its size.
- Local. The shifts of one node depend only on its parts and the font, not on the rest of the line. This is why a formula can be broken across lines only at its top level.
- Driven by parameters. The rules are fixed and a font designer tunes the layout through the parameters. The plain TeX values of
\scriptspaceand\nulldelimiterspaceare design choices. - Three sizes only. Scripts of scripts stay at scriptscript size, so deep nesting does not make text unreadably small.
Variants and improvements
- The full appendix G. TeX also has rules for the spacing between atoms by class (ordinary, operator, binary, relation, and others), large operators with limits, radicals, accents, delimiters that grow with their content, and italic corrections. This page leaves them out.
- The MATH table of OpenType. OpenType fonts can carry a table of math constants and glyph variants that plays the role of the TeX parameters, so that systems such as LuaTeX, XeTeX and word processors can lay out math with any font that has it.
- MathML. Browsers that render MathML use layout rules that follow the same ideas: styles that shrink, shifts from font constants, and minimum gaps.
When to use it
Use it to set formulas in a typesetting system, or to compute the size of a formula before you place it in a line. With an OpenType math font, read the parameters from its MATH table; with a TeX font, read them from the font metric files. For plain text with occasional exponents, the superscript feature of the font is simpler.
Pitfalls
- The size of the parameters. Most parameters come from the size of the current style, but
sup_dropandsub_dropcome from the size of the scripts. Mixing them up moves scripts on fractions and parenthesized groups. - A character nucleus. Scripts on a single character are placed from the baseline, not from its top and bottom; only a box nucleus uses the drops.
- Cramped styles. Forgetting to cramp the denominator and the subscripts makes exponents in denominators too high.
- Rounding. TeX computes in integer scaled points with its own half and div. Floating point can give results that differ from TeX by one unit.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tex-math-layout/. The authors are listed in prov/7WJTT8.jsonl.
"""Two rules of the math layout of TeX: scripts (rule 18) and fractions (rule 15).
This follows The TeXbook, appendix G, and TeX: The Program, parts 35 and
36 (make_scripts and make_fraction), for a small part of math: single
characters, horizontal lists of atoms, fractions with null delimiters,
and sub and superscripts. It leaves out the spacing between atoms
(rule 20), italic corrections (taken as 0), large operators, radicals,
accents and delimiters of variable size.
The font is a toy font. Its character sizes and its parameters are made
up for this page, loosely in the range of a 10 point font in units of
0.1 pt; they are not the values of any real font. All sizes are ints, and
// stands for the div of Pascal, which agrees with it on the values used
here (the only signed division is half, written to match TeX).
"""
from dataclasses import dataclass, field
from typing import Optional, Union
# ----------------------------------------------------------------- styles
D, D_, T, T_, S, S_, SS, SS_ = range(8) # display, text, script, scriptscript; _ is cramped
STYLE_NAMES = ["D", "D'", "T", "T'", "S", "S'", "SS", "SS'"]
TEXT_SIZE, SCRIPT_SIZE, SCRIPT_SCRIPT_SIZE = 0, 1, 2
def cramped(s: int) -> bool:
return s % 2 == 1
def size_of(s: int) -> int:
"""The font size of a style: D and T use text size, S script size, SS scriptscript size."""
return max(0, s // 2 - 1)
def sub_style(s: int) -> int:
return 2 * (s // 4) + S + 1
def sup_style(s: int) -> int:
return 2 * (s // 4) + S + (s % 2)
def num_style(s: int) -> int:
return s + 2 - 2 * (s // 6)
def denom_style(s: int) -> int:
return 2 * (s // 2) + 1 + 2 - 2 * (s // 6)
def half(x: int) -> int:
"""half of TeX: (x + 1) div 2 for odd x, x div 2 for even x."""
return (x + 1) // 2
# ------------------------------------------------------------- the toy font
_TEXT_CHARS = { # made up: (width, height, depth) at text size
"x": (57, 43, 0),
"y": (49, 43, 19),
"a": (53, 43, 0),
"b": (43, 69, 0),
"n": (60, 43, 0),
"1": (50, 64, 0),
"2": (50, 64, 0),
}
_TEXT_PARAMS = { # made up, named as in TeX: sigma 5 and sigma 8 to sigma 22
"x_height": 43,
"num1": 68,
"num2": 39,
"num3": 44,
"denom1": 69,
"denom2": 34,
"sup1": 41,
"sup2": 36,
"sup3": 29,
"sub1": 15,
"sub2": 25,
"sup_drop": 39,
"sub_drop": 5,
"axis_height": 25,
}
_SCALE = [(1, 1), (7, 10), (5, 10)] # text, script and scriptscript sizes
def _scaled(v: int, size: int) -> int:
a, b = _SCALE[size]
return v * a // b
CHARS = [{c: tuple(_scaled(v, z) for v in dims) for c, dims in _TEXT_CHARS.items()} for z in range(3)]
PARAMS = [{k: _scaled(v, z) for k, v in _TEXT_PARAMS.items()} for z in range(3)]
RULE_THICKNESS = 4 # xi 8, default_rule_thickness, the same at all sizes here
SCRIPT_SPACE = 5 # \scriptspace
NULL_DELIMITER_SPACE = 12 # \nulldelimiterspace
# ------------------------------------------------------------ formulas and boxes
@dataclass(frozen=True)
class Char:
c: str
@dataclass(frozen=True)
class Row:
"""A horizontal list of atoms, set side by side with no spacing."""
items: tuple
@dataclass(frozen=True)
class Frac:
num: object
den: object
thickness: Optional[int] = None # None is the default rule thickness, 0 is \atop
@dataclass(frozen=True)
class Scripts:
nucleus: object
sup: object = None
sub: object = None
Formula = Union[Char, Row, Frac, Scripts]
@dataclass
class Box:
"""A box with its width, height and depth. info keeps the shifts u and v."""
width: int
height: int
depth: int
info: dict = field(default_factory=dict)
def layout(f: Formula, s: int) -> Box:
"""The box of the formula f set in the style s."""
if isinstance(f, Char):
w, h, d = CHARS[size_of(s)][f.c]
return Box(w, h, d)
if isinstance(f, Row):
boxes = [layout(g, s) for g in f.items]
return Box(sum(b.width for b in boxes), max((b.height for b in boxes), default=0), max((b.depth for b in boxes), default=0))
if isinstance(f, Frac):
return make_fraction(f, s)
if isinstance(f, Scripts):
return make_scripts(f, s)
raise TypeError("not a formula")
def make_scripts(f: Scripts, s: int) -> Box:
"""Rule 18: attach a superscript, a subscript or both to the nucleus."""
z = layout(f.nucleus, s)
p = PARAMS[size_of(s)]
if f.sup is None and f.sub is None:
return z
if isinstance(f.nucleus, Char): # @line L1
u = v = 0
else: # @line L2
t = SCRIPT_SIZE if s < S else SCRIPT_SCRIPT_SIZE
u = z.height - PARAMS[t]["sup_drop"]
v = z.depth + PARAMS[t]["sub_drop"]
if f.sup is None: # @line L3
x = layout(f.sub, sub_style(s)) # @line L4
x.width += SCRIPT_SPACE
v = max(v, p["sub1"], x.height - abs(p["x_height"] * 4) // 5) # @line L5
return Box(z.width + x.width, max(z.height, x.height - v), max(z.depth, x.depth + v), {"u": None, "v": v})
x = layout(f.sup, sup_style(s)) # @line L6
x.width += SCRIPT_SPACE
if cramped(s): # @line L7
clr = p["sup3"]
elif s == D:
clr = p["sup1"]
else:
clr = p["sup2"]
u = max(u, clr, x.depth + abs(p["x_height"]) // 4)
if f.sub is None: # @line L8
return Box(z.width + x.width, max(z.height, x.height + u), max(z.depth, x.depth - u), {"u": u, "v": None})
y = layout(f.sub, sub_style(s)) # @line L9
y.width += SCRIPT_SPACE
v = max(v, p["sub2"])
clr = 4 * RULE_THICKNESS - ((u - x.depth) - (y.height - v)) # @line L10
if clr > 0: # @line L11
v += clr
clr = abs(p["x_height"] * 4) // 5 - (u - x.depth)
if clr > 0:
u += clr
v -= clr
w = max(x.width, y.width) # @line L12
return Box(z.width + w, max(z.height, x.height + u), max(z.depth, y.depth + v), {"u": u, "v": v})
def make_fraction(f: Frac, s: int) -> Box:
"""Rule 15: a fraction with a rule of thickness theta and null delimiters."""
p = PARAMS[size_of(s)]
theta = RULE_THICKNESS if f.thickness is None else f.thickness # @line L13
x = layout(f.num, num_style(s)) # @line L14
z = layout(f.den, denom_style(s))
w = max(x.width, z.width)
display = s < T
if display: # @line L15
u, v = p["num1"], p["denom1"]
else:
v = p["denom2"]
u = p["num2"] if theta != 0 else p["num3"]
axis = p["axis_height"]
if theta == 0: # @line L16
clr = 7 * RULE_THICKNESS if display else 3 * RULE_THICKNESS
delta = half(clr - ((u - x.depth) - (z.height - v)))
if delta > 0:
u += delta
v += delta
else: # @line L17
clr = 3 * theta if display else theta
delta = half(theta)
delta1 = clr - ((u - x.depth) - (axis + delta)) # @line L18
if delta1 > 0:
u += delta1
delta2 = clr - ((axis - delta) - (z.height - v)) # @line L19
if delta2 > 0:
v += delta2
# The null delimiters are empty boxes on the axis: they add width, and the
# height axis and the depth -axis, which rarely matter.
height = max(x.height + u, axis) # @line L20
depth = max(z.depth + v, -axis)
return Box(w + 2 * NULL_DELIMITER_SPACE, height, depth, {"u": u, "v": v, "theta": theta, "delta": delta})
def parse(text: str) -> Formula:
"""A tiny parser for tests and examples: characters, {groups}, ^, _ and \\frac{a}{b}."""
pos = 0
def atom():
nonlocal pos
if text.startswith("\\frac", pos):
pos += 5
a = group()
b = group()
return Frac(a, b)
if text.startswith("\\atop", pos):
pos += 5
a = group()
b = group()
return Frac(a, b, 0)
if text[pos] == "{":
return group()
c = text[pos]
pos += 1
return Char(c)
def group():
nonlocal pos
if text[pos] != "{":
return atom()
pos += 1
items = []
while text[pos] != "}":
items.append(scripted())
pos += 1
return items[0] if len(items) == 1 else Row(tuple(items))
def scripted():
nonlocal pos
nuc = atom()
sup = sub = None
while pos < len(text) and text[pos] in "^_":
op = text[pos]
pos += 1
arg = atom()
if op == "^":
sup = arg
else:
sub = arg
return Scripts(nuc, sup, sub) if sup is not None or sub is not None else nuc
items = []
while pos < len(text):
items.append(scripted())
return items[0] if len(items) == 1 else Row(tuple(items))
test_tex_math_layout.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tex-math-layout/. The authors are listed in prov/7WJTT8.jsonl.
import random
from tex_math_layout import (
CHARS,
D,
D_,
PARAMS,
RULE_THICKNESS,
S,
S_,
SS,
SS_,
T,
T_,
Char,
Frac,
Row,
Scripts,
cramped,
denom_style,
half,
layout,
num_style,
parse,
size_of,
sub_style,
sup_style,
)
def test_style_tables():
# The TeXbook, chapter 17: the styles of superscripts, subscripts, numerators and denominators.
assert [sup_style(s) for s in range(8)] == [S, S_, S, S_, SS, SS_, SS, SS_]
assert [sub_style(s) for s in range(8)] == [S_, S_, S_, S_, SS_, SS_, SS_, SS_]
assert [num_style(s) for s in range(8)] == [T, T_, S, S_, SS, SS_, SS, SS_]
assert [denom_style(s) for s in range(8)] == [T_, T_, S_, S_, SS_, SS_, SS_, SS_]
assert [size_of(s) for s in range(8)] == [0, 0, 0, 0, 1, 1, 2, 2]
for s in range(8):
assert cramped(sub_style(s)) and cramped(denom_style(s))
assert cramped(sup_style(s)) == cramped(s)
def test_half_matches_tex():
assert [half(x) for x in (-4, -3, -2, -1, 0, 1, 2, 3, 4)] == [-2, -1, -1, 0, 0, 1, 1, 2, 2]
def test_toy_font_sizes():
assert CHARS[0]["2"] == (50, 64, 0)
assert CHARS[1]["2"] == (35, 44, 0)
assert CHARS[1]["y"] == (34, 30, 13)
assert PARAMS[1]["sup_drop"] == 27 and PARAMS[1]["sub_drop"] == 3
def dims(b):
return (b.width, b.height, b.depth)
def test_superscript_on_a_character():
b = layout(parse("x^2"), T)
assert b.info["u"] == 36 # sup2, since T is neither display nor cramped
assert dims(b) == (57 + 35 + 5, 44 + 36, 0)
assert layout(parse("x^2"), D).info["u"] == 41 # sup1
assert layout(parse("x^2"), T_).info["u"] == 29 # sup3
def test_subscript_alone():
b = layout(parse("x_1"), T)
assert b.info["v"] == 15 # sub1 beats 44 - 4 * 43 / 5 = 10
assert dims(b) == (97, 43, 15)
def test_both_scripts_without_and_with_the_gap_rule():
b = layout(parse("x_1^2"), T)
assert (b.info["u"], b.info["v"]) == (36, 25) # the gap 17 is at least 4 * theta = 16
assert dims(b) == (97, 80, 25)
b = layout(parse("x_b^2"), T)
assert (b.info["u"], b.info["v"]) == (36, 28) # gap 13: the subscript moves down by 3
b = layout(parse("x_1^2"), T_)
# gap 10: v = 31; then the bottom of the superscript is 29 < 34, so both move up by 5
assert (b.info["u"], b.info["v"]) == (34, 26)
def test_scripts_on_a_box_use_the_drops():
b = layout(parse("{xy}^2"), T)
assert b.info["u"] == 36 # 43 - 27 = 16 is less than sup2
b = layout(parse("\\frac{1}{2}^2"), T)
assert b.info["u"] == 83 - 27 # the height of the fraction minus sup_drop at script size
assert b.height == 44 + 56
b = layout(parse("{xy}_1"), T)
assert b.info["v"] == 19 + 3 # the depth of y plus sub_drop at script size
def test_fraction_in_text_and_display():
b = layout(parse("\\frac{1}{2}"), T)
assert (b.info["u"], b.info["v"]) == (39, 34) # num2 and denom2, no correction
assert dims(b) == (35 + 24, 83, 34)
b = layout(parse("\\frac{1}{2}"), D)
assert (b.info["u"], b.info["v"]) == (68, 69) # num1 and denom1
assert dims(b) == (50 + 24, 132, 69)
b = layout(parse("\\frac{y}{2}"), T)
assert b.info["u"] == 44 # the depth of y leaves a gap of -1 to the rule: raise by 5
b = layout(parse("\\atop{1}{2}"), T)
assert (b.info["u"], b.info["v"]) == (44, 34) # num3, no rule
def test_narrower_part_is_centered_and_width_is_the_wider():
b = layout(parse("\\frac{xy}{2}"), T)
assert b.width == CHARS[1]["x"][0] + CHARS[1]["y"][0] + 24
def random_formula(rng, depth):
k = rng.random()
if depth == 0 or k < 0.35:
return Char(rng.choice("xyabn12"))
if k < 0.55:
return Row(tuple(random_formula(rng, depth - 1) for _ in range(rng.randint(1, 3))))
if k < 0.75:
return Frac(random_formula(rng, depth - 1), random_formula(rng, depth - 1), rng.choice([None, None, 0, 2, 7]))
sup = random_formula(rng, depth - 1) if rng.random() < 0.7 else None
sub = random_formula(rng, depth - 1) if sup is None or rng.random() < 0.5 else None
return Scripts(random_formula(rng, depth - 1), sup, sub)
def test_invariants_on_random_formulas():
rng = random.Random(1)
for _ in range(600):
f = random_formula(rng, 3)
s = rng.randrange(8)
b = layout(f, s)
assert b.width >= 0 and b.height + b.depth >= 0
if isinstance(f, Scripts) and f.sup is not None and f.sub is not None:
x, y = layout(f.sup, sup_style(s)), layout(f.sub, sub_style(s))
assert (b.info["u"] - x.depth) - (y.height - b.info["v"]) >= 4 * RULE_THICKNESS
if isinstance(f, Frac):
x, z = layout(f.num, num_style(s)), layout(f.den, denom_style(s))
u, v, th = b.info["u"], b.info["v"], b.info["theta"]
p = PARAMS[size_of(s)]
if th == 0:
clr = (7 if s < T else 3) * RULE_THICKNESS
assert (u - x.depth) - (z.height - v) >= clr
else:
clr = 3 * th if s < T else th
d = half(th)
assert (u - x.depth) - (p["axis_height"] + d) >= clr
assert (p["axis_height"] - d) - (z.height - v) >= clr
def test_scripts_shrink_with_the_style():
for s in range(8):
b = layout(Scripts(Char("x"), Char("2")), s)
x = CHARS[size_of(sup_style(s))]["2"]
assert b.width == CHARS[size_of(s)]["x"][0] + x[0] + 5
assert layout(parse("x^{x^{x^2}}"), T).width == 57 + (39 + 5) + (28 + 5) + (25 + 5)
def test_parser():
assert parse("x") == Char("x")
assert parse("x_1^2") == Scripts(Char("x"), Char("2"), Char("1"))
assert parse("\\frac{a}{b}") == Frac(Char("a"), Char("b"))
assert parse("{xy}^2") == Scripts(Row((Char("x"), Char("y"))), Char("2"), None)
assert parse("ab") == Row((Char("a"), Char("b")))
History
Knuth designed the math layout of TeX in the late 1970s and gave its final form in appendix G of The TeXbook in 1984, with the code in TeX, The Program in 1986. Later systems, among them the MATH table of OpenType and MathML renderers, kept the same scheme of styles, font parameters and clearances.
References
- Donald E. Knuth, The TeXbook, Addison-Wesley, 1984, appendix G, Generating boxes from formulas: rule 15 for fractions and rule 18 for sub and superscripts; chapter 17 for the styles
- Donald E. Knuth, TeX, The Program, Addison-Wesley, 1986, part 35, Subroutines for math mode, and part 36, Typesetting math formulas (make_fraction and make_scripts)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7WJTT8 Edit this page History Report an error Markdown