Skip to main content
Recipe number 184

Cookbook · Chapter 2 · Type & text

Justified prose without stacked words at the line edges

One page of Dickens set twice in a narrow measure: the first proof reports and marks every stack, the second weighs them in the line breaker.

  • Trim 115 × 180 mm
  • 1 column
  • Spectral 9.6/13.4
  • Cormorant Garamond
  • Spectral SC
  • 8 pages
  • Level
  • Postext 1.73.0
  • Laid out in 36 ms
  • 180 lines of code

In short

When two lines in a row end or start with the same word, the eye can slip to the wrong line. The book is set twice: once showing where that happens, once with the lines broken so it doesn't.

What you'll build

Two proofs of a pocket page, 115 × 180 mm, with the opening of A Christmas Carol justified in Spectral on an 83 mm measure. A narrow measure leaves the line breaker few choices, and in five places two lines in a row end or begin on the same word: sole over sole, his over his, No over No. The first proof is set with stacks: 'warn'. It changes nothing in the breaks, reports each stack, marks both words with a pale red band and lists them on a slip after the colophon. The second proof is set with 'avoid', and four of the five are gone. The Spanish edition sets the opening of Clarín's ¡Adiós, Cordera! the same way.

This recipe answers

  • How do I keep two lines in a row from ending or starting on the same word?

The short answer

script.js · lines 41–58in full code
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
  hyphenation: { enabled: true }, optimalLineBreaking: true, // stacks need the K–P breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A stack: two lines in a row that end on the same word or the same last characters
  // (“sole” over “sole”), or that start alike (“The” over “the”). 'warn' reports each one
  // and changes nothing; 'avoid' adds stackPenalty to the demerits of every break that
  // makes one, so the breaker sets the paragraph another way where the spacing allows.
  stacks: 'avoid', // the first proof sets 'warn' (see proofs)
  // Three characters by default; the Spanish rule counts a repeated syllable (co-/co-).
  stackMinCharacters: t({ en: 3, es: 2 }),
  // Default 3000, the cost of two hyphens in a row; a monosyllable (“his”, “lo”) costs twice.
  // 3000 kept two stacks of the first proof per edition: 10000 trades them for looser lines.
  stackPenalty: 10000,
  maxWordSpacing: 2, // the default: past it a line is never set, stack or not
};

Stacks reported in the first proof and weighed in the second

Ingredients

Type
Spectral, Spectral SC, Cormorant Garamond (SIL OFL 1.1)
Assets
  • carol-1100.jpg
  • cordera-1100.jpg
  • Painting: Scrooge's counting-house on a foggy Christmas Eve (Generated With Diffusion Models, original)
  • Painting: Rosa, Pinín and the Cordera by the telegraph pole (Generated With Diffusion Models, original)

Method

#1 · Report first, then weigh

script.js · lines 41–58in full code
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
  hyphenation: { enabled: true }, optimalLineBreaking: true, // stacks need the K–P breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A stack: two lines in a row that end on the same word or the same last characters
  // (“sole” over “sole”), or that start alike (“The” over “the”). 'warn' reports each one
  // and changes nothing; 'avoid' adds stackPenalty to the demerits of every break that
  // makes one, so the breaker sets the paragraph another way where the spacing allows.
  stacks: 'avoid', // the first proof sets 'warn' (see proofs)
  // Three characters by default; the Spanish rule counts a repeated syllable (co-/co-).
  stackMinCharacters: t({ en: 3, es: 2 }),
  // Default 3000, the cost of two hyphens in a row; a monosyllable (“his”, “lo”) costs twice.
  // 3000 kept two stacks of the first proof per edition: 10000 trades them for looser lines.
  stackPenalty: 10000,
  maxWordSpacing: 2, // the default: past it a line is never set, stack or not
};

A stack is two lines in a row that end on the same word or the same last characters, or that start alike. stackMinCharacters sets how many characters make a stack: three by default, spaces included, with accents and case left out, so The over the counts. 'warn' only reports, which is how a typesetter first sees where a text stacks. 'avoid' adds stackPenalty to the demerits of every break that would make one, and the Knuth–Plass breaker looks for another way to break the paragraph. It needs optimalLineBreaking: the greedy breaker has no demerits to add to.

