Pular para o conteúdo principal
Receita número 184

Receitas · Capítulo 2 · Tipo e texto

Prosa justificada sem repetições nas bordas da linha

Uma página de Dickens composta duas vezes numa medida estreita: a primeira prova aponta e marca cada repetição, a segunda a pesa na quebra de linhas.

Nesta página
Saída
Canvas
Postext
Testada com o Postext 1.73.0
Requer ≥ 1.73.0
Licença
Atualizada em 10 de nov. de 2026
Código MIT · Texto CC BY 4.0
  • Amostra em inglês: ainda sem edição em português
  • Refile 115 × 180 mm
  • 1 coluna
  • Spectral 9,6/13,4
  • Cormorant Garamond
  • Spectral SC
  • 8 páginas
  • Nível
  • Postext 1.73.0
  • Diagramado em 36 ms
  • 180 linhas de código

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

script.js · linhas 41–58no código completo
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

Tipografia
Spectral, Spectral SC, Cormorant Garamond (SIL OFL 1.1)
Materiais
  • carol-1100.jpg
  • cordera-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

script.js · linhas 41–58no código completo
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

script.js · linhas 173–201no código completo
// 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.

Primeira prova, página 2: sole sobre sole no fim da linha, depois even sobre event e The sobre the no início.

#3 · Duas provas de um mesmo texto

script.js · linhas 205–224no código completo
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].

Segunda prova, página 2: os mesmos parágrafos quebrados de outro jeito. Só resta even sobre event.

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

script.js · linhas 62–77no código completo
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é

script.js · linhas 81–93no código completo
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

Sandbox
// ═══ 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

Texto
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)
Sandbox