Em poucas palavras
Quando duas linhas seguidas terminam ou começam com a mesma palavra, o olho pode pular para a linha errada. O livro é composto duas vezes: uma mostra onde isso acontece, a outra quebra as linhas para que não aconteça.
O que você vai compor
Duas provas de uma página de bolso de 115 × 180 mm com o início de A Christmas Carol, justificado em Spectral numa medida de 83 mm. Uma medida estreita deixa poucas saídas para o algoritmo de quebra, e em cinco lugares duas linhas seguidas terminam ou começam com a mesma palavra: sole sobre sole, his sobre his, No sobre No. A primeira prova é composta com stacks: 'warn'. Ela não muda nenhuma quebra, aponta cada repetição, marca as duas palavras com uma faixa vermelho-clara e as lista numa tira depois do colofão. A segunda é composta com 'avoid', e quatro das cinco desaparecem. A edição espanhola compõe do mesmo jeito o início de ¡Adiós, Cordera!, de Clarín.
Esta receita responde a
- Como evito que duas linhas seguidas terminem ou comecem com a mesma palavra?
A resposta curta
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
};
Ingredientes
- Funcionalidades
- Repetições no início e no fim da linhaQuebra de linha ótima (Knuth–Plass)Hifenização e idioma do documentoViúvas, órfãs e linhas curtasTipografia do textoAberturas desenhadasImagens nos designs de páginaAtributos de títuloCabeços e fóliosCabeços por tipo de páginaMargens espelhadasBoxesEstilos de parágrafoPaleta de cores semântica
- Também usa
- DestaquesFiguras e tabelas como recursos
- Tipografia
- Spectral, Spectral SC, Cormorant Garamond (SIL OFL 1.1)
- Materiais
carol-1100.jpgcordera-1100.jpg- Painting: Scrooge's counting-house on a foggy Christmas Eve (Generated With Diffusion Models, original)
- Painting: Rosa, Pinín and the Cordera by the telegraph pole (Generated With Diffusion Models, original)
Preparo
#1 · Primeiro apontar, depois pesar
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
};
Há repetição quando duas linhas seguidas terminam com a mesma palavra ou com os mesmos últimos caracteres, ou começam igual. stackMinCharacters define quantos caracteres são necessários: três por padrão, contando os espaços, sem contar acentos nem maiúsculas, de modo que The sobre the conta. 'warn' só aponta, e assim quem compõe vê onde um texto se repete. 'avoid' soma stackPenalty aos deméritos de cada quebra que criaria uma repetição, e o algoritmo de Knuth–Plass procura outra forma de quebrar o parágrafo. Ele precisa de optimalLineBreaking: a quebra linha a linha não tem deméritos aos quais somar nada.
Os manuais de composição em espanhol contam a repetição entre os vícios de composição, ao lado dos rios e das escadas de hifens. Ao voltar à margem esquerda, o olho pode se prender à palavra repetida na linha errada e ler uma linha duas vezes ou pular outra; na margem direita, a repetição soa como eco. A regra espanhola alcança também a sílaba repetida, não só a palavra, e por isso a edição espanhola fixa stackMinCharacters em 2.
A penalidade padrão, 3000, é o que custam dois hifens seguidos, e uma palavra repetida de uma só sílaba custa o dobro. Nesta medida, 3000 deixava duas repetições em cada edição, porque a alternativa era uma linha mais aberta do que o algoritmo aceita. Com 10000 ele aceita essas linhas. maxWordSpacing fica no valor padrão, 2: com um limite mais apertado o algoritmo não tinha outra quebra para escolher e 'avoid' não mudava nada.
#2 · Marcar as repetições no texto
// 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);
}
Cada aviso dá a posição da sua primeira linha no texto-fonte, então o script encontra essa linha e a seguinte no documento composto, pega a borda repetida de cada uma e envolve a palavra inteira em :mark[…]. Uma marca pinta uma faixa sob o texto comum e não mexe nas quebras. Só se marcam palavras inteiras: uma marca em parte de uma palavra muda a forma como essa palavra se divide, e aí as linhas já não quebram onde o aviso foi encontrado.