Spanish typesetting manuals count a stack as a fault of composition, beside rivers and runs of hyphens. Coming back to the left edge, the eye can catch the repeated word on the wrong line and read a line twice or skip one; at the right edge the repetition reads as an echo. The Spanish rule covers a repeated syllable as well as a word, so the Spanish edition sets stackMinCharacters to 2.

The default penalty, 3000, is what two hyphens in a row cost, and a repeated word of one syllable costs twice. In this measure 3000 left two stacks in each edition, because the alternative was a line looser than the breaker would accept. At 10000 it takes the looser lines. maxWordSpacing stays at its default of 2: a tighter limit gave the breaker no other break to choose, and 'avoid' changed nothing.

#2 · Mark the stacks in the text

script.js · lines 173–201in full code
// A warning names its first line by its place in the source. The repeated edge of that
// line and the next is found in each line's stretch of the source and the whole word
// around it wrapped in :mark[…]: a band under ordinary text, so the breaks stay the same.
const LETTER = /[\p{L}\p{N}’-]/u;
const edgeOf = (text, n, end) => { // the words at a line's edge holding its first/last n
  const s = text.replace(end ? /[^\p{L}\p{N}]+$/u : /^[^\p{L}\p{N}]+/u, '');
  const cut = end ? s.lastIndexOf(' ', s.length - n) + 1 : s.indexOf(' ', n);
  return end ? s.slice(cut) : s.slice(0, cut < 0 ? undefined : cut);
};
function markStacks(source, doc, stacks) {
  const lines = doc.blocks.flatMap((b) => b.lines.map((line, i) => [line, b.lines[i + 1]]));
  const spans = new Map(); // start → end of each marked word in the source
  for (const w of stacks) {
    const pair = lines.find(([line]) => line.sourceStart === w.sourceStart);
    for (const line of pair?.[1] ? pair : []) {
      const piece = edgeOf(line.text.trim(), w.text.length, w.edge === 'end');
      const range = source.slice(line.sourceStart, line.sourceEnd);
      let from = line.sourceStart
        + (w.edge === 'end' ? range.lastIndexOf(piece) : range.indexOf(piece));
      if (from < line.sourceStart) continue;
      let to = from + piece.length; // a piece of a hyphenated word takes the whole word
      while (from > 0 && LETTER.test(source[from - 1])) from--;
      while (to < source.length && LETTER.test(source[to])) to++;
      if (!/[*_[\]\n]/.test(source.slice(from, to))) spans.set(from, to);
    }
  }
  return [...spans].sort(([x], [y]) => y - x).reduce((md, [from, to]) => `${md.slice(0, from)}`
    + `:mark[${md.slice(from, to)}]{style="stack"}${md.slice(to)}`, source);
}

Each warning gives the source position of its first line, so the script finds that line and the next one in the built document, takes the repeated edge of each and wraps the whole word in :mark[…]. A mark paints a band under ordinary text and leaves the line breaks alone. Only whole words are marked: a mark around part of a word changes how that word is hyphenated, and then the lines no longer break where the warning was found.

First proof, page 2: sole over sole at the line ends, then even over event and The over the at the starts.

#3 · Two proofs from one text

script.js · lines 205–224in full code
const quote = (s) => t({ en: `“${s}”`, es: `«${s}»` });
const SIDE = { end: t({ en: 'end', es: 'final' }), start: t({ en: 'start', es: 'principio' }) };
const tally = (n) => t({ en: `${n} stack${n === 1 ? '' : 's'}`,
  es: `${n} repetici${n === 1 ? 'ón' : 'ones'}` });
const byPage = (stacks) => Object.entries(Object.groupBy(stacks, (w) => w.pageIndex + 1))
  .map(([page, list]) => `${t({ en: 'p.', es: 'pág.' })} ${page}: ${list.map((w) =>
    `${quote(w.text)} (${SIDE[w.edge]})`).join(', ')}.`);
