简单来说
一本讲字体排印的小杂志,排成两端对齐的窄栏。示例演示怎样让词间空隙保持均匀,旁边的对照版把松散的行标成黄色。
成品一览
Galley第12期,一家字体实验室的期刊,在A5上排成两栏,每行约40个字符,一行两端对齐的文字只有五六个词间空格来吸收多余的宽度。章首页在一条石墨色色带上画出Knuth–Plass模型:一行单词框,黄色的“胶”弹簧拉伸着填满行长。文章解释窄栏为何容易排松,并在段落之间用等宽字体印出每条规则背后的设置。第3页底部有一个对照测试,把同一段文字排成齐左、不断词的两端对齐和断词的两端对齐。pen还用首次适配断行、关闭段末孤行和段首孤行保护排了一遍这期刊物,并把两个版本的第2页并排显示在页面上方(本食谱的卡片也是这样),过松的行用荧光黄涂出,孤行和孤字在页边标注。
这道食谱解答
- 怎样让西班牙文、法文或德文获得良好的两端对齐和断词?
- 怎样避免段末孤行、段首孤行和只有一个词的末行(孤字),并让标题与正文不分开?
- 为什么有一行排得不齐或被拉得过宽(URL、长复合词、单元格里的长词)?
- 怎样找出文档哪里出了问题(警告、溢出、版面不收敛)?
简短回答
// 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 } });
用料
- 功能
- 最优断行(Knuth–Plass)段末孤行、段首孤行与孤字警告与诊断断词与文档语言缩进、对齐与段落间距框内或正文中的分栏嵌套框标注框设计过的章首页页面设计中的图片标题属性段落样式在Canvas上绘制页面作为资源的图和表语义调色板书眉与页码按页面角色显示书眉
- 还用到
- 通栏章首色带
- 类型
- Petrona, Bricolage Grotesque, Source Code Pro(SIL OFL 1.1)
- 素材
- 无:所有图片都用代码绘制
做法
#1 · 收紧界限,保留保护
这一步的代码就是上面的简短回答。Knuth–Plass、断词、段末孤行、段首孤行和孤字的惩罚值以及标题与下文不分离,默认都已开启,所以正式版只把词间距界限收窄到正常空格的0.8和1.6倍(默认是0.6和2)。超出上限的行比任何连字符或孤字代价都高,所以断行器会先尝试别的断点;删掉这两个界限,这篇文章会有两行超过1.6。断词按locale选择:'es'、'fr'和'de'有各自的TeX模式,'es-ES'这样带地区的标签用其语言的模式,没有模式的语言则按美式英语断词,并在控制台给出警告。
#2 · 从版面树标出过松的行
// 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返回词间距拉伸超过某个阈值(这里是上限)的两端对齐行,每行都带有高亮要覆盖的条带(在你自己的Canvas中标出松散行)。这份清单没有的,marks()从VDT里补上:超过3倍的行没有比值,因为引擎会把它排成齐左,并标记为line.ragged;被两栏拆开的段落,每个片段各返回一个块,孤行就是这样找出来的。在40个字符的行长下,光靠界限并不能让每一行都低于1.6;调整文章篇幅时,这些标记指出了需要改写哪些句子。
#3 · 把对照版放在正式版旁边
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
}
两个版本共用同一个设计,所以两个第2页之间的每一处差别都来自断行器及其保护。英文版中,贪心对照版的110个两端对齐行里有47行超过1.6,30行超过2,其中三行超过3倍,被引擎排成齐左;而Knuth–Plass版把全部105行都控制在0.80到1.60之间。在第2页上,对照版还把一个段落的最后一行单独带到一栏的栏首(avoidOrphans: false允许这样做),另有一个段落以孤字结尾。
#4 · 每种设置各用一个框
// 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) } },
];
一个框用同一种正文样式排:::columns组里的所有栏,所以每张样条都是一个带自己body的嵌套框,breaks="3"把齐左样条和不断词样条叠放在第一栏。齐左样条不需要hyphenation: false:除非打开bodyText.hyphenation.ragged,齐左文字不断词。对照测试用placement: 'bottom'浮动到第3页底部,它的下内边距重复了4 mm的边框,因为最后一张样条的marginBottom在框的末尾会被舍去。
#5 · 把模型画进章首页
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) })),
] },
});
示意图是H1设计中的一个图像元素。如果作为图,它会是一个通栏的top浮动体,而在第1页引用的top浮动体会排到第2页的顶部。色带比示意图伸得更低,而章首页预留的高度一直算到最低的元素,所以不需要minHeight,正文就从色带下方开始;由于H1默认的marginBottom,还要再往下一行。标签是按图本身坐标摆放的设计文字,字体和字距与章首页的其他标签一致。
完整食谱
// ═══ 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,
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#给德语文本断词
断词模式由locale决定,所以德语文本写'de',或者'de-AT'这样带地区的标签。
-const locale = t({ en: 'en-us', es: 'es' }); // config().locale:各版本自己的断词模式
+const locale = 'de'; // 德语断词模式;'de-AT'也用它#只标出最差的行
把阈值从1.6提高到2,荧光笔就只标出空格已超过原来两倍的行。
- const loose = findLooseLines(doc, { threshold: FENCES.maxWordSpacing, pageIndex: page.index });
+ const loose = findLooseLines(doc, { threshold: 2, pageIndex: page.index });常见问题
易错点
avoidWidows管栏底,avoidOrphans管栏顶
Postext对两种孤行的命名自成一套:avoidWidows(widowMinLines、widowPenalty)防止段落的首行单独留在栏底,avoidOrphans(orphanMinLines、orphanPenalty)防止段落的末行单独出现在下一栏的栏顶。很多体例手册的叫法正好相反,所以要按作用的位置选择设置。两者默认开启,字符网格(cjk.grid)除外:网格上avoidWidows默认关闭,日本地区的avoidOrphans也关闭,好让页面排满网格所数的行数(postext 1.28起)。两者都以惩罚值的方式起作用:排版时会把每一项与遵守它所留下的空行放在一起权衡。 段末孤行、段首孤行与孤字 →
易错点
'top'浮动体默认排在引用页的下一页,除非允许它置于引用页顶
默认情况下浮动体不会排在自己的引用之前,所以在第N页引用的整页宽'top'浮动体会出现在第N+1页的顶部。在资源或其类型的defaultPlacement上设置placement.citingPage: true(或者对全书设置layout.floatsAtCitingPage,自postext 1.25起),它就改为置于第N页顶部,引用处之上的文字移到它下方,前提是它不超过layout.maxTopFraction且引用行仍留在该页。它不会置于章首页或强制分页之后的页面顶部:那时仍排在下一页,而'auto'或'bottom'可以占用引用页的底部。 图的放置 →
沙盒检查 · looseLine
松散行
原因. 某个两端对齐的行把空格拉得超过了阈值,通常是长单词、URL或行长太窄造成的。
解决. 按正确的语言开启断词、加大行长、改写句子,或把这段排成齐左。 文档 →
- 留在栏尾的框,在各栏齐底时会掉到栏底,离开它所属的段落。调整文字篇幅让这一栏排满,“Fences for the glue”下面的设置框就需要这样处理。也可以把
headings.balancing.closingBox设为'off',这样框就不会被移动。 - 不断词样条看不到它本来需要的最宽空隙。两端对齐的行若要把空格拉到正常宽度的三倍以上,就按自然间距排成齐左,框内和正文一样,所以这张样条的前两行没有排满行长。没到这个上限的行仍然两端对齐,样条上那些宽空隙就出自这些行。
致谢
- 文本
- 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
- 字体
- Petrona (SIL OFL 1.1) · Bricolage Grotesque (SIL OFL 1.1) · Source Code Pro (SIL OFL 1.1)


