かんたんな説明
文字組みを扱う小さな雑誌を、文章の両端をそろえた狭い段で組んだ例です。語と語の間を均一に保つ方法を、不ぞろいな行を黄色で示した版と並べて見せます。
できあがり
文字組みの研究所が出す専門誌『Galley』の第12号です。A5判に1行約40字の2段組みで組み、両端そろえの行が余りを吸収するための語間は5つか6つしかありません。章扉はグラファイト色の帯にKnuth–Plassのモデルを描きます。語の箱が1列に並び、グルーの黄色いばねが伸びて行長を埋める図です。論考は狭い段がなぜゆるくなるかを説明し、各規則を支える設定を段落の間に等幅書体で印刷します。3ページ目の地では、比較テストが1つの段落を左そろえ、ハイフンなしの両端そろえ、ハイフンありの両端そろえで組みます。CodePenのサンプルは同じ号をファーストフィットの改行で、ウィドウとオーファンの保護を切って組んだ版も作り、このレシピのカードと同じように、2つの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)ウィドウ、オーファン、ラント警告と診断ハイフネーションと文書の言語字下げ、行そろえ、段落間隔囲みの中や本文中の段組み入れ子の囲み囲みデザインした章扉ページデザインの画像見出しの属性段落スタイルキャンバス上のページリソースとしての図と表セマンティックカラーパレット柱とノンブルページの役割ごとの柱
- 併用する機能
- 段抜きの章見出し帯
- 種類
- Petrona, Bricolage Grotesque, Source Code Pro (SIL OFL 1.1)
- 素材
- なし:画像はすべてコードで描画
作り方
#1 · 語間の柵を狭め、保護は残す
この手順のコードは上の手短な答えにあります。Knuth–Plass、ハイフネーション、ウィドウ・オーファン・ラントのペナルティ、次の段落と離さない見出しは初期設定で有効なので、公開版は語間の上下限を通常の語間の0.8倍と1.6倍に狭めるだけです(初期値は0.6と2)。上限を超える行はどのハイフンやラントよりも高くつくので、改行処理はまずほかの改行位置を試します。2つの上下限を消すと、この論考では1.6を超える行が2行できます。ハイフネーションは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の印を付けるからです。2つの段に分かれた段落は断片ごとに1ブロックとして返ってくるので、孤立した行はそこから見つけます。1行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つの版は同じデザインを共有するので、2つの2ページ目の違いはすべて改行処理とその保護から来ます。英語版では、貪欲法の対照版は両端そろえの110行のうち47行が1.6を、30行が2を超え、うち3行は3倍を超えてエンジンが左そろえで組みます。一方、Knuth–Plass版は105行すべてを0.80から1.60の間に収めます。2ページ目では、対照版は段落の最終行を1行だけ段の頭へ送ってもいます。これは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グループのすべての段を1つの本文スタイルで組むので、各試し刷りはそれぞれbodyを含む入れ子の囲みにし、breaks="3"で左そろえとハイフンなしの試し刷りを1段目に積みます。左そろえのテキストはbodyText.hyphenation.raggedを有効にしないかぎりハイフネーションされないので、左そろえの試し刷りにhyphenation: falseは要りません。比較テストはplacement: 'bottom'で3ページ目の地にフロートします。最後の試し刷りのmarginBottomは囲みの終わりで捨てられるので、下の内側余白で4 mmの枠を繰り返しています。
#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があるため、さらに1行下からです。ラベルは図の座標の上に置いたデザインのテキストで、章扉のほかのラベルと同じ書体と字間で組みます。
レシピの全体
// ═══ 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: each edition's patterns
+const locale = 'de'; // German patterns; 'de-AT' picks them too#最もゆるい行にだけ印を付ける
しきい値を1.6から2に上げると、蛍光ペンは語間が2倍を超えた行にだけ印を付けます。
- const loose = findLooseLines(doc, { threshold: FENCES.maxWordSpacing, pageIndex: page.index });
+ const loose = findLooseLines(doc, { threshold: 2, pageIndex: page.index });よくあるつまずき
つまずき
avoidWidowsは段の末尾を、avoidOrphansは段の頭を守る
Postextは2種類の孤立行に独自の名前を付けています。avoidWidows(widowMinLines、widowPenalty)は段落の1行目が段の末尾に1行だけ残るのを防ぎ、avoidOrphans(orphanMinLines、orphanPenalty)は段落の最終行が次の段の頭に1行だけ残るのを防ぎます。多くの組版の手引きはこの2つの名前を逆に使っているので、設定は効く位置で選んでください。どちらも既定で有効ですが、文字グリッド(cjk.grid)上では違います。グリッド上ではavoidWidowsが既定でオフになり、日本の地域設定ではavoidOrphansもオフになります(postext 1.28以降)。ページがグリッドの数える行数を収めるためです。どちらもペナルティとして働きます。レイアウトは、それぞれを、従った場合に生じる空行と比べて判断します。 ウィドウ、オーファン、ラント →
つまずき
'top'のフロートは参照ページの先頭を許さない限り次のページに置かれる
既定では、フロートが自分の参照より上に置かれることはありません。そのため、Nページで参照したページ幅の'top'フロートはN+1ページの頭に置かれます。リソースまたはその種類のdefaultPlacementにplacement.citingPage: trueを設定すると(本全体ならlayout.floatsAtCitingPage、postext 1.25から)、layout.maxTopFraction以内に収まり参照行がそのページに残る場合は代わりにNページの先頭に置かれ、参照より前の本文はその下に送られます。章の最初のページと強制改ページの後のページの先頭には置かれません。その場合は次のページに置かれ、'auto'または'bottom'なら参照したページの下端に入れられます。 図の配置 →
Sandboxの検査 · looseLine
ゆるい行
原因. 両端そろえの行で、語間がしきい値を超えて広がっています。原因はたいてい長い単語、URL、または狭い行長です。
対処. 正しい言語でハイフネーションを有効にする、行長を広げる、文を書き換える、またはその箇所を左そろえ(行末不ぞろい)で組んでください。 ドキュメント →
- 段の終わりに残った囲みは、段末をそろえるときに段の地へ落ち、属する段落から離れます。「Fences for the glue」の下の設定の囲みで必要だったように、原稿を調整して段を埋めてください。
headings.balancing.closingBoxを'off'にすれば、囲みは動かされません。 - ハイフンなしの試し刷りには、本来必要な最も広い語間は現れません。語間が通常の3倍を超えて伸びる両端そろえの行は、本文と同じく囲みの中でも自然な語間のまま左そろえで組まれるため、この試し刷りの最初の2行は行長より手前で終わります。3倍に届かない行は両端そろえのままで、試し刷りに見える広い語間はそれらの行のものです。
クレジット
- 本文
- 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)


