← .fab

Mathematics

Why optimal beats greedy

A paragraph has many possible sets of line breaks. Choosing them one at a time is easy and slightly wrong. Choosing them all at once is a shortest-path problem, and it has been solved since 1981.

The greedy method, and what it costs

First-fit takes each word in turn and puts it on the current line if it fits. When it does not fit, it breaks. The decision is local: nothing that happens later can revise a break already made. Slack that could have been distributed across several lines instead piles up wherever the algorithm happened to run out of room, and the eye finds that line every time.

Every web browser breaks lines this way, and every EPUB reader is a browser. So a book delivered as EPUB is line-broken greedily on the reader's device, no matter how it was typeset before.

Badness

Knuth and Plass begin by measuring how badly a single line fits. Let L be the target measure and W the natural width of the material on the line. The elastic material between words — glue — has a total stretchability Y and a total shrinkability Z. The adjustment ratio is

r = (L − W) / Y   when W < L  (the line must stretch)
r = (L − W) / Z   when W > L  (the line must shrink) r = 0 is a perfect fit. r = 1 means every gap is stretched to its full permitted amount. r < −1 means the line cannot shrink enough and the break is infeasible.

Badness is that ratio, cubed, so that a line which is twice as loose is much more than twice as bad:

b = 100 · |r|3 Cubing is the whole trick. It makes one very loose line cost more than several slightly loose ones, which is exactly the judgement a compositor makes by eye.

Demerits, and the sum over the paragraph

Badness judges one line. Demerits turn it into something that can be summed over a paragraph, adding a per-line cost l and any penalty p attached to the breakpoint — a hyphenation penalty, for instance:

d = (l + b)2 + p·|p|   (sign-preserving penalty term) Squaring again favours evenness. Additional demerits are charged when two consecutive lines end in hyphens, or when adjacent lines sit in very different fitness classes — a tight line directly under a very loose one is visibly worse than the two badness values alone suggest.

The problem is then stated in one line: choose the set of breakpoints that minimises the total demerits of the paragraph. Model each feasible breakpoint as a node and each possible line as an edge weighted by its demerits, and this is a shortest path through a directed acyclic graph. Dynamic programming solves it exactly.

Keeping it linear

A naive dynamic program considers every pair of breakpoints, which is quadratic in the length of the paragraph. A line of running prose holds a bounded number of words, so the engine bounds the inner loop to a window of at most sixteen words per line. The cost becomes O(16n), linear in paragraph length, while remaining exact for every line the window can express.

This lives in one shared function, FabLayoutPlanner._optimal_break_positions, and all flowed text goes through it: uniform prose, inline-styled rich lines and table cells alike. Greedy survives only as a pathology fallback beyond roughly four thousand words in a single paragraph. A build gate named wrap-quality fails on purpose if any text is ever routed back to greedy, in every justification mode.

Judged by a metric it does not optimise

A model that grades its own homework proves nothing. The engine minimises demerits, but it is measured with a different and simpler yardstick that the optimiser never sees. For each non-final line, the residual space is

ri = (Wmax − Wi) / Wmax

RMS-raggedness = √( mean( ri2 ) )
max-raggedness = max( ri ) Lower is tighter. The maximum is the honest one: it is the single ugliest line in the paragraph, the one a reader actually notices.

Against that independent measure, optimal breaking reduces the ugliest line from 16.9% to 10.0% residual space across the Fabylon catalogue — the figure the wrap-quality gate defends. A synthetic run on this engine on 2026-08-17 gives a consistent picture with different absolute values, and also shows where greedy wins. Both sets of numbers, and the command that produces the second, are on the benchmarks page.

Three more instruments in the same pass

Font expansion — the hz-program

When a line must stretch, the alternative to widening the word gaps is to widen the letters. The engine scales glyphs on loose justified lines by at most three percent (e ≤ 1.03), which damps the variance in inter-word spacing rather than the spacing itself. Measured effect: inter-word stretch variance drops 19%, enforced by the microtype-expansion gate. The scaling is content-preserving by construction — glyphs are scaled, none are added or removed — and the PDF backend draws them with per-span horizontal scaling so that what was measured is what is rendered.

Optical margins — protrusion

A period at the end of a justified line is mostly white space. Aligned mathematically, it makes the margin look ragged; hung slightly past the margin, the edge looks straight. The same applies to an opening quotation mark protruding into the left margin.

Most implementations use a hand-made table of protrusion factors per typeface. This engine derives the factors from each embedded font's own ink geometry, so the optical edge tunes itself to fonts no hand-made table ever covered (microtype-autocalib). Measured effect: optical edge RMS error falls from 2.41 pt to 0.00 pt, enforced by microtype-quality. Protrusion is a horizontal shift only, so the text content is untouched.

Kerning

The engine reads GPOS pair positioning from the embedded font directly, and supplements it with optical kerning for pairs the font does not cover.

Why this can only live in the file

Each of these decisions depends on the exact measure, the exact embedded font and the exact glyph metrics. A reader that reflows text has none of that at the moment it breaks a line. This is the argument for storing decided lines in the container rather than recomputing them on the device — and it is why .fab stores geometry as data.

The reading measure

None of this helps if the line is the wrong length to begin with. Legibility research puts comfortable line length in a band of roughly 45 to 80 characters, so the engine caps the reading measure at about 66 characters regardless of how wide the screen is. With the cap, measured lines fall inside the comfort band 88–95% of the time; without it, 9–10%.

Benchmarks The numbers, and how to repeat them The full measurement table, the exact command, and the paragraph lengths where greedy is better. Specification Where the decided lines are stored The container layout, the manifest and the page records that carry this geometry.

Sources: Breaking Paragraphs into Lines, D. E. Knuth and M. F. Plass, Software: Practice and Experience 11(11), 1981 — for badness, demerits and the shortest-path formulation. Implementation, gates and measured figures: the Fabylon engine, verified 2026-08-17.