const slip = (mode, stacks) => ['', `:::callout{type="proof" title="${mode === 'warn'
  ? t({ en: 'First proof', es: 'Primeras pruebas' })
  : t({ en: 'Second proof', es: 'Segundas pruebas' })}"}`,
`${t({ en: 'Set with', es: 'Compuesto con' })} stacks: '${mode}' · ${tally(stacks.length)}.`,
...byPage(stacks).flatMap((line) => ['', line]), ':::', ''].join('\n');
const build = (md, stacks) => buildDocumentWithFonts({ markdown: md, resources },
  { ...config, bodyText: { ...bodyText, stacks } }, kitFonts(FONTS));
async function proof(mode) {
  const plain = await build(markdown, mode); // pass 1: where the stacks are
  const stacks = (plain.contentWarnings ?? []).filter((w) => w.kind === 'stack');
  return build(markStacks(markdown, plain, stacks) + slip(mode, stacks), mode); // pass 2
}
const docs = { warn: await proof('warn'), avoid: await proof('avoid') };

Each proof is built twice. The first build finds the stacks. The second sets the same text with the marks and a slip appended after the colophon, so the slip falls on the last page. The pen keeps the first build of each proof, the plain text, out of the published pages: capture.doc lists the two marked builds, [1, 3].

Second proof, page 2: the same paragraphs broken another way. Only even over event is left.

The stack left in the English edition is even over event: the two words share their first three letters, and every other break of that paragraph cost more. In Spanish, with two characters, the first proof finds five stacks, including co in con over como and ar in levantar over vacilar, and the second proof has none.

#4 · The opener over the text

script.js · lines 62–77in full code
const PICTURE = { width: MEASURE, height: 11 * LINE }; // 83 × 52 mm, the painting's 3:2
const at = (to, edge, y, size) => ({ anchor: { to, edge }, offset: { x: mm(0), y: mm(y) },
  ...(size && { size }) });
const opener = {
  enabled: true, minHeight: pt(16 * LEAD), // the text starts on the seventeenth line
  slot: { elements: [
    { kind: 'image', id: 'art', resourceId: '{attr.art}', fit: 'cover', placement: at('container',
      'top', 0, { width: mm(PICTURE.width), height: mm(PICTURE.height) }) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: LABEL, fontWeight: 600,
      fontSize: pt(8.5), letterSpacing: pt(1.7), color: col('accent'), align: 'left',
      placement: at('container', 'top-left', PICTURE.height + 5.5) },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, italic: true,
      fontWeight: 500, fontSize: pt(27), lineHeight: 1.05, color: col('ink'), align: 'left',
      placement: at('#kicker', 'below', 1.5, { width: mm(MEASURE), height: 'auto' }) },
  ] },
};

The heading's art attribute names the painting, so one style serves both editions. minHeight holds sixteen lines and the text starts on the seventeenth, on the same grid as the pages that follow.

#5 · Running heads and a drop folio

script.js · lines 81–93in full code
const head = (id, content, parity, edge, x, extra = {}, y = 10.5) => ({ kind: 'text', id,
  content, parity, pages: 'body', fontFamily: LABEL, fontWeight: 500, fontSize: pt(8),
  letterSpacing: pt(1.2), color: col('muted'),
  placement: { anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(y) } }, ...extra });
const folio = { fontFamily: TEXT, letterSpacing: pt(0), color: col('ink') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-author', '{author}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{title}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'odd', 'bottom-right', -OUTER,
  { ...folio, pages: 'opener' }, -11)] }; // the opener's folio sits at the foot

