Algorithm Search⌘K

Algorithmintro

Greedy line breaking

Also called first-fit line breaking.

Put as many words on each line as fit and then start a new line. With rigid or shrink-only spaces it uses the fewest lines, but it can leave very uneven lines.

Time
O(m + K B) worstΘ(m) best
Space
Θ(m) extra
Where
B = the largest number of legal breaks that one scan can pass before it stops; K = the number of lines; m = the number of items of the paragraph
Properties
deterministiconlineiterative
Origin
Donald E. Knuth, Michael F. Plass, 1981

Greedy line breaking fills a paragraph one line at a time: each line takes as many words as fit, and the next line starts after them. A line fits when its spaces can shrink enough to make it no wider than the column. The method never looks at later lines, so it is fast and simple, and the lines that it has made do not change when more text comes. When the spaces cannot stretch, it uses the fewest lines of all layouts with no overfull line. When the spaces can stretch, as in justified text, it can leave a line with very wide spaces, even when a better layout with the same number of lines exists. Knuth and Plass called it first fit and replaced it in TeX by the total-fit method of the Knuth-Plass algorithm.

In plain words

Write words on a line until the next word does not fit, then go to a new line. This is what most people do by hand and what most text editors do.

It is the best way to use few lines, because each line ends as late as it can, so the next line never starts earlier than in any other layout. It is not the best way to get even lines. If a full line leaves a long word for the next line, and that word is followed by another long word that does not fit beside it, the line with the single word must stretch its spaces a lot, or it stays very short. A method that looks ahead could have moved one short word down and made both lines a little loose.

The problem

The input is a paragraph x0,…,xm−1x_0, \ldots, x_{m-1} in the box, glue and penalty model, whose last item is a forced break, and the lengths l0,l1,…l_0, l_1, \ldots of the lines (often all equal to one ll). A line from a break aa to a legal break bb is overfull when its width at full shrink is larger than its length, that is, when its adjustment ratio is less than −1-1. The output is a breaking b1<⋯<bk=m−1b_1 < \cdots < b_k = m - 1 that holds every forced break. The greedy rule is: each line ends at the farthest legal break before the next forced break that does not make it overfull. With cost 1 per line, this is the optimal text wrapping problem of using the fewest lines.

The algorithm

  1. GREEDY-BREAK(x_0 .. x_{m-1}, l_0, l_1, ...)
  2. 1breaks ← empty list; a ← -1
  3. 2while a < m - 1 do
  4. 3best ← nil; l ← l_{|breaks|}
  5. 4for each legal break b > a, in increasing order do
  6. 5if the line (a, b) is not overfull at length l then
  7. 6best ← b
  8. 7if x_b is a forced break, or the line (a, b) without x_b is wider than l at full shrink, then stop the scan
  9. 8if best = nil then best ← the first legal break after a ▷ the line is overfull
  10. 9append best to breaks; a ← best
  11. 10return breaks

The width, stretch and shrink of a line come from prefix sums over the items, so each test costs O(1)O(1). Line L5 is the test "fits". Line L7 stops the scan when no later break can fit: the width at full shrink of the items before xbx_b only grows as bb moves right, so once it is larger than ll, every longer line is overfull. The test leaves out xbx_b, because a hyphen at xbx_b has a width that a later break does not have. Line L8 handles a word that is wider than the line: the line ends at the first possible break and is overfull, as in TeX.

Example

Take "the quick brown fox jumps over the lazy dog" with each word a box as wide as its number of letters, rigid spaces of width 1, and l=15l = 15:

line text width next word
1 the quick brown 15 "fox" gives 19 > 15
2 fox jumps over 14 "the" gives 18 > 15
3 the lazy dog 12 end of the paragraph

The words have 35 letters. On 2 lines they would need at least 7 spaces inside the lines, so 42 units, but 2 lines hold only 30. So 3 lines is the fewest, as the theorem below says.

Stretchable spaces. Now take the words "ab abc a abcd abcd" with glue of width 2, stretch 1 and shrink 1, l=8l = 8, and the tolerance 200 of plain TeX:

breaking lines rr of each line badness of each line total
greedy ab abc a / abcd / abcd −1-1, ∞\infty, last line 100, 10000, 0 10100
best ab abc / a abcd / abcd 11, 11, last line 100, 100, 0 200

The first greedy line has natural width 10 and shrink 2, so it just fits with r=−1r = -1. The second line can hold only "abcd", because "abcd abcd" is 10 wide with shrink 1. That line has no glue to stretch, so its badness is 10000. The other breaking has the same number of lines and every line within the tolerance; a search over all breakings shows it is the only one. A greedy method that tests "badness at most 200" instead of "not overfull" also fails here: no second line meets the test, so it must give an overfull or a very bad line.

Correctness

The proof rests on two facts. First, a line that fits still fits if it starts at a later break (Lemma 1), because its content then is a final part of the old content, and every item adds a width of at least 0 at full shrink. Second, the scan of lines L4 to L7 finds the farthest break that fits (Lemma 2). Then greedy stays ahead: if gtg_t and oto_t are the tt-th breaks of the greedy breaking and of any breaking with no overfull line, then gt≥otg_t \ge o_t for every tt, by induction, since the line from gtg_t to ot+1o_{t+1} fits by Lemma 1 and greedy takes the farthest break that fits. So greedy uses at most as many lines. With one length ll, no greedy line is overfull when some breaking has no overfull line. This is the greedy stays ahead argument. The full proof is in the proof file.

Lemma 1 is the reason for the condition in the summary. For the test "badness at most ρ\rho", a line that starts later is shorter and must stretch more, so a good line can become a bad one, and the argument fails, as the example shows.

