A page looks innocent: the algorithms behind a typeset page
Recorded: Oct. 21, 2026, 2:11 p.m.
| Original | Summarized |
A page looks innocent: the algorithms behind a typeset page News Start (news) Search speedata news This page is about development news from speedata. Links Start (news) Recent posts A page looks innocent: the algorithms behind a typeset page Version 5.8 released The manual was complete. Something was still missing. Checking PDF/UA without firing up a Windows VM Version 5.6 released Version 5.4 released Structuring layouts with the new Section element I benchmarked 6 PDF engines — the fastest is not the one I’d pick 2025 Fixing macOS notarization issues in the speedata Publisher 5.2.0 Version 5.2 released billingcat – invoicing software powered by the speedata Publisher High speed PDF generation with boxes and glue Version 5 Released speedata Publisher and AI Electronic invoices Release stable version 4.20 2024 Creating PDF with JavaScript New XPath variables semantics Microtypography and speedata Publisher and accessibility What is PDF? Part 6 - Tagged PDF What is PDF? Part 5 - Metadata Release speedata Publisher 4.18 What is PDF? Part 4 - interactive features What is PDF? Part 3 – Vector graphis What is PDF? Part 2 – Fonts What is PDF? Part 1 – the basics Debugging PDF files Page shuffling Reduce PDF file size Markdown and a layout-quine Mixing Go and Lua New logging backend New stable version 4.16 released 2023 The roadmap towards version 5 of the speedata Publisher Compatibility with older versions of the speedata Publisher New XML and XPath parser from Patrick Gundlach | October 18 2026 When you look at a page of a well-typeset book or catalog, you usually don’t notice anything special. There is some text, maybe a table, a picture or a footnote. But every line on such a page is the result of many small decisions. The algorithms behind them were invented decades ago, and people still work on them today. A page typeset with boxes and glue. The numbers are the sections of this post. Two engines, one set of problems Level Page Paragraph Word Text run Glyph PDF Most of the algorithms are the same in both systems. The difference is the architecture, and this is more important than it looks at first. Widows and orphans: a single line of a paragraph alone at the top or bottom of a page looks wrong. To avoid it, lines have to move to the next page, and then there is a gap on the current page. Footnotes Feasible breaks for a 190 pt column in Latin Modern 10 pt. The cheapest path has a loose fifth line (107,969 demerits), because all other paths start with worse lines. You can try it yourself. Change the width of the column and see how the line breaks move. Sometimes a line far away from the end changes: The full version of the demo shows more of what the algorithm sees: for each line the adjustment ratio (how much the spaces are stretched or shrunk), the badness and the demerits. You can also change all the parameters that TeX uses for the decision. Font expansion: the glyphs can be made a little bit wider or narrower, so the line breaker has more freedom. I wrote about this in Microtypography and font expansion. 3. The word Ligatures: “f” followed by “i” can become one glyph “fi”. All these rules are in the font itself, in the OpenType tables GSUB (substitution) and GPOS (positioning). The program that reads these tables and applies them is the shaper. The reference is HarfBuzz. It is used by browsers, LibreOffice and nowadays also by LuaTeX, and so by the speedata Publisher. boxes and glue uses a Go port of HarfBuzz, so everything stays in Go. Text Loading HarfBuzz… ◀ ▶ More features of this font (0) Font: And here the same for Arabic. In the step with cmap, every letter still has its isolated form. Then the features init, medi and fina give each letter the form for its position in the word, and the letters connect: Text Loading HarfBuzz… ◀ ▶ More features of this font (0) Font: 5. The glyph The a of Crimson Pro. A pixel is black when its center is inside the outline. At 12 pixels per em and without hints, the letter breaks apart. Try it yourself. Move the slider and see when the letter breaks. You can also type other letters. For example, at 13 pixels per em the “m” loses its middle stem completely. Or switch on anti-aliasing. Then a pixel gets a gray level for the part the outline covers. This is the other answer to the pixel problem, and it is the reason why macOS mostly ignores hints. Text Anti-aliasing (gray levels) Font: Hints are instructions in the font. They tell the rasterizer how to move the outline to the pixel grid at small sizes, so that all stems have the same width and the x-height is on a full pixel. The typesetting engine does not use them. It calculates everything in the design units of the font, and these do not depend on any device. When you look at the PDF on a screen, the PDF viewer can use the hints. On paper they don’t matter at all. So this is the one level in this post that the typesetter does not have to care about. BT Beitragsnavigation Version 5.8 released Home |
The article, authored by Patrick Gundlach, explores the intricate algorithms and processes that underpin the typesetting of a page, presenting a comparative analysis between two systems: the speedata Publisher, which leverages LuaTeX for typographic operations, and boxes and glue, a Go-based library that independently implements these algorithms. Gundlach traces the typographic journey from the macro-level page layout down to the micro-level representation within a PDF file, illustrating how each system handles the six distinct levels of typesetting. The speedata Publisher relies on LuaTeX to perform the majority of typographic work, while the Publisher itself manages page placement and interactivity. In contrast, boxes and glue is a modular Go library where each typographic level is encapsulated as its own package, allowing for independent use, testing, or replacement. The fundamental algorithms across both systems are largely shared, with the primary differences lying in their architectural design. At the first level, the page, Gundlach addresses the fundamental question of what content appears on which page. The speedata Publisher employs a custom page model featuring a grid, areas, and explicit positions, bypassing the powerful but complex TeX page builder. It handles common challenges such as widows and orphans by relocating lines to avoid isolated paragraphs, tables across pages by splitting tables while repeating headers and adding continuation footers, and floats by positioning images near their referencing text without strict fixed placement. Footnotes, though seemingly straightforward, are among the most complex, as they must remain with their reference and can require moving together or splitting across pages; the speedata Publisher uses insertions to track space, while boxes and glue manages footnotes in the HTML layer, ensuring the reference and footnote move together or are split appropriately. Moving to the paragraph level, the focus is on line breaking decisions. Gundlach explains that a naive approach of filling lines word by word leads to uneven line lengths, while the Knuth and Plass algorithm, published in 1981, treats the entire paragraph as a graph of feasible break points. Each break point is a node, and each possible line is an edge with weights representing demerits (a combination of badness and penalties for hyphenation or hyphenation in consecutive lines). The optimal paragraph is the minimum-cost path from start to end, as demonstrated with a graph from the fairy tale "The Frog King". Gundlach notes that boxes and glue implements this same algorithm, and the resulting demo allows users to adjust column width, viewing how line breaks shift, as well as to examine detailed metrics like adjustment ratios, badness, and demerits for each line. Two additional refinements are font expansion, which allows glyphs to be slightly wider or narrower to increase break flexibility, and hanging punctuation, which positions hyphens and quotes to straighten line edges. At the word level, hyphenation is addressed. Gundlach explains that a full dictionary of hyphenations would be impractical, so TeX uses patterns: a pattern is a segment of a word with numeric markers between letters, where odd numbers permit a break and even numbers forbid it, with the highest number prevailing. An example with the word "hyphenation" under US English patterns is provided, showing how patterns combine to yield the break points hy-phen-ation. The patterns are carefully chosen to avoid incorrect breaks. boxes and glue employs the same pattern files and algorithm as TeX, as evidenced by debug output. The text run level deals with shaping, the transformation from Unicode characters to PDF glyphs. This process involves complex rules such as ligatures (e.g., "fi" becoming "fi"), kerning (adjusting glyph positions), contextual forms (e.g., different letter shapes in Arabic), reordering (vowel signs before consonants), and bidirectional text handling (bidi algorithm). The reference implementation is HarfBuzz, which is compiled into LuaTeX and thus the speedata Publisher; boxes and glue uses a Go port of HarfBuzz. A live demo in the article allows users to step through the shaping process, visualizing how characters are converted to glyph IDs and then transformed by GSUB and GPOS tables. The demo can be used with various fonts, including Arabic, to illustrate contextual forms. At the glyph level, Gundlach examines the font file structure: an OpenType font is a database containing tables such as cmap (character to glyph mapping), hmtx (widths), and glyf/CFF (outlines), along with GSUB and GPOS tables for shaping rules. Variable fonts and color fonts add additional complexity. Hinting is discussed as a mechanism for rasterization, where glyphs are drawn from pixel grids; at low resolution, hints guide the rasterizer to maintain consistent stem widths and x-height. However, the typesetting engine operates in design units, independent of pixel sizes, and thus does not rely on hints; the PDF viewer may use them for display, but this level is beyond the typester's immediate concern. Finally, at the PDF level, Gundlach details how text is represented in a PDF file. A line of text is stored as glyph IDs in the TJ operator, with positioning offsets in thousandths of font size, including adjustments for justification and kerning. Fonts are embedded with a subset containing only used glyphs, and text is not stored as characters but as glyph IDs, which complicates copying and requires a ToUnicode table for accessibility. For PDF/UA, each text piece is tagged with its role (heading, paragraph, etc.). The article includes a sample PDF snippet showing the start of a first line, demonstrating the TJ operator and embedded font. Throughout, Gundlach emphasizes that the levels are not entirely separate; a ligature from shaping influences hyphenation possibilities, and a color change can alter space in PDF. The most interesting bugs often arise at the boundaries between levels, which is why boxes and glue keeps each level as an independent package. The article concludes by noting that each level could warrant its own dedicated post, and invites readers to follow further by contacting the author on mastodon. |