#3 · Duas provas de um mesmo texto
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') };
Cada prova é composta duas vezes. A primeira composição encontra as repetições. A segunda compõe o mesmo texto com as marcas e uma tira acrescentada depois do colofão, que cai assim na última página. O pen deixa de fora das páginas publicadas a primeira composição de cada prova, o texto sem marcas: capture.doc lista as duas composições marcadas, [1, 3].

A repetição que fica na edição inglesa é even sobre event: as duas palavras compartilham as três primeiras letras, e qualquer outra quebra daquele parágrafo custava mais. Em espanhol, com dois caracteres, a primeira prova encontra cinco repetições, entre elas co de con sobre como e ar de levantar sobre vacilar, e a segunda nenhuma.
#4 · A abertura sobre o texto
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' }) },
] },
};
O atributo art do título nomeia a pintura, então um só estilo serve às duas edições. minHeight reserva dezesseis linhas e o texto começa na décima sétima, na mesma grade das páginas seguintes.
#5 · Cabeços e fólio no pé
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
O autor vai no verso e o título no recto, cada um ao lado do seu fólio. Na abertura os cabeços somem e o fólio desce para o pé.
A receita completa
// ═══ 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
O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)
Variações
#Contar só palavras longas
Três caracteres é o padrão. Com cinco, palavras curtas como his e No deixam de contar como repetição, e o algoritmo mantém em volta delas as quebras mais apertadas.
- stackMinCharacters: t({ en: 3, es: 2 }),
+ stackMinCharacters: 5,#Compor o livro com a penalidade padrão
O padrão mantém o espaçamento mais apertado e aceita duas repetições por edição onde evitá-las abriria mais uma linha.
- stackPenalty: 10000,
+ stackPenalty: 3000,Erros comuns
Aviso de diagramação · stack
Repetição
Por quê. Duas linhas seguidas de um parágrafo, na mesma coluna, terminam com a mesma palavra ou os mesmos últimos bodyText.stackMinCharacters caracteres (3 por padrão, espaços incluídos), ou começam igual: «…de um» sobre «…com um». Acentos e maiúsculas não contam, e só há repetições nas escritas que separam as palavras com espaços. Com bodyText.stacks em 'warn' todas são assinaladas; em 'avoid', as que a quebra de linha manteve porque nenhuma composição dentro do espaçamento entre palavras as evitava por menos que bodyText.stackPenalty. O motor regista cada uma em doc.contentWarnings com o texto repetido, a borda (fim ou início), as duas linhas e a página.
Correção. Ponha bodyText.stacks em 'avoid': a quebra de linha compõe o parágrafo de outro modo onde o espaçamento entre palavras permite. Uma repetição que fica custa mais a evitar que bodyText.stackPenalty: aumente a penalização para a trocar por linhas mais soltas, ou reescreva uma das duas linhas. Num port de um livro existente mantenha 'warn': o port reproduz as quebras do original. Docs →
- As repetições são procuradas nas linhas já quebradas. Se você mudar o formato, o corpo ou o texto, a primeira prova encontra outras: leia os avisos de cada composição e não copie posições de uma anterior.
- As repetições são contadas dentro de um parágrafo e só em escritas que separam as palavras com espaços: dois parágrafos que começam com Scrooge não fazem repetição, e um texto em chinês ou japonês nunca aponta nenhuma.
Créditos
- Receita
- Ignacio Ferro
- Texto
- A Christmas Carol (1843), the opening of Stave One, from Project Gutenberg eBook #46, with typographic quotes and dashes · Charles Dickens · domínio público
- ¡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 · domínio público
- Imagens
- Painting: Scrooge's counting-house on a foggy Christmas Eve · Generated With Diffusion Models · original
- Painting: Rosa, Pinín and the Cordera by the telegraph pole · Generated With Diffusion Models · original
- Fontes
- Spectral (SIL OFL 1.1) · Spectral SC (SIL OFL 1.1) · Cormorant Garamond (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