Proof: First fit uses the fewest lines when spaces cannot stretchfull

Claim. Let x0,…,xm−1x_0, \ldots, x_{m-1} be a paragraph of boxes, glue and penalties whose last item is a forced break. Assume that every box width and every penalty width is at least 0, and that every glue has wi−zi≥0w_i - z_i \ge 0 with shrink of finite order. Then GREEDY-BREAK (lines L1 to L10) stops. If the lengths l0,l1,…l_0, l_1, \ldots of the lines are all equal to ll and some breaking has no overfull line, then no line of the greedy breaking is overfull, and the greedy breaking has the fewest lines among all breakings with no overfull line. For any lengths l0,l1,…l_0, l_1, \ldots, the greedy breaking has at most as many lines as any breaking with no overfull line. Stretch plays no part in this claim: a line counts as good when it is not overfull, whatever its badness.

Setup. A breaking is a list of legal breaks b1<⋯<bk=m−1b_1 < \cdots < b_k = m - 1 that holds every forced break. Put b0=−1b_0 = -1. Line tt (for t=1,…,kt = 1, \ldots, k) runs from just after bt−1b_{t-1} to btb_t, and its length is lt−1l_{t-1}. For a break aa (or a=−1a = -1) and a later legal break bb, let s(a,b)s(a, b) be the first box after aa, or bb if there is none before bb; the items from a+1a + 1 to s(a,b)−1s(a, b) - 1 are discarded, as in TeX. The content of the line (a,b)(a, b) is the items s(a,b),…,b−1s(a, b), \ldots, b - 1, plus the penalty xbx_b if xbx_b is a penalty. Glue and penalties that are not at the break inside the content count as in the model: glue adds wiw_i, yiy_i and ziz_i, a penalty that is not the break adds nothing. Let M(a,b)=L−ZM(a, b) = L - Z be the width of the line (a,b)(a, b) when its glue shrinks fully. The line is overfull at length ll exactly when M(a,b)>lM(a, b) > l; this is the test fits of line L5. Each item of the content adds a value of at least 0 to MM, by the hypothesis on the widths.

Lemma 1 (a shorter start fits). If a≤a′<ba \le a' < b and the line (a,b)(a, b) fits at length ll, then the line (a′,b)(a', b) fits at length ll.

Proof. The first box after a′a' is not before the first box after aa, so s(a′,b)≥s(a,b)s(a', b) \ge s(a, b). Hence the content of (a′,b)(a', b) is a subset of the content of (a,b)(a, b): it is a final part of the items from s(a,b)s(a, b) to b−1b - 1, with the same item at the break. Every item adds at least 0 to MM, so M(a′,b)≤M(a,b)≤lM(a', b) \le M(a, b) \le l. □\square

Lemma 2 (the scan finds the farthest fitting break). Fix a break aa and a length ll. Let b∗b^* be the largest legal break b>ab > a such that no forced break lies strictly between aa and bb and the line (a,b)(a, b) fits, if there is one. Then the loop of lines L4 to L7 sets best=b∗best = b^*. If there is none, line L8 sets bestbest to the first legal break after aa.

