In short
A small magazine about type, set in narrow columns with both edges of the text lined up. It shows how to keep the gaps between words even, beside a version with its uneven lines marked in yellow.
What you'll build
Issue 12 of Galley, a type lab's journal, set on A5 in two columns of about forty characters, where a justified line has only five or six word spaces to take up the slack. The opener draws the Knuth–Plass model on a graphite band: a line of word boxes whose yellow springs of glue stretch to fill the measure. The essay explains why narrow columns go loose and prints the settings behind each rule in mono between its paragraphs. At the foot of page 3 a bench test sets one paragraph ragged, justified without hyphens and justified with them. The pen also sets the issue with first-fit breaking and the widow and orphan guards off, and shows both page 2s side by side above the pages, as on this recipe's card, with loose lines washed in highlighter yellow and lone lines and runts tagged in the margin.
This recipe answers
- How do I get good justification and hyphenation for Spanish, French or German text?
- How do I avoid widows, orphans and one-word last lines (runts), and keep a heading with its text?
- Why is one line set ragged or over-stretched (URLs, long compounds, long words in cells)?
- How do I find out what is wrong with my document (warnings, overflow, non-converging layout)?
The short answer
// Knuth–Plass breaking, hyphenation and the widow, orphan and runt penalties are all on by
// default. A narrow column also needs a tighter fence round the glue, in multiples of a
// normal word space (defaults 0.6 and 2): lines past the upper fence cost more than any
// hyphen, so the breaker hyphenates or re-breaks the paragraph before it stretches that far.
const FENCES = { minWordSpacing: 0.8, maxWordSpacing: 1.6 };
const bodyText = { // config().bodyText
fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
firstLineIndent: mm(4), indentAfterHeading: false, // justified and hyphenated by default
...FENCES,
};
// Hyphenation follows the document's locale:
const locale = t({ en: 'en-us', es: 'es' }); // config().locale: each edition's patterns
// The control: first-fit breaking, which sets each line once and moves on, with the widow and
// orphan guards off (runts are priced inside Knuth–Plass only). Same text, fonts and measure.
const GREEDY = { optimalLineBreaking: false, avoidWidows: false, avoidOrphans: false };
const control = () => ({ ...config(), bodyText: { ...bodyText, ...GREEDY } });
One design, two line breakers: Knuth–Plass inside fences, greedy without
Ingredients
- Features
- Optimal line breaking (Knuth–Plass)Widows, orphans and runtsWarnings and diagnosticsHyphenation and document languageIndents, alignment and paragraph spacingColumns in a box or in the textNested boxesCallout boxesDesigned openersPictures in page designsHeading attributesParagraph stylesPages on a canvasFigures and tables as resourcesSemantic colour paletteRunning heads and foliosHeads by page role
- Also uses
- Full-width chapter band
- Type
- Petrona, Bricolage Grotesque, Source Code Pro (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · Tighten the fences, keep the guards
The code for this step is the short answer above. Knuth–Plass, hyphenation, the widow, orphan and runt penalties and keep-with-next headings are on by default, so the published edition only narrows the word-spacing bounds to 0.8 and 1.6 times a normal space (the defaults are 0.6 and 2). A line past the upper bound costs more than any hyphen or runt, so the breaker tries other breaks first; delete the two bounds and this essay sets two lines past 1.6. Hyphenation follows locale: 'es', 'fr' and 'de' get their own TeX patterns, a regional tag such as 'es-ES' takes its language's, and a language with no patterns is hyphenated as American English, with a warning on the console.
#2 · Mark loose lines from the layout tree
// findLooseLines gives the justified lines whose word spaces stretch past a threshold, here the
// upper fence. The rest is read from the VDT: a line past 3× is set ragged (line.ragged), and a
// paragraph cut by a column is two blocks.
function marks(doc, page) {
const body = doc.pages.flatMap((p) => p.columns.flatMap((c) => c.blocks)).filter((b) =>
b.type === 'paragraph' && b.containerId === undefined && b.textAlign === 'justify');
const loose = findLooseLines(doc, { threshold: FENCES.maxWordSpacing, pageIndex: page.index });
const out = loose.map(({ x, y, width: w, height: h }) => ({ x, y, w, h, kind: 'loose' }));
for (const column of page.columns) {
for (const b of column.blocks.filter((x) => body.includes(x))) {
const parts = body.filter((o) => o.contentIndex === b.contentIndex);
b.lines.forEach((line) => {
const at = { x: b.bbox.x, y: line.bbox.y, w: b.bbox.width, h: line.bbox.height, column };
if (line.ragged) out.push({ ...at, kind: 'loose' }); // past 3×: no ratio, set ragged
if (b.lines.length === 1 && parts.length > 1) { // Postext's names (see the essay):
out.push({ ...at, kind: b === parts[0] ? 'widow' : 'orphan' }); // foot : head
} else if (line.isLastLine && !/\s/.test(line.text.trim())) {
out.push({ ...at, kind: 'runt' }); // one word alone on a paragraph's last line
}
});
}
}
return out;
}
const TAGS = t({ en: { widow: 'widow', orphan: 'orphan', runt: 'runt' },
es: { widow: 'viuda', orphan: 'huérfana', runt: 'corta' } });
function paintMarks(canvas, list, scale) {
const ctx = canvas.getContext('2d');
ctx.setTransform(scale, 0, 0, scale, 0, 0); // page px from here on
for (const m of list) { // loose lines: a wash; lone lines and runts: a tag in the margin
const loose = m.kind === 'loose';
ctx.globalCompositeOperation = loose ? 'multiply' : 'source-over'; // the ink shows through
ctx.fillStyle = loose ? palette.marker : palette.graphite;
if (loose) { ctx.fillRect(m.x - 2, m.y + 1, m.w + 4, m.h - 1); continue; }
ctx.font = `600 ${m.h * 0.48}px "${MONO}"`;
const w = ctx.measureText(TAGS[m.kind]).width + m.h * 0.5;
const x = m.column.index === 0 ? m.x - w - m.h * 0.35 : m.x + m.w + m.h * 0.35;
ctx.fillRect(x, m.y + m.h * 0.12, w, m.h * 0.8);
ctx.fillStyle = palette.marker;
ctx.fillText(TAGS[m.kind], x + m.h * 0.25, m.y + m.h * 0.7);
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
findLooseLines returns the justified lines whose word spaces stretch past a threshold, here the upper bound, each with the band a highlight covers (Loose lines in your own canvas). marks() adds what that list leaves out, read from the VDT: a line past 3× has no ratio, because the engine sets it ragged and flags it line.ragged instead, and a paragraph split between two columns comes back as one block per fragment, which is how the lone lines are found. At forty characters the bounds alone do not keep every line under 1.6; while the essay was being copy-fitted, the marks showed which sentences to reword.
#3 · Lay the control beside the published page
function compare(pairs) {
document.head.insertAdjacentHTML('beforeend', `<style>
#compare { background: ${palette.graphite}; color: ${palette.haze}; padding: 36px 24px 44px;
font: 500 12px/1.4 "${MONO}", monospace; } #compare > * { max-width: 860px; margin: 0 auto; }
#compare h2 { font: 800 clamp(30px, 6vw, 72px)/0.95 "${DISPLAY}", sans-serif; color: #fff;
margin: 6px auto 26px; letter-spacing: -0.01em; } #compare figure { margin: 0; }
#compare .kicker { color: ${palette.marker}; letter-spacing: .16em; text-transform: uppercase; }
#compare .pair { display: grid; grid-template-columns: 1fr 1fr; gap: 28px; }
#compare canvas { width: 100%; display: block; }
#compare figcaption { margin-bottom: 12px; text-transform: uppercase; letter-spacing: .12em; }
#compare figcaption b { display: block; margin-bottom: 6px; color: #fff; letter-spacing: 0;
font: 800 clamp(18px, 2.4vw, 26px)/1 "${DISPLAY}"; text-transform: none; }
@media (max-width: 640px) { #compare .pair { grid-template-columns: 1fr; } }</style>`);
const section = Object.assign(document.createElement('section'), { id: 'compare' });
section.innerHTML = `<p class="kicker">${t({ en: 'Same text · same design · page 2',
es: 'El mismo texto · el mismo diseño · página 2' })}</p><h2>${t({
en: 'Two line breakers', es: 'Dos formas de cortar' })}</h2><div class="pair"></div>`;
for (const [name, doc] of pairs) {
const page = doc.pages[1];
const list = marks(doc, page); // one walk per edition: the counts and the paint share it
const n = (...kinds) => list.filter((m) => kinds.includes(m.kind)).length;
const counts = `${t({ en: 'loose', es: 'flojas' })} ${n('loose')} · `
+ `${t({ en: 'lone', es: 'solas' })} ${n('widow', 'orphan')} · `
+ `${t({ en: 'runts', es: 'cortas' })} ${n('runt')}`;
const figure = document.createElement('figure');
figure.innerHTML = `<figcaption><b>${name}</b><span>${counts}</span></figcaption>`;
const canvas = figure.appendChild(document.createElement('canvas'));
canvas.setAttribute('role', 'img');
canvas.setAttribute('aria-label', `${name}, ${t({ en: 'page', es: 'página' })} 2: ${counts}`);
renderPageToCanvas(page, doc, canvas, { scale: 1000 / page.width });
paintMarks(canvas, list, 1000 / page.width);
section.querySelector('.pair').append(figure);
}
document.getElementById('pages').before(section); // #pages: the desk showPages() builds
}
Both editions share one design, so every difference between the two page 2s comes from the line breaker and its guards. In English the greedy control leaves 47 of its 110 justified lines past 1.6 and 30 past 2, three of them past 3× and set ragged by the engine, while the Knuth–Plass edition keeps all 105 between 0.80 and 1.60. On page 2 the control also carries a paragraph's last line alone to the head of a column, which avoidOrphans: false allows, and ends another paragraph on a runt.
#4 · Give each setting a box of its own
// A box sets all its :::columns in one body style, so each setting is a nested box; breaks="3"
// counts a nested box as one block. The bench floats to a page foot.
const [SLIP_GAP, FRAME] = [3, 4]; // mm: between slips; the bench's frame round them
const slip = (id, body) => ({ id, background: col('paper'), marginBottom: mm(SLIP_GAP),
padding: { top: mm(2.2), right: mm(2.6), bottom: mm(2.4), left: mm(2.6) },
titleStyle: { fontFamily: MONO, fontSize: pt(6.6), fontWeight: 600, color: col('muted'),
gap: mm(1.6) }, // code keeps its case: textAlign, not TEXTALIGN
body: { fontSize: pt(8.6), lineHeight: pt(11.6), firstLineIndent: pt(0), ...body } });
const calloutStyles = [
{ id: 'bench', span: 'page', placement: 'bottom', background: col('graphite'),
columnGap: mm(FRAME), // the foot needs a FRAME too: the last slip's marginBottom is dropped
padding: { top: mm(3.4), right: mm(FRAME), bottom: mm(FRAME), left: mm(FRAME) },
titleStyle: { ...caps(7.5, 600), color: col('marker'), gap: mm(2.4) },
body: { fontSize: pt(8.6), lineHeight: pt(11.6), color: col('paper'), textAlign: 'left',
firstLineIndent: pt(0) } },
slip('ragged', { textAlign: 'left' }), // ragged text keeps its words whole by default
slip('unhyphenated', { hyphenation: false }), // justified, like the body text
slip('justified', {}), // justified and hyphenated: the body text's own settings
{ id: 'settings', backgroundEnabled: false, marginTop: pt(3), marginBottom: pt(3), // config
stripe: { enabled: true, side: 'left', width: pt(2), color: col('graphite') },
padding: { top: pt(1), right: pt(0), bottom: pt(1), left: mm(3) },
body: { fontFamily: MONO, fontSize: pt(7), lineHeight: pt(9.5), color: col('graphite'),
firstLineIndent: pt(0) } },
];
A box sets all the columns of a :::columns group in one body style, so each slip is a nested box with a body of its own, and breaks="3" stacks the ragged and the unhyphenated slips in the first column. The ragged slip needs no hyphenation: false: ragged text keeps its words whole unless bodyText.hyphenation.ragged is switched on. The bench floats to the foot of page 3 with placement: 'bottom', and its bottom padding repeats the 4 mm frame because the last slip's marginBottom is dropped at the end of the box.
#5 · Draw the model into the opener
const BAND = 104; // mm from the trim's top edge to the band's foot
const DIAGRAM = { y: 64, w: MEASURE + 8, h: 34 }; // mm: its top on the page, width, height
const LABEL = 7; // pt: the diagram's labels, tracked less than caps() so the legend fits
const text = (id, content, family, size, color, x, y, extra) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col(color), align: 'left', overflow: 'wrap',
placement: { anchor: { to: 'page', edge: 'top-left' }, offset: { x: mm(x), y: mm(y) },
size: { width: mm(MEASURE) } }, ...extra });
const opener = () => ({ // a function: the diagram's constants are defined further down
enabled: true,
slot: { elements: [
// The band reaches below the diagram, so it sets the height the opener reserves; the H1's
// default marginBottom adds a line of white, and the body starts on the second grid line
// under the band.
{ kind: 'box', id: 'band', style: { backgroundColor: col('graphite') },
placement: { anchor: { to: 'bleed', edge: 'top-left' },
size: { width: 'fill', height: mm(BAND) } } },
text('kicker', '{attr.kicker}', MONO, 7.5, 'marker', INNER, TOP, caps(7.5, 600)),
text('title', '{titleText}', DISPLAY, 29, 'paper', INNER, TOP + 5, // one line in both
{ fontWeight: 800, lineHeight: 1.02 }),
text('standfirst', '{attr.standfirst}', TEXT, 10.5, 'haze', INNER, TOP + 19,
{ italic: true, lineHeight: 1.3 }),
{ kind: 'image', id: 'diagram', resourceId: 'diagram', placement: { anchor: { to: 'page',
edge: 'top-left' }, offset: { x: mm(INNER), y: mm(DIAGRAM.y) },
size: { width: mm(DIAGRAM.w), height: mm(DIAGRAM.h) } } },
// The diagram's labels are design text: set and tracked like the opener's other labels.
...diagramLabels().map(([id, words, x, y]) => text(id, words, MONO, LABEL, 'haze',
INNER + x, DIAGRAM.y + y, { ...caps(LABEL), letterSpacing: pt(0.5) })),
] },
});
The diagram is an image element of the H1's design. As a figure it would be a page-wide top float, and a top float cited on page 1 opens page 2. The band reaches below the diagram, and an opener reserves height down to its lowest element, so the text starts under the band without a minHeight, a line further down because of the H1's default marginBottom. The labels are design text laid on the drawing's own coordinates, set and tracked like the opener's other labels.
The whole recipe
// ═══ Postext Cookbook · Nº 014 · Justification lab ════════════════════════════════
// https://postext.dev/en/cookbook/justification-lab
// Code: MIT · Text: original (CC BY 4.0) · Diagram: generated in code (CC BY 4.0)
// Fonts: Petrona, Bricolage Grotesque, Source Code Pro (SIL OFL 1.1) · Needs postext ≥ 1.34.0
// A type journal's essay set twice from one design, Knuth–Plass and greedy: the two page 2s
// side by side with their loose lines marked from the layout tree, then the published pages.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, parseMarkdownWithIssues,
findLooseLines,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'justification-lab';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Graphite, paper and one highlighter yellow; col() links each colour to its palette entry.
const palette = {
ink: '#1f2124', // text: a graphite near-black
graphite: '#2e3136', // the accent: the opener band, the bench box, folios
marker: '#ffe14d', // highlighter yellow: glue and loose lines, never type on white
haze: '#c3c7cc', // type on graphite: the standfirst, the diagram's labels
muted: '#66686c', // running heads, settings lines, the colophon
paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
{ id: 'main-color', name: 'defaults', value: { hex: palette.graphite, model: 'hex' } }, // no blue
];
const [TEXT, DISPLAY, MONO] = ['Petrona', 'Bricolage Grotesque', 'Source Code Pro'];
const [BODY, LEAD] = [9.5, 13]; // pt: body size and leading, the grid both columns share
// mm: an A5 trim, mirrored margins and a narrow gutter: two columns of about 40 characters
const [TRIM_W, TRIM_H, TOP, BOTTOM, INNER, OUTER, GUTTER] = [148, 210, 20, 20, 16, 13, 5];
const MEASURE = TRIM_W - INNER - OUTER; // mm: 119, the text width the opener aligns to
const caps = (size, weight = 500) => ({ fontFamily: MONO, fontSize: pt(size), fontWeight: weight,
letterSpacing: pt(size * 0.16), textTransform: 'uppercase' }); // tracked mono labels
// #region answer: one design, two line breakers: Knuth–Plass inside fences, greedy without
// Knuth–Plass breaking, hyphenation and the widow, orphan and runt penalties are all on by
// default. A narrow column also needs a tighter fence round the glue, in multiples of a
// normal word space (defaults 0.6 and 2): lines past the upper fence cost more than any
// hyphen, so the breaker hyphenates or re-breaks the paragraph before it stretches that far.
const FENCES = { minWordSpacing: 0.8, maxWordSpacing: 1.6 };
const bodyText = { // config().bodyText
fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
firstLineIndent: mm(4), indentAfterHeading: false, // justified and hyphenated by default
...FENCES,
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#Hyphenate a German text
The locale picks the patterns, so a German text takes 'de', or a regional tag such as 'de-AT'.
-const locale = t({ en: 'en-us', es: 'es' }); // config().locale: each edition's patterns
+const locale = 'de'; // German patterns; 'de-AT' picks them too#Mark only the worst lines
Raise the threshold from 1.6 to 2 and the highlighter marks only the lines whose spaces have more than doubled.
- const loose = findLooseLines(doc, { threshold: FENCES.maxWordSpacing, pageIndex: page.index });
+ const loose = findLooseLines(doc, { threshold: 2, pageIndex: page.index });Pitfalls
Pitfall
avoidWidows guards the foot of a column, avoidOrphans its head
Postext names the two lone lines its own way: avoidWidows (widowMinLines, widowPenalty) keeps a paragraph's first line from standing alone at the foot of a column, and avoidOrphans (orphanMinLines, orphanPenalty) keeps its last line from standing alone at the head of the next. Many style manuals give the two names the other way round, so pick the setting by where it acts. Both are on by default, except on a character grid (cjk.grid): there avoidWidows is off, and avoidOrphans too in the Japan region, so that a page holds the lines its grid counts (since postext 1.28). They work as penalties: the layout weighs each one against the empty lines that obeying it would leave. Widows, orphans and runts →
Pitfall
A 'top' float goes to the page after its citation unless it may head the citing page
By default a float never goes above its own reference, so a page-wide 'top' float cited on page N opens page N+1. Set placement.citingPage: true on the resource or its type's defaultPlacement (or layout.floatsAtCitingPage for the whole book, since postext 1.25) and it heads page N instead, the text above the reference moving down under it, when it fits within layout.maxTopFraction and the citing line stays on that page. It never heads a chapter's first page or a page after a forced break: there it still opens the next page, and 'auto' or 'bottom' can take the foot of the citing page. Figure placement →
Sandbox check · looseLine
Loose line
Why. A justified line stretches its spaces beyond the threshold, usually because of a long word, a URL or a narrow measure.
Fix. Turn on hyphenation in the right language, widen the measure, rephrase, or set the passage ragged. Docs →
- A box left at the end of a column drops to the column's foot when the columns are balanced, away from the paragraph it belongs to. Fit the copy so the column is full, as the settings box under “Fences for the glue” needed, or set
headings.balancing.closingBoxto'off', which never moves the box. - The unhyphenated slip does not show the widest gaps it would need. A justified line whose spaces would stretch past three times a normal space is set ragged at its natural spacing, in a box as in the body text, so the slip's first two lines end short of the measure. The lines under that cap stay justified, and theirs are the wide gaps the slip shows.
Credits
- Recipe
- Ignacio Ferro
- Text
- The essay “The river problem” and its Spanish version “El problema de los ríos”, the bench test and the diagram, written and drawn for this recipe · Postext Cookbook · CC BY 4.0
- Fonts
- Petrona (SIL OFL 1.1) · Bricolage Grotesque (SIL OFL 1.1) · Source Code Pro (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


