Algorithm Search⌘K

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
Properties
deterministicexactrecursive
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 x2x^2, 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 θ\theta (the default thickness ξ8\xi_8 of the font, or 0 for \atop);
  • scripts: a nucleus with a superscript, a subscript or both.

The style is one of D,T,S,SSD, T, S, SS (display, text, script and scriptscript), each in a normal and a cramped form (D′D', T′T', S′S', SS′SS'). Cramped styles raise superscripts less; they are used under a bar and in subscripts. With the styles numbered D=0D = 0, D′=1D' = 1, T=2T = 2 up to SS′=7SS' = 7, TeX computes the style of each part with integer arithmetic:

part style example
superscript 2⌊s/4⌋+4+(s mod 2)2 \lfloor s/4 \rfloor + 4 + (s \bmod 2) T→ST \to S, T′→S′T' \to S', S→SSS \to SS
subscript 2⌊s/4⌋+52 \lfloor s/4 \rfloor + 5 T→S′T \to S', S→SS′S \to SS'
numerator s+2−2⌊s/6⌋s + 2 - 2 \lfloor s/6 \rfloor D→TD \to T, T→ST \to S, SS→SSSS \to SS
denominator 2⌊s/2⌋+3−2⌊s/6⌋2 \lfloor s/2 \rfloor + 3 - 2 \lfloor s/6 \rfloor D→T′D \to T', T→S′T \to S'

DD and TT use the text size of the font, SS the script size and SSSS the scriptscript size. The font gives, for each size, the parameters named σ5\sigma_5 (x-height), σ8\sigma_8 to σ12\sigma_{12} (num1, num2, num3, denom1, denom2), σ13\sigma_{13} to σ17\sigma_{17} (sup1, sup2, sup3, sub1, sub2), σ18\sigma_{18} and σ19\sigma_{19} (sup_drop, sub_drop) and σ22\sigma_{22} (the axis height, the height of the fraction bar), and the rule thickness ξ8\xi_8. The output is a box with its width, height and depth, and the shift up uu of the numerator or superscript and the shift down vv 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 σ\sigma means the parameter at the size of the current style ss.

  1. SCRIPTS(nucleus box z, superscript, subscript, style s)
  2. 1if the nucleus is a single character then u ← 0; v ← 0
  3. 2else t ← the size of the scripts; u ← h(z) − sup_drop(t); v ← d(z) + sub_drop(t)
  4. 3if there is no superscript then
  5. 4x ← the subscript set in sub(s), plus the script space
  6. 5v ← max(v, sub1, h(x) − 4σ5/5); return z followed by x lowered by v
  7. 6x ← the superscript set in sup(s), plus the script space
  8. 7u ← max(u, sup3 if s is cramped, else sup1 if s = D, else sup2, d(x) + σ5/4)
  9. 8if there is no subscript then return z followed by x raised by u
  10. 9y ← the subscript set in sub(s), plus the script space; v ← max(v, sub2)
  11. 10c ← 4ξ8 − ((u − d(x)) − (h(y) − v))
  12. 11if c > 0 then v ← v + c; c ← 4σ5/5 − (u − d(x)); if c > 0 then u ← u + c; v ← v − c
  13. 12return z followed by x raised by u over y lowered by v
  14. FRACTION(numerator, denominator, θ, style s)
  15. 13if θ is the default then θ ← ξ8
  16. 14x ← the numerator set in num(s); z ← the denominator set in denom(s); center the narrower one
  17. 15if s is D or D' then u ← num1; v ← denom1 else v ← denom2; u ← num2 if θ ≠ 0, else num3
  18. 16if θ = 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 + δ
  19. 17else c ← 3θ if s is D or D', else θ; δ ← half(θ)
  20. 18δ1 ← c − ((u − d(x)) − (σ22 + δ)); if δ1 > 0 then u ← u + δ1
  21. 19δ2 ← c − ((σ22 − δ) − (h(z) − v)); if δ2 > 0 then v ← v + δ2
  22. 20return 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 4ξ84\xi_8 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(x)(x) is x/2x/2 rounded up for odd xx, 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, ξ8=4\xi_8 = 4, 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 uu, vv gap (u−dx)−(hy−v)(u - d_x) - (h_y - v) final uu, vv
