# 行首行尾不重复的两端对齐正文

> 同一页狄更斯在窄栏里排两遍：初校报出并标记每处重复，二校把重复计入断行代价，换一种断法。

- HTML版本: https://postext.dev/zh/cookbook/prose-without-stacks
- 食谱 No. 184 · 字体与文字 · 难度 2 (中级) · 输出: Canvas
- 体裁: 小说、戏剧与文学散文
- 需要 postext ≥ 1.73.0 · 已用 1.73.0 测试，日期 2026-11-10
- 页面: [1](https://postext.dev/cookbook/prose-without-stacks/en/p01.webp?v=74376510), [2](https://postext.dev/cookbook/prose-without-stacks/en/p02.webp?v=74376510), [3](https://postext.dev/cookbook/prose-without-stacks/en/p03.webp?v=74376510), [4](https://postext.dev/cookbook/prose-without-stacks/en/p04.webp?v=74376510), [1](https://postext.dev/cookbook/prose-without-stacks/en/p05.webp?v=74376510), [2](https://postext.dev/cookbook/prose-without-stacks/en/p06.webp?v=74376510), [3](https://postext.dev/cookbook/prose-without-stacks/en/p07.webp?v=74376510), [4](https://postext.dev/cookbook/prose-without-stacks/en/p08.webp?v=74376510)
- 在沙盒中打开: https://postext.dev/zh/sandbox#recipe=prose-without-stacks&lang=en (.postext: https://postext.dev/cookbook/prose-without-stacks/en/prose-without-stacks.postext)
- 最后更新: 2026-11-10
- 其他语言: [en](https://postext.dev/en/cookbook/prose-without-stacks.md), [es](https://postext.dev/es/cookbook/prose-without-stacks.md), [ca](https://postext.dev/ca/cookbook/prose-without-stacks.md), [de](https://postext.dev/de/cookbook/prose-without-stacks.md), [fr](https://postext.dev/fr/cookbook/prose-without-stacks.md), [it](https://postext.dev/it/cookbook/prose-without-stacks.md), [pt](https://postext.dev/pt/cookbook/prose-without-stacks.md), [ja](https://postext.dev/ja/cookbook/prose-without-stacks.md), [ar](https://postext.dev/ar/cookbook/prose-without-stacks.md)

## 简单来说

相邻两行以同一个词结尾或开头时，读者的目光容易跳错行。这本书排了两遍：一遍标出哪里出现重复，一遍改变断行让重复消失。

## 成品一览

两份 115 × 180 mm 口袋本的校样，排的是《圣诞颂歌》（*A Christmas Carol*）的开头，Spectral 字体，83 mm 栏宽，两端对齐。栏窄，断行算法可选的余地就少，有五处相邻两行以同一个词结尾或开头：*sole* 叠 *sole*，*his* 叠 *his*，*No* 叠 *No*。初校用 `stacks: 'warn'` 排：断行一处不改，只报出每处重复，在两个词下面加浅红色底纹，并在版权说明后的校样条上逐条列出。二校用 `'avoid'` 排，五处去掉了四处。西班牙语版用同样方法排 Clarín 的 *¡Adiós, Cordera!* 开头。

**这份食谱回答的问题:**

- 怎样避免相邻两行以同一个词结尾或开头？

## 简短回答

```js
// script.js, 行 41–58
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
};
```

## 用料

**讲解**

- [行首行尾重复](https://postext.dev/zh/docs/configuration-text.md#正文): 找出相邻两行以同一个词或相同字符结尾或开头的情况，可以只报告（bodyText.stacks: 'warn'），也可以让断行器换一种方式排这一段（'avoid'，代价为 stackPenalty）。
- [最优断行（Knuth–Plass）](https://postext.dev/zh/docs/justification.md#knuth-plass通观整个段落): 把每个段落作为整体断行，在词间距限度内使词间距均匀，而不是逐行填满。

**还用到**

- [断词与文档语言](https://postext.dev/zh/docs/justification.md#支持的语言)
- [段末孤行、段首孤行与孤字](https://postext.dev/zh/docs/configuration-page-flow.md#段首孤行段末孤行孤字与不拆分规则)
- [正文字体](https://postext.dev/zh/docs/configuration-text.md#正文)
- [设计过的章首页](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [页面设计中的图片](https://postext.dev/zh/docs/configuration-headers-footers.md#图像元素)
- [标题属性](https://postext.dev/zh/docs/document-format.md#标题属性)
- [书眉与页码](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [按页面角色显示书眉](https://postext.dev/zh/docs/configuration-headers-footers.md#文本元素)
- [对称页边距](https://postext.dev/zh/docs/configuration-page-layout.md#对称页边距)
- [标注框](https://postext.dev/zh/docs/configuration-callouts.md#标注框样式)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)
- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [高亮标记](https://postext.dev/zh/docs/document-format-inline.md#高亮标记)
- [作为资源的图和表](https://postext.dev/zh/docs/document-format-resources.md#资源)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.md#正文), [`calloutStyles`](https://postext.dev/zh/docs/configuration-callouts.md#标注框样式), [`colorPalette`](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板), [`footer`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`header`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`headings`](https://postext.dev/zh/docs/configuration-headings.md#标题), [`layout`](https://postext.dev/zh/docs/configuration-page-layout.md#版式), [`locale`](https://postext.dev/zh/docs/configuration-language.md#断词), [`markStyles`](https://postext.dev/zh/docs/configuration-styles.md#高亮样式), [`page`](https://postext.dev/zh/docs/configuration-page-layout.md#页面), [`paragraphStyles`](https://postext.dev/zh/docs/configuration-styles.md#段落样式)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体), [`registerResourceImage`](https://postext.dev/zh/docs/architecture.md#api接口), [`renderPageToCanvas`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#把页面渲染为位图)

**字体**

- Spectral (OFL-1.1), Spectral SC (OFL-1.1), Cormorant Garamond (OFL-1.1)

## 做法

### 1 · 先报出，再计入代价

```js
// script.js, 行 41–58
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
};
```

相邻两行以同一个词或相同的末尾几个字符结尾，或以相同方式开头，就算一处重复。`stackMinCharacters` 规定至少几个字符才算：默认三个，空格计入，不区分重音符号和大小写，所以 *The* 叠 *the* 也算。`'warn'` 只报告，排版的人借此先看清文本在哪里重复。`'avoid'` 给每个会造成重复的断点加上 `stackPenalty`，Knuth–Plass 断行算法于是另找一种断法。它需要开启 `optimalLineBreaking`：逐行断行没有可以累加的代价。

西班牙语的排版手册把这种重复列为排版缺陷，与“河流”和连字符阶梯并列。目光回到左边时，可能被错行上的同一个词勾住，把一行读两遍或跳过一行；在右边，重复读起来像回声。西班牙语的规则连重复的音节也算在内，不只是整个词，所以西班牙语版把 `stackMinCharacters` 设为 2。

默认代价 3000，与连续两行用连字符的代价相同；重复的单音节词代价加倍。在这个栏宽下，3000 让两个版本各留下两处重复，因为另一种断法会让某一行松到算法不肯接受。设为 10000 后，算法接受了这些稍松的行。`maxWordSpacing` 保持默认值 2：限值再紧，算法就没有别的断点可选，`'avoid'` 也就不起作用。

### 2 · 在文字上标出重复

```js
// script.js, 行 173–201
// 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);
}
```

每条警告都给出第一行在源文本中的位置。脚本在排好的文档里找到这一行和下一行，取出各自重复的边缘，再用 `:mark[…]` 包住整个词。标记只在普通文字下面画底纹，不改动断行。只标整词：如果只标半个词，这个词的连字符断法会变，行就不再断在发现警告的位置。

![Page 2.](https://postext.dev/cookbook/prose-without-stacks/en/p02.webp?v=74376510)

*初校第2页：行尾 sole 叠 sole，行首 even 叠 event、The 叠 the。*

### 3 · 同一文本的两份校样

```js
// script.js, 行 205–224
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') };
```

每份校样排两次。第一次找出重复；第二次排同样的文字，加上标记，并在版权说明后附一张校样条，所以校样条落在最后一页。每份校样的第一次排版，也就是不带标记的文字，不进入发布的页面：`capture.doc` 只列两次带标记的排版，`[1, 3]`。

![Page 2.](https://postext.dev/cookbook/prose-without-stacks/en/p06.webp?v=74376510)

*二校第2页：同样的段落换了一种断法，只剩 even 叠 event。*

英文版留下的一处是 *even* 叠 *event*：两个词前三个字母相同，而这一段的其他断法代价都更高。西班牙语版按两个字符计算，初校找到五处，其中有 *con* 叠 *como* 的 *co*、*levantar* 叠 *vacilar* 的 *ar*，二校一处也没有。

### 4 · 正文上方的章首

```js
// script.js, 行 62–77
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' }) },
  ] },
};
```

标题的 `art` 属性指定插画，一个样式就能用于两个版本。`minHeight` 占十六行，正文从第十七行开始，与后面各页落在同一网格上。

### 5 · 书眉与页脚页码

```js
// script.js, 行 81–93
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
```

左页印作者，右页印书名，各自挨着页码。章首页不印书眉，页码移到页脚。

## 完整食谱

一个文件，由食谱文件夹合成，示例文本和排版食谱的公共工具包都已内联；它自己排出页面。要运行它，把它放进空白页面的`<script type="module">`，或粘贴到新建CodePen的JS面板里（设为模块）。它从esm.sh导入postext，不需要安装或构建。

- 食谱文件夹: https://github.com/drnachio/postext/tree/main/cookbook/prose-without-stacks

### script.js

```js
// ═══ 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
  // 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
};
// #endregion

// #region opener: the painting over the measure, kicker and title under it
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' }) },
  ] },
};
// #endregion

// #region heads: the author on the verso, the title on the recto, a drop folio on the opener
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
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }), // each edition's hyphenation patterns
  colorPalette,
  page: { width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
    margins: { top: mm(TOP), bottom: mm(TRIM_H - TOP - LINES * LINE), left: mm(INNER),
      right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText,
  headings: { fontFamily: DISPLAY, color: col('ink'), levels: [{ level: 1,
    breakBefore: { enabled: true, parity: 'odd' }, marginBottom: pt(0),
    advancedDesign: opener }] },
  // The band under a stacked word: painted under ordinary text, so the lines stay as set.
  markStyles: [{ id: 'stack', name: t({ en: 'Stack', es: 'Repetición' }), background: col('mark'),
    color: col('ink'), paddingX: em(0.1), paddingTop: em(0.02), paddingBottom: em(0.08) }],
  calloutStyles: [{ id: 'proof', title: t({ en: 'Proof', es: 'Prueba' }),
    background: col('tint'), stripe: { enabled: true, side: 'top', width: pt(2.5),
      color: col('accent') },
    padding: { top: mm(2.5), right: mm(3.5), bottom: mm(2.5), left: mm(3.5) },
    titleStyle: { fontFamily: LABEL, fontSize: pt(8), fontWeight: 600, letterSpacing: pt(1.2),
      color: col('accent') },
    body: { fontFamily: TEXT, fontSize: pt(8.2), lineHeight: pt(11.2), color: col('ink'),
      textAlign: 'left', firstLineIndent: pt(0), boldColor: col('ink'),
      italicColor: col('ink') } }],
  paragraphStyles: [{ id: 'colophon', fontFamily: TEXT, fontSize: pt(7.2), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
  header, footer,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// #region art: the opener's painting, one per edition: a JPEG in assets/, no lettering
const ART = t({ en: 'carol', es: 'cordera' }); // the heading's art="…" attribute
const resources = [{ id: ART, typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${ART}-1100.jpg`, format: 'jpeg', width: 1100, height: 733 },
  altText: t({
    en: 'A Victorian counting-house on a foggy evening: through the open door an old man in '
      + 'black counts coins at a high desk by a small fire, and a clerk writes by one candle.',
    es: 'Un prado en cuesta de Asturias: una vaca rubia echada en la hierba, dos niños '
      + 'abrazados a un poste del telégrafo y, abajo, un tren que sale de la trinchera.' }) }];
const ARTS = { carol: asset('carol-1100.jpg'), cordera: asset('cordera-1100.jpg') };
await loadImage(`${ART}-1100.jpg`, ARTS[ART]);
// #endregion
const markdown = String.raw`---
title: "A Christmas Carol"
author: "Charles Dickens"
---

# Marley’s Ghost {kicker="Stave One" art="carol"}

Marley was dead: to begin with. There is no doubt whatever about that. The register of his burial was signed by the clergyman, the clerk, the undertaker, and the chief mourner. Scrooge signed it: and Scrooge’s name was good upon ‘Change, for anything he chose to put his hand to. Old Marley was as dead as a door-nail.

Mind! I don’t mean to say that I know, of my own knowledge, what there is particularly dead about a door-nail. I might have been inclined, myself, to regard a coffin-nail as the deadest piece of ironmongery in the trade. But the wisdom of our ancestors is in the simile; and my unhallowed hands shall not disturb it, or the Country’s done for. You will therefore permit me to repeat, emphatically, that Marley was as dead as a door-nail.

Scrooge knew he was dead? Of course he did. How could it be otherwise? Scrooge and he were partners for I don’t know how many years. Scrooge was his sole executor, his sole administrator, his sole assign, his sole residuary legatee, his sole friend, and sole mourner. And even Scrooge was not so dreadfully cut up by the sad event, but that he was an excellent man of business on the very day of the funeral, and solemnised it with an undoubted bargain.

The mention of Marley’s funeral brings me back to the point I started from. There is no doubt that Marley was dead. This must be distinctly understood, or nothing wonderful can come of the story I am going to relate. If we were not perfectly convinced that Hamlet’s Father died before the play began, there would be nothing more remarkable in his taking a stroll at night, in an easterly wind, upon his own ramparts, than there would be in any other middle-aged gentleman rashly turning out after dark in a breezy spot—say Saint Paul’s Churchyard for instance—literally to astonish his son’s weak mind.

Scrooge never painted out Old Marley’s name. There it stood, years afterwards, above the warehouse door: Scrooge and Marley. The firm was known as Scrooge and Marley. Sometimes people new to the business called Scrooge Scrooge, and sometimes Marley, but he answered to both names. It was all the same to him.

Oh! But he was a tight-fisted hand at the grind-stone, Scrooge! a squeezing, wrenching, grasping, scraping, clutching, covetous, old sinner! Hard and sharp as flint, from which no steel had ever struck out generous fire; secret, and self-contained, and solitary as an oyster. The cold within him froze his old features, nipped his pointed nose, shrivelled his cheek, stiffened his gait; made his eyes red, his thin lips blue; and spoke out shrewdly in his grating voice. A frosty rime was on his head, and on his eyebrows, and his wiry chin. He carried his own low temperature always about with him; he iced his office in the dog-days; and didn’t thaw it one degree at Christmas.

External heat and cold had little influence on Scrooge. No warmth could warm, no wintry weather chill him. No wind that blew was bitterer than he, no falling snow was more intent upon its purpose, no pelting rain less open to entreaty. Foul weather didn’t know where to have him. The heaviest rain, and snow, and hail, and sleet, could boast of the advantage over him in only one respect. They often “came down” handsomely, and Scrooge never did.

Nobody ever stopped him in the street to say, with gladsome looks, “My dear Scrooge, how are you? When will you come to see me?” No beggars implored him to bestow a trifle, no children asked him what it was o’clock, no man or woman ever once in all his life inquired the way to such and such a place, of Scrooge. Even the blind men’s dogs appeared to know him; and when they saw him coming on, would tug their owners into doorways and up courts; and then would wag their tails as though they said, “No eye at all is better than an evil eye, dark master!”

But what did Scrooge care! It was the very thing he liked. To edge his way along the crowded paths of life, warning all human sympathy to keep its distance, was what the knowing ones call “nuts” to Scrooge.

:::paragraphs{style="colophon"}
Charles Dickens, *A Christmas Carol*, London, 1843: the opening of Stave One, from Project Gutenberg eBook #46 (public domain) · Set in Spectral, Spectral SC and Cormorant Garamond (SIL Open Font License) · Painting made for this page with a diffusion model.
:::
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { Spectral: ['400', '400i', '600'], 'Spectral SC': ['500', '600'],
  'Cormorant Garamond': ['500i'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region marks: each stack the build reported, marked on both of its lines
// 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);
}
// #endregion

// #region proofs: the same text twice, 'warn' then 'avoid', each with its stacks marked
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') };
// #endregion

const TITLE = t({ en: 'Prose without stacks', es: 'Prosa sin repeticiones' });
const show = (key) => showPages(docs[key], { title: `${TITLE} · stacks: '${key}'` });
const button = (key) => Object.assign(document.createElement('button'),
  { type: 'button', textContent: key, onclick: () => show(key) });
document.getElementById('pt-actions').prepend(button('warn'), button('avoid'));
show('warn');

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## 变化

### 只算较长的词

默认是三个字符。设为五个，*his*、*No* 这样的短词不再算重复，算法在它们周围保留更紧的断行。

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

### 用默认代价排全书

默认代价让字距更紧，在避开重复会让某一行更松的地方，每个版本接受两处重复。

```diff
-  stackPenalty: 10000,
+  stackPenalty: 3000,
```

## 常见问题

- **排版警告: 行首行尾重复** (`stack`). 段落中同一栏内相邻的两行以同一个词或相同的最后bodyText.stackMinCharacters个字符（默认3个，含空格）结尾，或以相同方式开头。不区分重音和大小写；只有用空格分词的文字才有重复。bodyText.stacks设为'warn'时报告每一处；设为'avoid'时，只报告断行保留下来的那些：在词距范围内没有代价低于bodyText.stackPenalty的排法能避开它们。引擎把每一处记入doc.contentWarnings，附上重复的文字、所在边（行尾或行首）、两行文字和页码。 解决办法: 把bodyText.stacks设为'avoid'：断行会在词距允许的范围内重排段落。仍然保留的重复，避开它的代价高于bodyText.stackPenalty：调高惩罚值以换取更松的行，或改写两行中的一行。移植现有书籍时保持'warn'：移植要重现原书的断行。 ([文档](https://postext.dev/zh/docs/configuration-text.md#正文))

- 重复是在断好的行里查找的。改了开本、字号或文字，初校找到的重复就不同了；请读每次排版的警告，不要照抄上一次的位置。
- 重复只在同一段落内计算，而且只针对用空格分词的文字：两段都以 *Scrooge* 开头不算重复，中文和日文文本从不报这种警告。

## 致谢

- 食谱: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 文字: A Christmas Carol (1843), the opening of Stave One, from Project Gutenberg eBook #46, with typographic quotes and dashes: Charles Dickens ([来源](https://www.gutenberg.org/ebooks/46)), 公有领域
- 文字: ¡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 ([来源](https://es.wikisource.org/wiki/%C2%A1Adi%C3%B3s,_Cordera!)), 公有领域
- 图片: Painting: Scrooge's counting-house on a foggy Christmas Eve: Generated With Diffusion Models, 原创
- 图片: Painting: Rosa, Pinín and the Cordera by the telegraph pole: Generated With Diffusion Models, 原创
- 字体: Spectral (OFL-1.1), Spectral SC (OFL-1.1), Cormorant Garamond (OFL-1.1)
- 代码: MIT · 示例内容: CC-BY-4.0

## 相关食谱

- [No. 104 · 按IEC规则断词的加泰罗尼亚语中篇小说](https://postext.dev/zh/cookbook/catalan-pocket-novella.md): 把Narcís Oller的《El transplantat》全文排成32页口袋本：按IEC规则划分加泰罗尼亚语音节，l·l断为il- | lusió，每章一幅版画。 · 难度 2 (中级) · 小说、戏剧与文学散文
- [No. 016 · 口袋本小说里两端对齐的西班牙语](https://postext.dev/zh/cookbook/spanish-pocket-novel.md): 把《Marianela》第一章开头排成口袋本：西班牙语断词，词间距小于1.7倍，没有孤字，抬高的首字，地图作为Figura 1。 · 难度 2 (中级) · 小说、戏剧与文学散文
- [No. 180 · 学习读本里按颜色分类的高亮](https://postext.dev/zh/cookbook/colour-coded-study-highlights.md): 一本历史读本，关键词用三种颜色高亮：术语绿色、日期琥珀色、人名地名蓝色，三种样式都在 markStyles 里定义并链接到调色板。 · 难度 2 (中级) · 教科书
