KeynoteTalk 04 · Main stage

Pages are an optimization problem

How a layout engine decides where a line, a figure or a page ends, and why the greedy answer is rarely the best one.

Ada LindqvistStaff engineer, Typesetting
The problem

A document is a long string of choices, and every choice changes the next one.

2ⁿ

ways to break a paragraph of n possible break points. We do not try them all.

1×

pass over the document for a greedy break: fast, simple, and it never looks back.

O(n²)

worst case for the shortest-path view, which sees the whole paragraph at once.

Pages are an optimization problem2 / 10
A Julia set in violet, pink and gold
A Julia set: simple rule, surprising structure.
Idea

Break lines as a shortest-path problem

In practice

Fifteen lines that find the cheapest path

breaks.rs
// best[i]: the cheapest way to end a line at break i
let mut best = vec![f64::INFINITY; n + 1];
let mut from = vec![0; n + 1];
best[0] = 0.0;
for j in 1..=n {
    for i in (0..j).rev() {
        let r = ratio(i, j, width);
        if r < -1.0 { break; }  // too full
        let cost = best[i] + badness(r);
        if cost < best[j] {
            best[j] = cost;
            from[j] = i;
        }
    }
}
Look backEach break considers every earlier break that still fits the line.
Prune earlyOnce a line is too full, nothing further back can work either.
Walk the pathFollowing from from the end yields the breaks.
Pages are an optimization problem4 / 10
“
The best way to find a good line break is to stop deciding one line at a time.
A paragraph, seen as a whole
Badness

Loose lines are punished faster than they look

r = 1: badness 100 00.511.52 stretch ratio r 0400800
Near the ideal

A line stretched by a quarter costs almost nothing.

Far from it

Double the stretch and the cost is eight times larger, because it grows with the cube.

Pages are an optimization problem6 / 10
Side by side

The same paragraph, two strategies

First fit greedy

Layout in print differs from
layout on screen because
content flows across fixed
pages and cannot scroll.
Total badness 412

Whole paragraph optimal

Layout in print differs from layout
on screen because content flows
across fixed pages and cannot
scroll.
Total badness 96
Pages are an optimization problem7 / 10
Gallery

What a page can hold

Photographs
Generated art
Soft gradients
Conic colour
Patterns
Pages are an optimization problem8 / 10
Next

From lines to whole pages

1

Lines

Pick breaks for a paragraph by the cheapest path.

Done
2

Paragraphs

Let a paragraph stretch or shrink by a line to improve the page.

Done
3

Floats

Place figures at the top or the bottom, from columns to the page.

Done
4

Wrapping

Flow text around floats at the sides of a paragraph.

Next
Pages are an optimization problem9 / 10

Questions?

Thank you. Slides, source and this PDF are made from one HTML file.