x2x^2 TT u=max⁡(0,36,10)=36u = \max(0, 36, 10) = 36 36
x2x^2 T′T' u=29u = 29 (sup3) 29
x1x_1 TT v=max⁡(0,15,44−34)=15v = \max(0, 15, 44 - 34) = 15 15
x12x_1^2 TT 36, 25 36−19=17≥1636 - 19 = 17 \ge 16 36, 25
x12x_1^2 T′T' 29, 25 29−19=10<1629 - 19 = 10 < 16 34, 26

In the last row, line L11 first moves the subscript down by 6, to v=31v = 31. The bottom of the superscript is then at 29, below 4⋅43/5=344 \cdot 43 / 5 = 34, so both scripts move up by 5: u=34u = 34 and v=26v = 26. The gap stays 16. In the text style TT the superscript is high enough already.

For 12\frac{1}{2} in style TT, with num2 39, denom2 34, axis height 25 and θ=4\theta = 4: the clearances to the bar are (39−0)−(25+2)=12(39 - 0) - (25 + 2) = 12 and (25−2)−(44−34)=13(25 - 2) - (44 - 34) = 13, both at least θ\theta, so u=39u = 39 and v=34v = 34, and the box has height 39+44=8339 + 44 = 83 and depth 34. In style DD the same fraction uses num1 and denom1 and its parts are set in TT and T′T' 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 h(x)+uh(x) + u and depth d(y)+vd(y) + v, 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 D=0D = 0, D′=1D' = 1, T=2T = 2, T′=3T' = 3, S=4S = 4, S′=5S' = 5, SS=6SS = 6, SS′=7SS' = 7, so a style is cramped exactly when its number is odd. Write ξ8\xi_8 for the default rule thickness, σ5\sigma_5 for the x-height and σ22\sigma_{22} for the axis height of the current size. A box has a width ww, a height hh above the baseline and a depth dd below it. A box raised by uu has its top at h+uh + u and its bottom at u−du - d; a box lowered by vv has its top at h−vh - v and its bottom at −(d+v)-(d + v).

Lemma 1 (the styles). The formulas of the page, sup(s)=2⌊s/4⌋+4+(s mod 2)\mathrm{sup}(s) = 2 \lfloor s / 4 \rfloor + 4 + (s \bmod 2), sub(s)=2⌊s/4⌋+5\mathrm{sub}(s) = 2 \lfloor s / 4 \rfloor + 5, num(s)=s+2−2⌊s/6⌋\mathrm{num}(s) = s + 2 - 2 \lfloor s / 6 \rfloor and denom(s)=2⌊s/2⌋+3−2⌊s/6⌋\mathrm{denom}(s) = 2 \lfloor s / 2 \rfloor + 3 - 2 \lfloor s / 6 \rfloor, give the table of The TeXbook: a superscript of DD or TT is set in SS, of SS or SSSS in SSSS, cramped when the style is cramped; a subscript is set in the cramped form of the same style as the superscript; a numerator of DD is in TT, of TT in SS, of SS or SSSS in SSSS, 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 s∈{0,1,2,3}s \in \{0, 1, 2, 3\}, ⌊s/4⌋=0\lfloor s/4 \rfloor = 0, so sup(s)=4+(s mod 2)\mathrm{sup}(s) = 4 + (s \bmod 2), which is SS or S′S', and sub(s)=5=S′\mathrm{sub}(s) = 5 = S'. For s∈{4,…,7}s \in \{4, \ldots, 7\}, sup(s)=6+(s mod 2)\mathrm{sup}(s) = 6 + (s \bmod 2) and sub(s)=7\mathrm{sub}(s) = 7. For s<6s < 6, num(s)=s+2\mathrm{num}(s) = s + 2 keeps the parity and moves one size class down; for s∈{6,7}s \in \{6, 7\} it is ss. denom(s)\mathrm{denom}(s) is num(s)\mathrm{num}(s) with the parity bit set, since 2⌊s/2⌋+12 \lfloor s/2 \rfloor + 1 is ss with the parity bit set. □\square

Lemma 2 (the sizes of the result). For scripts with both parts, the result is the nucleus followed by a box of width max⁡(wx,wy)\max(w_x, w_y), height hx+uh_x + u and depth dy+vd_y + v; with only a superscript, the box xx raised by uu; with only a subscript, the box xx lowered by vv. For a fraction, the result has height max⁡(hx+u,σ22)\max(h_x + u, \sigma_{22}), depth max⁡(dz+v,−σ22)\max(d_z + v, -\sigma_{22}) and width max⁡(wx,wz)+2n\max(w_x, w_z) + 2n, where nn is the null delimiter space. These are the boxes that TeX builds.