The author goes on the verso and the title on the recto, each beside its folio. On the opener the heads are off and the folio drops to the foot.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 184 · Prose without stacks ═════════════════════════════
// https://postext.dev/en/cookbook/prose-without-stacks
// Code: MIT · Text: Dickens, 1843; Clarín, 1893 (public domain) · Paintings: diffusion model
// Fonts: Spectral, Spectral SC, Cormorant Garamond (SIL OFL 1.1) · Needs postext ≥ 1.73.0
//
// A pocket edition set twice from the same text. The first proof keeps the line breaks the
// breaker finds and reports every stack (two lines in a row that end or start alike); the
// second weighs each stack in the breaker's demerits and sets the paragraph another way.
// Each proof marks its stacks in the text and lists them on a slip after the colophon.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'prose-without-stacks';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a proofreader's red pencil over a warm book ink
const palette = {
  ink: '#241f1b', // text: a warm near-black
  accent: '#8e2f1d', // kicker, the slip's stripe and label: the red of a proof pencil
  mark: '#f4cfc2', // the band under a stacked word, pale enough for ink on top
  tint: '#f5efe6', // the slip's background
  rule: '#d2c8bb', // hairlines
  muted: '#6b6158', // running heads, 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: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [TEXT, LABEL, DISPLAY] = ['Spectral', 'Spectral SC', 'Cormorant Garamond'];
const [BODY, LEAD] = [9.6, 13.4]; // pt
const LINE = (LEAD * 25.4) / 72; // mm: one line, 4.73
const [TRIM_W, TRIM_H, TOP, INNER, OUTER, LINES] = [115, 180, 17, 15, 17, 30];
const MEASURE = TRIM_W - INNER - OUTER; // 83 mm: about 50 characters, a narrow pocket measure

// #region answer: stacks reported in the first proof and weighed in the second
const bodyText = {
  fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
  boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
  textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
  hyphenation: { enabled: true }, optimalLineBreaking: true, // stacks need the K–P breaker
  avoidWidows: true, avoidOrphans: true, avoidRunts: true,
  // A stack: two lines in a row that end on the same word or the same last characters
  // (“sole” over “sole”), or that start alike (“The” over “the”). 'warn' reports each one

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

#Count only whole short words

Three characters is the default. With five, short words such as his and No no longer count as stacks, and the breaker keeps the tighter breaks around them.

-  stackMinCharacters: t({ en: 3, es: 2 }),
+  stackMinCharacters: 5,

#Set the book with the default penalty

The default keeps the spacing tighter and accepts two stacks per edition where breaking around them would open a line further.

-  stackPenalty: 10000,
+  stackPenalty: 3000,

Pitfalls

Layout warning · stack

Stack

Why. Two lines in a row of a paragraph, in one column, end on the same word or the same last bodyText.stackMinCharacters characters (3 by default, spaces included), or start alike: “…in the” over “…on the”. Accents and case do not count, and only scripts that separate words with spaces have stacks. With bodyText.stacks on 'warn' every stack is reported; on 'avoid', the ones the line breaker kept because no setting within the word spacing avoided them for less than bodyText.stackPenalty. The engine lists each in doc.contentWarnings with the repeated text, the edge (end or start), the two lines and their page.

Fix. Set bodyText.stacks to 'avoid': the line breaker sets the paragraph otherwise where the word spacing allows. A stack that stays costs more to avoid than bodyText.stackPenalty: raise the penalty to trade looser lines for it, or reword one of the two lines. In a port of an existing book keep 'warn': the port reproduces the original's breaks. Docs →

  • Stacks are found in the lines as broken. Change the trim, the font size or the text and the first proof finds different ones, so read the warnings of every build and don't copy positions from an earlier one.
  • Stacks are counted inside a paragraph, and only in scripts that put spaces between words: two paragraphs that both open with Scrooge make no stack, and Chinese or Japanese text never reports one.

Credits

Text
  • A Christmas Carol (1843), the opening of Stave One, from Project Gutenberg eBook #46, with typographic quotes and dashes · Charles Dickens · public domain
  • ¡Adiós, Cordera!, the opening of the story, from El Señor y lo demás son cuentos (Madrid, 1919), with « » quotation marks · Leopoldo Alas, Clarín · public domain
Images
  • Painting: Scrooge's counting-house on a foggy Christmas Eve · Generated With Diffusion Models · original
  • Painting: Rosa, Pinín and the Cordera by the telegraph pole · Generated With Diffusion Models · original
Fonts
Spectral (SIL OFL 1.1) · Spectral SC (SIL OFL 1.1) · Cormorant Garamond (SIL OFL 1.1)
Sandbox