Proof. The loop visits the legal breaks after aa in increasing order. Line L6 records each one that fits, so at the exit bestbest is the largest visited break that fits. It remains to show that no unvisited break qualifies. The loop stops at a break bb for one of two reasons (line L7). If xbx_b is a forced break, every later break b′b' has the forced break bb strictly between aa and b′b', so it does not qualify. Otherwise μ(b)>l\mu(b) > l, where μ(b)\mu(b) is the width at full shrink of the items s(a,b),…,b−1s(a, b), \ldots, b - 1 without xbx_b. Since μ(b)>l≥0\mu(b) > l \ge 0, some box lies between aa and bb, so s(a,b)s(a, b) is the first box after aa and s(a,b′)=s(a,b)s(a, b') = s(a, b) for every later legal break b′b'. Then the content of (a,b′)(a, b') holds the items s(a,b),…,b−1s(a, b), \ldots, b - 1, and all its other items add at least 0. So M(a,b′)≥μ(b)>lM(a, b') \ge \mu(b) > l and (a,b′)(a, b') is overfull. If the loop ends because the legal breaks run out, every break was visited. In each case bestbest is b∗b^*, or nothing fits and line L8 takes the first legal break. □\square

Termination. Each pass of the outer loop (line L2) appends a break best>abest > a and sets aa to it. There are finitely many legal breaks and the last item m−1m - 1 is a forced break, which the scan never passes (line L7). So the breaks grow strictly and the loop stops when a=m−1a = m - 1. The greedy list g1<⋯<gK=m−1g_1 < \cdots < g_K = m - 1 holds every forced break: a forced break f>af > a stops the scan, so gt+1≤fg_{t+1} \le f, and the breaks keep moving until they reach ff. Hence the output is a breaking.

Theorem (greedy stays ahead). Let o1<⋯<ok=m−1o_1 < \cdots < o_k = m - 1 be any breaking with no overfull line, and let g1<⋯<gKg_1 < \cdots < g_K be the greedy breaking, for any lengths l0,l1,…l_0, l_1, \ldots. Put gt=m−1g_t = m - 1 for t>Kt > K. Then gt≥otg_t \ge o_t for t=0,…,kt = 0, \ldots, k. In particular K≤kK \le k.

Proof. By induction on tt. For t=0t = 0 both are −1-1. Assume gt≥otg_t \ge o_t with t<kt < k. If gt=m−1g_t = m - 1, then gt+1=m−1≥ot+1g_{t+1} = m - 1 \ge o_{t+1}. If ot+1≤gt<m−1o_{t+1} \le g_t < m - 1, then gt+1>gt≥ot+1g_{t+1} > g_t \ge o_{t+1}. Otherwise ot≤gt<ot+1o_t \le g_t < o_{t+1}. The line (ot,ot+1)(o_t, o_{t+1}) fits at length ltl_t, so by Lemma 1 the line (gt,ot+1)(g_t, o_{t+1}) fits at length ltl_t. No forced break lies strictly between gtg_t and ot+1o_{t+1}, because the breaking oo holds every forced break and has none strictly between oto_t and ot+1o_{t+1}. So ot+1o_{t+1} qualifies in Lemma 2 for the greedy line number t+1t + 1, which has length ltl_t, and gt+1=b∗≥ot+1g_{t+1} = b^* \ge o_{t+1}. This ends the induction. For t=kt = k we get gk≥ok=m−1g_k \ge o_k = m - 1, so the greedy breaking has ended after at most kk lines. □\square

Theorem (no overfull line with one length). If lt=ll_t = l for all tt and some breaking oo has no overfull line, then line L8 never uses its fallback, so no greedy line is overfull.

Proof. Take a greedy break gt<m−1g_t < m - 1. Let uu be the least index with ou>gto_u > g_t; it exists because ok=m−1o_k = m - 1. Then ou−1≤gt<ouo_{u-1} \le g_t < o_u. The line (ou−1,ou)(o_{u-1}, o_u) fits at length ll, so the line (gt,ou)(g_t, o_u) fits at length ll by Lemma 1, and no forced break lies strictly between gtg_t and ouo_u. By Lemma 2 the scan finds a fitting break. □\square

Conclusion. With one length ll, the greedy breaking has no overfull line and at most as many lines as any breaking with no overfull line, so it has the fewest. With other lengths, it still has at most as many lines as any breaking with no overfull line, but its own lines can be overfull: greedy is ahead, so the line of oo that covers the start of the greedy line tt can have a later index and a larger length than lt−1l_{t-1}. Only the test "not overfull" enters the proofs. When the test is "badness at most a tolerance", Lemma 1 fails: a later start makes the line shorter and its stretch larger, so a line that was good can become underfull. The page gives an example. ■\blacksquare

Complexity

The prefix sums take Θ(m)\Theta(m) time and space. The scan of a line visits the legal breaks from aa up to the first one where the line is too wide or a forced break, so at most B+1B + 1 of them, and each test is O(1)O(1). The time is O(m+KB)O(m + K B) for KK lines. In normal text, BB is the number of words and hyphen points that fit in one line, so the time is linear in mm; the tests of this page count at most 2m2m tests on a paragraph of 2000 random words. The best case is Θ(m)\Theta(m), since every item is read.

Properties

  • Online. Each line is fixed once its scan stops, before the rest of the paragraph is read. Adding text at the end never changes the earlier lines, which is why editors use it.
  • Fewest lines, not best lines. It is optimal for the number of lines, in the sense of the proof, and for nothing else. It ignores the badness of the lines.
  • Stable. A small change in the text moves line ends only from the change onward.
  • Local. Each choice depends only on the current line, so it cannot trade a slightly worse line for a much better one later.

Variants and improvements

  • Natural width. Many tools test the natural width of a line instead of its width at full shrink, so the spaces never shrink. This is first fit with rigid spaces, and the theorem applies to it directly.
  • Best fit. Among the breaks that fit, take the one whose line has the least cost, not the farthest one. The page builder of TeX works this way for pages, see best-fit page breaking.
  • Total fit. Choose all breaks together to minimize the total cost: the Knuth-Plass algorithm, or printing neatly for rigid spaces.
  • Hyphenation. With the hyphen points of a word as flagged penalties, the greedy scan can end a line inside a word. The points come from a method for the hyphenation problem.
  • Break opportunities of Unicode. For text in many scripts, the legal breaks come from the Unicode line breaking algorithm, and the greedy rule picks among them.

When to use it

Use it when speed and stable lines matter more than even spacing: text editors and terminals, ragged-right text, code and plain text wrapping, and documents that are edited while they are shown. For justified text of high quality, or when hyphens should be few, use the Knuth-Plass algorithm, which looks at the whole paragraph.

Pitfalls

  • "Fewest lines" with a badness test. The theorem holds for the test "not overfull". With a tolerance on the badness, greedy can fail to find a breaking that exists, as in the example.
  • Different line lengths. With lengths that change from line to line, greedy still uses at most as many lines as any breaking with no overfull line, but its own lines can be overfull: being ahead, it can reach a short line with more text than the other breaking puts there.
  • Stopping at the first line that does not fit. A hyphen can be wider than the rest of its word. Then the break at the hyphen does not fit, but the break after the word does. Line L7 stops only when the width without xbx_b is too large, and the test test_greedy_takes_the_farthest_break_with_varying_lengths checks that no later break fits.
  • A word wider than the line. No break fits, so the loop must still move forward; line L8 makes an overfull line instead of an endless loop.
  • The glue at a break. The glue at the break and the glue right after it belong to no line. Counting them makes some lines look too wide.

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.

boxglue.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the text processing and typesetting pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Boxes, glue and penalties, in the notation of the typesetting pages.

This module holds no line breaking or page breaking method. It gives:

- the item types Box, Glue and Penalty, and the constant INF_PENALTY;
- a paragraph builder from word widths, with an interword glue and the
  ending of TeX (penalty 10000, glue 0 plus 1fil, penalty -10000);
- the legal breakpoints of an item list;
- the measures (L, Y, Z) of a line between two breaks, by prefix sums;
- the adjustment ratio r as a Fraction;
- the real badness min(100 |r|^3, 10000) as an exact Fraction, and the
  integer badness of TeX: The Program, section 108;
- a brute force that lists every breaking of a tiny paragraph;
- a text renderer for examples.

Widths are ints or fractions.Fraction. Do not use floats for widths.

A break is an index b of the item list. The start of the paragraph is the
break -1. A line from break a to break b holds the items a+1 .. b-1, less
the glue and penalties that follow a before the first box (TeX discards
them), plus the width of x_b when x_b is a penalty (a hyphen). Nothing is
discarded at the start of the paragraph (a = -1).

Glue can have an infinite order: 0 is normal, 1 is fil, 2 is fill and 3 is
filll, as in TeX. Stretch and shrink totals are tuples with one entry per
order.
"""

from dataclasses import dataclass
from fractions import Fraction
from itertools import product
import math
from typing import Iterator, Sequence, Union

Number = Union[int, Fraction]

INF_PENALTY = 10000  # a penalty >= INF_PENALTY forbids a break, <= -INF_PENALTY forces one
INF_BAD = 10000  # the largest finite badness (inf_bad in TeX)
NORMAL, FIL, FILL, FILLL = 0, 1, 2, 3
ORDERS = 4


@dataclass(frozen=True)
class Box:
    """A rigid item: a letter, a word or a line. text is for the renderer."""

    width: Number
    height: Number = 0
    depth: Number = 0
    text: str = ""


@dataclass(frozen=True)
class Glue:
    """A space with natural width, stretchability y and shrinkability z."""

    width: Number
    stretch: Number = 0
    shrink: Number = 0
    stretch_order: int = NORMAL
    shrink_order: int = NORMAL


@dataclass(frozen=True)
class Penalty:
    """A possible break with cost penalty. flagged marks a hyphen."""

    width: Number
    penalty: int
    flagged: bool = False


Item = Union[Box, Glue, Penalty]


def is_forced(item: Item) -> bool:
    """True for a penalty of -INF_PENALTY or less (a forced break)."""
    return isinstance(item, Penalty) and item.penalty <= -INF_PENALTY


def is_legal_break(items: Sequence[Item], b: int) -> bool:
    """A penalty below INF_PENALTY, or a glue right after a box."""
    x = items[b]
    if isinstance(x, Penalty):
        return x.penalty < INF_PENALTY
    if isinstance(x, Glue):
        return b > 0 and isinstance(items[b - 1], Box)
    return False


def legal_breakpoints(items: Sequence[Item]) -> list[int]:
    """The indices of all legal breakpoints, in increasing order."""
    return [b for b in range(len(items)) if is_legal_break(items, b)]


def _box(piece) -> Box:
    if isinstance(piece, Box):
        return piece
    if isinstance(piece, str):
        return Box(len(piece), text=piece)
    return Box(piece)


def paragraph(
    words: Sequence,
    space: Glue = Glue(1, 0, 0),
    hyphen_width: Number = 1,
    hyphen_penalty: int = 50,
    finish: bool = True,
) -> list[Item]:
    """Build the item list of a paragraph.

    Each word is a width (int or Fraction), a str (width len(str), and the
    text is kept), a Box, or a list or tuple of such pieces. Between two
    pieces of one word the builder puts a flagged penalty (a hyphenation
    point) of width hyphen_width and cost hyphen_penalty. Between two words
    it puts the glue space. With finish, it adds the ending of TeX:
    Penalty(0, INF_PENALTY), Glue(0, 1, 0, FIL) (the parfillskip) and
    Penalty(0, -INF_PENALTY).
    """
    items: list[Item] = []
    for k, word in enumerate(words):
        if k > 0:
            items.append(space)
        pieces = word if isinstance(word, (list, tuple)) else [word]
        for t, piece in enumerate(pieces):
            if t > 0:
                items.append(Penalty(hyphen_width, hyphen_penalty, True))
            items.append(_box(piece))
    if finish:
        items.append(Penalty(0, INF_PENALTY))
        items.append(Glue(0, 1, 0, stretch_order=FIL))
        items.append(Penalty(0, -INF_PENALTY))
    return items


class Measures:
    """Prefix sums over an item list, and the measures of a line in O(1).

    With vertical=True the size of a box is its height plus its depth and a
    penalty has no size, a simple model of a vertical list. The page builder
    of TeX treats the depth of the last box apart; a page that needs this
    must correct for it.
    """

    def __init__(self, items: Sequence[Item], vertical: bool = False) -> None:
        m = len(items)
        self.items = list(items)
        self.vertical = vertical
        self.W: list[Number] = [0] * (m + 1)
        self.Y: list[list[Number]] = [[0] * (m + 1) for _ in range(ORDERS)]
        self.Z: list[list[Number]] = [[0] * (m + 1) for _ in range(ORDERS)]
        for i, x in enumerate(self.items):
            dw: Number = 0
            for o in range(ORDERS):
                self.Y[o][i + 1] = self.Y[o][i]
                self.Z[o][i + 1] = self.Z[o][i]
            if isinstance(x, Box):
                dw = x.height + x.depth if vertical else x.width
            elif isinstance(x, Glue):
                dw = x.width
                self.Y[x.stretch_order][i + 1] += x.stretch
                self.Z[x.shrink_order][i + 1] += x.shrink
            self.W[i + 1] = self.W[i] + dw
        # next_box[i]: the least index >= i that holds a box, or m
        self.next_box = [m] * (m + 1)
        for i in range(m - 1, -1, -1):
            self.next_box[i] = i if isinstance(self.items[i], Box) else self.next_box[i + 1]

    def start(self, a: int, b: int) -> int:
        """The index of the first item of the line from break a to break b."""
        if a < 0:
            return 0
        return min(self.next_box[a + 1], b)

    def line(self, a: int, b: int) -> tuple[Number, tuple, tuple]:
        """(L, Y, Z) of the line from break a to break b, with a < b.

        L is the natural width, Y and Z are the total stretch and shrink,
        one entry per glue order.
        """
        s = self.start(a, b)
        L = self.W[b] - self.W[s]
        x = self.items[b]
        if isinstance(x, Penalty) and not self.vertical:
            L += x.width
        Y = tuple(self.Y[o][b] - self.Y[o][s] for o in range(ORDERS))
        Z = tuple(self.Z[o][b] - self.Z[o][s] for o in range(ORDERS))
        return L, Y, Z


def _orders(v) -> tuple:
    if isinstance(v, tuple):
        return v + (0,) * (ORDERS - len(v))
    return (v,) + (0,) * (ORDERS - 1)


def adjustment_ratio(l: Number, L: Number, Y, Z) -> tuple:
    """(r, order) for a line of natural width L set to the length l.

    Y and Z are numbers (normal order only) or tuples by order. The ratio
    uses the highest order with a nonzero total. r is a Fraction, or
    math.inf when the line must stretch and cannot, or -math.inf when it
    must shrink and cannot.
    """
    Yo, Zo = _orders(Y), _orders(Z)
    if L == l:
        return Fraction(0), NORMAL
    tot = Yo if L < l else Zo
    for o in range(ORDERS - 1, -1, -1):
        if tot[o] != 0:
            return Fraction(l - L) / Fraction(tot[o]), o
    return (math.inf if L < l else -math.inf), NORMAL


def is_overfull(r, order: int = NORMAL) -> bool:
    """True when the glue must shrink more than its shrinkability."""
    return order == NORMAL and r < -1


def badness(r, order: int = NORMAL):
    """The real badness min(100 |r|^3, 10000) of Knuth and Plass, exact.

    Glue of infinite order gives 0. An overfull line (r < -1) gives
    math.inf, so that it loses to every legal line. A line that cannot
    stretch (r = math.inf) gives 10000.
    """
    if order != NORMAL:
        return Fraction(0)
    if r < -1:
        return math.inf
    if r == math.inf:
        return Fraction(INF_BAD)
    return min(100 * abs(Fraction(r)) ** 3, Fraction(INF_BAD))


def tex_badness(t: int, s: int) -> int:
    """The integer badness(t, s) of TeX: The Program, section 108.

    t >= 0 is the amount to stretch or shrink and s the total stretch or
    shrink, both in scaled points (integers). The value is about
    100 (t/s)^3, and 10000 stands for infinitely bad.
    """
    if t < 0:
        raise ValueError("t must be >= 0")
    if t == 0:
        return 0
    if s <= 0:
        return INF_BAD
    if t <= 7230584:
        r = (t * 297) // s  # 297^3 = 99.94 * 2^18
    elif s >= 1663497:
        r = t // (s // 297)
    else:
        r = t
    if r > 1290:  # 1290^3 < 2^31 < 1291^3
        return INF_BAD
    return (r * r * r + 0o400000) // 0o1000000  # r^3 / 2^18, rounded


def tex_line_badness(l: int, L: int, Y, Z) -> int:
    """The badness that the line breaker of TeX gives a line (sections 852 and 853).

    Integer widths only. A line that needs stretch and has stretch of an
    infinite order gets 0. An overfull line gets INF_BAD + 1. Infinite
    shrink, which TeX reports as an error in a paragraph, gives 0 here.
    """
    Yo, Zo = _orders(Y), _orders(Z)
    shortfall = l - L
    if shortfall > 0:
        if any(Yo[1:]):
            return 0
        return tex_badness(shortfall, Yo[0])
    if shortfall < 0:
        if any(Zo[1:]):
            return 0
        if -shortfall > Zo[0]:
            return INF_BAD + 1
        return tex_badness(-shortfall, Zo[0])
    return 0


def all_breakings(items: Sequence[Item]) -> Iterator[tuple[int, ...]]:
    """Yield every breaking of the paragraph, for tiny paragraphs only.

    A breaking is a tuple b_1 < ... < b_k of legal breaks with b_k = m - 1
    that holds every forced break. The last item must be a forced penalty.
    There are 2^q breakings for q optional breakpoints.
    """
    m = len(items)
    if m == 0 or not is_forced(items[-1]):
        raise ValueError("the last item must be a forced penalty")
    legal = legal_breakpoints(items)
    optional = [b for b in legal if b != m - 1 and not is_forced(items[b])]
    forced = [b for b in legal if b == m - 1 or is_forced(items[b])]
    for choice in product((False, True), repeat=len(optional)):
        chosen = [b for b, c in zip(optional, choice) if c]
        yield tuple(sorted(chosen + forced))


def render(items: Sequence[Item], breaks: Sequence[int]) -> list[str]:
    """The text of each line of a breaking, for examples.

    A box shows its text (or 'x' repeated by its integer width), a glue of
    positive width shows one space, and a flagged penalty at a break shows
    '-'. Trailing spaces are removed.
    """
    meas = Measures(items)
    out: list[str] = []
    a = -1
    for b in breaks:
        parts: list[str] = []
        for x in items[meas.start(a, b) : b]:
            if isinstance(x, Box):
                if x.text:
                    parts.append(x.text)
                else:
                    parts.append("x" * x.width if isinstance(x.width, int) else "x")
            elif isinstance(x, Glue) and x.width > 0:
                parts.append(" ")
        x = items[b]
        if isinstance(x, Penalty) and x.flagged and not is_forced(x):
            parts.append("-")
        out.append("".join(parts).rstrip())
        a = b
    return out
greedy_line_breaking.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-line-breaking/. The authors are listed in prov/HF8Z28.jsonl.

"""Greedy (first-fit) line breaking on boxes, glue and penalties.

Each line takes the farthest legal break that does not make the line
overfull, that is, the line fits when its glue shrinks fully. The method
never looks at later lines.
"""

from typing import Optional, Sequence

from boxglue import NORMAL, Item, Measures, adjustment_ratio, is_forced, is_legal_break, is_overfull


def _length(line_width, j: int):
    """The length l_j of line j (0-based). A sequence repeats its last entry."""
    if isinstance(line_width, (list, tuple)):
        return line_width[min(j, len(line_width) - 1)]
    return line_width


def fits(meas: Measures, a: int, b: int, l) -> bool:
    """True when the line from break a to break b is not overfull at length l."""
    L, Y, Z = meas.line(a, b)
    r, order = adjustment_ratio(l, L, Y, Z)
    return not is_overfull(r, order)


def _min_width(meas: Measures, a: int, b: int):
    """The width at full shrink of the line a..b without the item x_b.

    This value never decreases when b grows, so it tells when to stop.
    It is None when the line has shrink of an infinite order (never overfull).
    """
    s = meas.start(a, b)
    if any(meas.Z[o][b] - meas.Z[o][s] for o in range(1, len(meas.Z))):
        return None
    return (meas.W[b] - meas.W[s]) - (meas.Z[NORMAL][b] - meas.Z[NORMAL][s])


def greedy_line_breaks(items: Sequence[Item], line_width, stats: Optional[dict] = None) -> list[int]:
    """The breaks b_1 < ... < b_k = m - 1 that first fit chooses.

    line_width is one length for every line, or a sequence of lengths l_0,
    l_1, ... (the last one repeats). The last item must be a forced
    penalty. When no legal break gives a line that fits, the line ends at
    the first legal break and is overfull. If stats is a dict, stats["tests"]
    counts the lines that were measured.
    """
    m = len(items)
    if m == 0 or not is_forced(items[-1]):
        raise ValueError("the last item must be a forced penalty")
    meas = Measures(items)
    legal = [b for b in range(m) if is_legal_break(items, b)]
    tests = 0
    breaks: list[int] = []  # @line L1
    a, k = -1, 0  # k indexes legal: the first legal break after a
    while a < m - 1:  # @line L2
        l = _length(line_width, len(breaks))
        best = None  # @line L3
        first = legal[k]
        i = k
        while i < len(legal):  # @line L4
            b = legal[i]
            tests += 1
            if fits(meas, a, b, l):  # @line L5
                best = b  # @line L6
            mw = _min_width(meas, a, b)
            if is_forced(items[b]) or (mw is not None and mw > l):  # @line L7
                break
            i += 1
        if best is None:  # @line L8
            best = first
        breaks.append(best)  # @line L9
        a = best
        while k < len(legal) and legal[k] <= a:
            k += 1
    if stats is not None:
        stats["tests"] = tests
    return breaks  # @line L10
test_greedy_line_breaking.py 298 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-line-breaking/. The authors are listed in prov/HF8Z28.jsonl.

import math
import random
from fractions import Fraction

from boxglue import (
    FIL,
    FILL,
    INF_BAD,
    INF_PENALTY,
    Box,
    Glue,
    Measures,
    Penalty,
    adjustment_ratio,
    all_breakings,
    badness,
    is_forced,
    is_legal_break,
    is_overfull,
    legal_breakpoints,
    paragraph,
    render,
    tex_badness,
    tex_line_badness,
)

# ---------------------------------------------------------------- the helper


def direct_line(items, a, b):
    """Measures of the line a..b by a direct scan, without prefix sums."""
    i = 0 if a < 0 else a + 1
    if a >= 0:
        while i < b and not isinstance(items[i], Box):
            i += 1
    L = 0
    Y = [0, 0, 0, 0]
    Z = [0, 0, 0, 0]
    for x in items[i:b]:
        if isinstance(x, Box):
            L += x.width
        elif isinstance(x, Glue):
            L += x.width
            Y[x.stretch_order] += x.stretch
            Z[x.shrink_order] += x.shrink
    if isinstance(items[b], Penalty):
        L += items[b].width
    return L, tuple(Y), tuple(Z)


def random_items(rng, n_words):
    words = []
    for _ in range(n_words):
        k = rng.randint(1, 3)
        words.append([rng.randint(1, 6) for _ in range(k)])
    space = Glue(rng.randint(1, 3), rng.randint(0, 2), rng.randint(0, 1))
    items = paragraph(words, space=space, hyphen_width=1, hyphen_penalty=50)
    # put a few extra items in, to test the discard rule and the orders
    j = rng.randrange(len(items) - 3)
    items.insert(j, Glue(2, 1, 1, stretch_order=rng.choice([0, FIL, FILL])))
    items.insert(j, Penalty(0, rng.choice([0, 100, INF_PENALTY, -INF_PENALTY])))
    return items


def test_paragraph_builder():
    items = paragraph([3, ["ab", "c"], Fraction(5, 2)], space=Glue(1, 1, 1))
    assert items[0] == Box(3)
    assert items[1] == Glue(1, 1, 1)
    assert items[2] == Box(2, text="ab")
    assert items[3] == Penalty(1, 50, True)
    assert items[4] == Box(1, text="c")
    assert items[6] == Box(Fraction(5, 2))
    assert items[-3:] == [Penalty(0, INF_PENALTY), Glue(0, 1, 0, stretch_order=FIL), Penalty(0, -INF_PENALTY)]
    assert is_forced(items[-1]) and not is_forced(items[-3])


def test_legal_breakpoints():
    items = paragraph([2, [1, 1], 3])
    # 0 box, 1 glue, 2 box, 3 hyphen, 4 box, 5 glue, 6 box, 7 pen 10000, 8 fil glue, 9 pen -10000
    assert legal_breakpoints(items) == [1, 3, 5, 9]
    assert not is_legal_break(items, 7) and not is_legal_break(items, 8)
    glue_after_glue = [Box(1), Glue(1), Glue(1), Box(1)]
    assert legal_breakpoints(glue_after_glue) == [1]


def test_measures_against_direct_scan():
    rng = random.Random(7)
    for _ in range(200):
        items = random_items(rng, rng.randint(1, 6))
        meas = Measures(items)
        legal = legal_breakpoints(items)
        for a in [-1] + legal:
            for b in legal:
                if b > a:
                    assert meas.line(a, b) == direct_line(items, a, b)


def test_vertical_measures():
    items = [Box(5, height=10, depth=2), Glue(3, 1, 1), Box(5, height=8, depth=1), Penalty(4, 0)]
    meas = Measures(items, vertical=True)
    assert meas.line(-1, 3) == (10 + 2 + 3 + 8 + 1, (1, 0, 0, 0), (1, 0, 0, 0))


def test_adjustment_ratio():
    assert adjustment_ratio(19, 19, 3, 3) == (0, 0)
    assert adjustment_ratio(19, 18, 3, 3) == (Fraction(1, 3), 0)
    assert adjustment_ratio(19, 20, 3, 3) == (Fraction(-1, 3), 0)
    assert adjustment_ratio(10, 4, 0, 0) == (math.inf, 0)
    assert adjustment_ratio(10, 14, 2, 0) == (-math.inf, 0)
    assert adjustment_ratio(10, 4, (3, 2, 0, 0), 0) == (Fraction(3), FIL)
    r, o = adjustment_ratio(10, 16, 3, 3)
    assert r == -2 and is_overfull(r, o)
    assert not is_overfull(Fraction(-1), 0) and not is_overfull(-5, FIL)


def test_real_badness():
    assert badness(Fraction(1, 3)) == Fraction(100, 27)
    assert badness(Fraction(-1, 3)) == Fraction(100, 27)
    assert badness(Fraction(1)) == 100
    assert badness(Fraction(-1)) == 100
    assert badness(Fraction(5)) == INF_BAD
    assert badness(math.inf) == INF_BAD
    assert badness(Fraction(-3, 2)) == math.inf
    assert badness(Fraction(7), FIL) == 0


def test_tex_badness_check_values():
    assert tex_badness(1, 3) == 4
    assert tex_badness(1, 1) == 100
    assert tex_badness(1, 2) == 12
    assert tex_badness(2, 1) == 800
    assert tex_badness(3, 10) == 3
    assert tex_badness(0, 0) == 0
    assert tex_badness(5, 0) == INF_BAD
    assert tex_badness(1000, 1) == INF_BAD


def test_tex_badness_monotone_and_close():
    # the integer badness of TeX grows with t and falls with s: badness(t+1, s) >= badness(t, s) >= badness(t, s+1)
    for s in range(1, 60):
        for t in range(0, 150):
            b = tex_badness(t, s)
            assert tex_badness(t + 1, s) >= b >= tex_badness(t, s + 1)
    rng = random.Random(3)
    for _ in range(2000):
        s = rng.randint(65536, 20 * 65536)
        t = rng.randint(0, 2 * s)
        exact = Fraction(100 * t**3, s**3)
        b = tex_badness(t, s)
        if exact < 1000:
            # the integer form is within 1 plus 2 percent of the real form here
            assert abs(b - exact) <= 1 + exact / 50


def test_tex_line_badness():
    pt = 65536
    assert tex_line_badness(19 * pt, 18 * pt, 3 * pt, 3 * pt) == 4
    assert tex_line_badness(19 * pt, 20 * pt, 3 * pt, 3 * pt) == 4
    assert tex_line_badness(19 * pt, 23 * pt, 3 * pt, 3 * pt) == INF_BAD + 1
    assert tex_line_badness(19 * pt, 2 * pt, (0, 1, 0, 0), 0) == 0
    assert tex_line_badness(19 * pt, 19 * pt, 0, 0) == 0


def test_all_breakings():
    items = paragraph([2, [1, 1], 3, 4])
    optional = [b for b in legal_breakpoints(items) if b != len(items) - 1]
    got = list(all_breakings(items))
    assert len(got) == 2 ** len(optional)
    assert len(set(got)) == len(got)
    for br in got:
        assert br[-1] == len(items) - 1
        assert list(br) == sorted(br)
        assert all(is_legal_break(items, b) for b in br)
    forced_inside = [Box(1), Glue(1), Box(1), Penalty(0, -INF_PENALTY), Box(1), Glue(1), Box(1), Penalty(0, -INF_PENALTY)]
    got = list(all_breakings(forced_inside))
    assert got == [(3, 7), (3, 5, 7), (1, 3, 7), (1, 3, 5, 7)]


def test_render():
    items = paragraph(["hyph", "en", ["ex", "am", "ple"], "go"])
    br = (1, 7, len(items) - 1)  # after hyph, at the hyphen after am, at the end
    assert items[7] == Penalty(1, 50, True)
    assert render(items, br) == ["hyph", "en exam-", "ple go"]


# ---------------------------------------------------------------- greedy line breaking

from greedy_line_breaking import fits, greedy_line_breaks  # noqa: E402


def all_lines_fit(items, br, l):
    meas = Measures(items)
    a = -1
    for b in br:
        if not fits(meas, a, b, l):
            return False
        a = b
    return True


def line_badness(items, br, l):
    meas = Measures(items)
    out, a = [], -1
    for b in br:
        L, Y, Z = meas.line(a, b)
        r, order = adjustment_ratio(l, L, Y, Z)
        out.append(badness(r, order))
        a = b
    return out


def fixed_space_items(rng):
    """Random words with hyphenation points; glue that cannot stretch, and shrink <= width."""
    n_words = rng.randint(1, 9)
    words = []
    for _ in range(n_words):
        k = 1 if rng.random() < 0.7 else 2
        words.append([rng.randint(1, 5) for _ in range(k)])
    w = rng.randint(1, 2)
    space = Glue(w, 0, rng.randint(0, w))
    items = paragraph(words, space=space, hyphen_width=1, hyphen_penalty=50)
    return items, max(max(p) for p in words) + 1


def test_greedy_example_of_the_page():
    words = "the quick brown fox jumps over the lazy dog".split()
    items = paragraph(words, space=Glue(1, 0, 0))
    br = greedy_line_breaks(items, 15)
    assert render(items, br) == ["the quick brown", "fox jumps over", "the lazy dog"]


def test_greedy_fewest_lines_against_brute_force():
    rng = random.Random(7)
    for _ in range(250):
        items, wmin = fixed_space_items(rng)
        l = rng.randint(wmin, wmin + 12)
        g = greedy_line_breaks(items, l)
        assert all_lines_fit(items, g, l)
        feasible = [br for br in all_breakings(items) if all_lines_fit(items, br, l)]
        assert feasible
        assert len(g) == min(len(br) for br in feasible)
        # greedy stays ahead: its k-th break is at least the k-th break of any feasible breaking
        for br in feasible:
            for k in range(len(g)):
                assert g[k] >= br[k]


def test_greedy_takes_the_farthest_break_with_varying_lengths():
    rng = random.Random(11)
    for _ in range(200):
        items, wmin = fixed_space_items(rng)
        lengths = [rng.randint(wmin, wmin + 8) for _ in range(3)]
        g = greedy_line_breaks(items, lengths)
        meas = Measures(items)
        legal = legal_breakpoints(items)
        a = -1
        for j, b in enumerate(g):
            l = lengths[min(j, 2)]
            assert fits(meas, a, b, l)
            later = [c for c in legal if c > b]
            assert all(not fits(meas, a, c, l) for c in later)
            a = b


def test_stretch_model_greedy_fails():
    # Glue 2 with stretch 1 and shrink 1, lines of length 8, tolerance 200 as in plain TeX.
    words = ["ab", "abc", "a", "abcd", "abcd"]
    items = paragraph(words, space=Glue(2, 1, 1))
    g = greedy_line_breaks(items, 8)
    assert render(items, g) == ["ab abc a", "abcd", "abcd"]
    assert line_badness(items, g, 8) == [100, 10000, 0]
    good = [br for br in all_breakings(items) if all(x <= 200 for x in line_badness(items, br, 8))]
    assert [render(items, br) for br in good] == [["ab abc", "a abcd", "abcd"]]
    assert line_badness(items, good[0], 8) == [100, 100, 0]
    # the least total badness over all breakings (the total-fit choice) is 200, greedy gives 10100
    best = min(sum(line_badness(items, br, 8)) for br in all_breakings(items))
    assert best == 200 and sum(line_badness(items, g, 8)) == 10100


def test_overfull_word_and_forced_break():
    items = paragraph(["abcdefghij", "ab"], space=Glue(1, 0, 0))
    g = greedy_line_breaks(items, 5)
    assert render(items, g) == ["abcdefghij", "ab"]
    assert not all_lines_fit(items, g, 5)
    forced = [Box(1), Glue(1), Box(1), Penalty(0, -INF_PENALTY), Box(1), Glue(1), Box(1), Penalty(0, -INF_PENALTY)]
    assert greedy_line_breaks(forced, 100) == [3, 7]


def test_greedy_measures_a_linear_number_of_lines():
    rng = random.Random(3)
    words = [rng.randint(1, 6) for _ in range(2000)]
    items = paragraph(words, space=Glue(1, 0, 0))
    stats = {}
    greedy_line_breaks(items, 30, stats)
    assert stats["tests"] <= 2 * len(items)

History

Filling each line before starting the next is how text is set by hand and in most simple programs. Knuth and Plass gave it the name first fit in 1981, showed paragraphs where it makes much worse lines than total fit, and made total fit the method of TeX. The fact that first fit uses the fewest lines is a standard example of the greedy stays ahead argument.

References

  1. Donald E. Knuth and Michael F. Plass, Breaking paragraphs into lines, Software: Practice and Experience 11(11), 1119-1184, 1981, the first-fit method, its comparison with total fit, and the examples of bad lines that first fit makes
  2. Donald E. Knuth, The TeXbook, Computers and Typesetting volume A, Addison-Wesley, Chapter 14, How TeX breaks paragraphs into lines

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 proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
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