Proof. With both scripts, TeX stacks xx, a kern k=(u−dx)−(hy−v)k = (u - d_x) - (h_y - v) and yy, and lowers the stack by vv. The stack has height hx+dx+k+hyh_x + d_x + k + h_y and depth dyd_y, so after the shift its height is hx+dx+(u−dx)−(hy−v)+hy−v=hx+uh_x + d_x + (u - d_x) - (h_y - v) + h_y - v = h_x + u and its depth is dy+vd_y + v. For a fraction, TeX sets the height of the stack to u+hxu + h_x and its depth to dz+vd_z + v directly. Each null delimiter is an empty box of width nn, height 0 and depth 0, moved so that its center is on the axis, which is a shift up by σ22\sigma_{22}; it reaches the height σ22\sigma_{22} and the depth −σ22-\sigma_{22}. The width and the other cases are sums and maxima of the parts. □\square

Lemma 3 (the clearances). Let xx be the superscript and yy the subscript, both set. After line L11, the gap (u−dx)−(hy−v)(u - d_x) - (h_y - v) between the bottom of the superscript and the top of the subscript is at least 4ξ84 \xi_8. For a fraction with a rule of thickness θ>0\theta > 0 and c=3θc = 3\theta in display styles, c=θc = \theta otherwise, after lines L18 and L19 the gap between the bottom of the numerator and the top of the rule, (u−dx)−(σ22+half(θ))(u - d_x) - (\sigma_{22} + \mathrm{half}(\theta)), and the gap between the bottom of the rule and the top of the denominator, (σ22−half(θ))−(hz−v)(\sigma_{22} - \mathrm{half}(\theta)) - (h_z - v), are both at least cc. For θ=0\theta = 0, after line L16 the gap (u−dx)−(hz−v)(u - d_x) - (h_z - v) is at least c=7ξ8c = 7 \xi_8 in display styles and 3ξ83 \xi_8 otherwise.

Proof. Scripts: let gg be the gap before line L10 and e=4ξ8−ge = 4 \xi_8 - g. If e≤0e \le 0, nothing changes and g≥4ξ8g \ge 4 \xi_8. If e>0e > 0, line L11 adds ee to vv, which adds ee to the gap, so it becomes 4ξ84 \xi_8. The second step adds the same amount to uu and subtracts it from vv, which leaves the gap the same. Rule: line L18 adds δ1\delta_1 to uu when δ1>0\delta_1 > 0, and the first gap is c−δ1c - \delta_1 before it, so it is ≥c\ge c after it. Line L19 changes only vv and so does not undo this, and the same argument gives the second gap. No rule: let gg be the gap and δ=half(c−g)\delta = \mathrm{half}(c - g). If δ≤0\delta \le 0 then c−g≤0c - g \le 0, since half(x)≥x/2\mathrm{half}(x) \ge x / 2, so g≥cg \ge c. If δ>0\delta > 0, both shifts grow by δ\delta, the gap grows by 2δ≥c−g2\delta \ge c - g, and so it is ≥c\ge c. Here half(x)=(x+1)div⁡2\mathrm{half}(x) = (x + 1) \operatorname{div} 2 for odd xx and xdiv⁡2x \operatorname{div} 2 for even xx, so 2 half(x)≥x2\, \mathrm{half}(x) \ge x for all integers xx. □\square

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. □\square

Complexity. Each node of the formula is laid out once, by its parent, and each rule does O(1)O(1) work besides the calls on its parts, or O(k)O(k) for a row of kk parts. So the time is O(N)O(N) for a formula with NN nodes, and the extra space is the recursion depth, O(N)O(N) in the worst case.

Complexity

Each node is laid out once by its parent, with O(1)O(1) work per fraction and per script node and O(k)O(k) for a row of kk parts. So the time is Θ(n)\Theta(n) for a formula with nn nodes. The extra space is the depth of the recursion, O(n)O(n) 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 \scriptspace and \nulldelimiterspace are 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_drop and sub_drop come 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.

tex_math_layout.pyI0RawGitHub
# 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

  1. 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
  2. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/7WJTT8/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example