简单来说
相邻两行以同一个词结尾或开头时,读者的目光容易跳错行。这本书排了两遍:一遍标出哪里出现重复,一遍改变断行让重复消失。
成品一览
两份 115 × 180 mm 口袋本的校样,排的是《圣诞颂歌》(A Christmas Carol)的开头,Spectral 字体,83 mm 栏宽,两端对齐。栏窄,断行算法可选的余地就少,有五处相邻两行以同一个词结尾或开头:sole 叠 sole,his 叠 his,No 叠 No。初校用 stacks: 'warn' 排:断行一处不改,只报出每处重复,在两个词下面加浅红色底纹,并在版权说明后的校样条上逐条列出。二校用 'avoid' 排,五处去掉了四处。西班牙语版用同样方法排 Clarín 的 ¡Adiós, Cordera! 开头。
这道食谱解答
- 怎样避免相邻两行以同一个词结尾或开头?
简短回答
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
};
用料
- 类型
- Spectral, Spectral SC, Cormorant Garamond(SIL OFL 1.1)
- 素材
carol-1100.jpgcordera-1100.jpg- 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, 原创)
做法
#1 · 先报出,再计入代价
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 · 在文字上标出重复
// 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[…] 包住整个词。标记只在普通文字下面画底纹,不改动断行。只标整词:如果只标半个词,这个词的连字符断法会变,行就不再断在发现警告的位置。

#3 · 同一文本的两份校样
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]。

英文版留下的一处是 even 叠 event:两个词前三个字母相同,而这一段的其他断法代价都更高。西班牙语版按两个字符计算,初校找到五处,其中有 con 叠 como 的 co、levantar 叠 vacilar 的 ar,二校一处也没有。
#4 · 正文上方的章首
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 · 书眉与页脚页码
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
左页印作者,右页印书名,各自挨着页码。章首页不印书眉,页码移到页脚。
完整食谱
// ═══ 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
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
常见问题
版面警告 · stack
行首行尾重复
原因. 段落中同一栏内相邻的两行以同一个词或相同的最后bodyText.stackMinCharacters个字符(默认3个,含空格)结尾,或以相同方式开头。不区分重音和大小写;只有用空格分词的文字才有重复。bodyText.stacks设为'warn'时报告每一处;设为'avoid'时,只报告断行保留下来的那些:在词距范围内没有代价低于bodyText.stackPenalty的排法能避开它们。引擎把每一处记入doc.contentWarnings,附上重复的文字、所在边(行尾或行首)、两行文字和页码。
解决. 把bodyText.stacks设为'avoid':断行会在词距允许的范围内重排段落。仍然保留的重复,避开它的代价高于bodyText.stackPenalty:调高惩罚值以换取更松的行,或改写两行中的一行。移植现有书籍时保持'warn':移植要重现原书的断行。 文档 →
- 重复是在断好的行里查找的。改了开本、字号或文字,初校找到的重复就不同了;请读每次排版的警告,不要照抄上一次的位置。
- 重复只在同一段落内计算,而且只针对用空格分词的文字:两段都以 Scrooge 开头不算重复,中文和日文文本从不报这种警告。
致谢
- 文本
- A Christmas Carol (1843), the opening of Stave One, from Project Gutenberg eBook #46, with typographic quotes and dashes · Charles Dickens · 公有领域
- ¡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 · 公有领域
- 图片
- 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 (SIL OFL 1.1) · Spectral SC (SIL OFL 1.1) · Cormorant Garamond (SIL OFL 1.1)


