Em poucas palavras
Dois capítulos de um livro de fisiologia com um índice no final. As palavras são marcadas no texto e o livro encontra sozinho os números de página, sem digitar nenhum à mão.
O que você vai compor
A parte IV de Principles of Human Physiology, um livro didático numa página de 210 × 277 mm: o capítulo 14, The heart as a pump, e o capítulo 15, Vessels and blood pressure, abrem em páginas ímpares sob uma faixa vermelha e compõem as notas clínicas e as legendas num canal externo. A parte termina com um índice de umas noventa entradas e trinta subentradas em duas colunas, do jeito que um livro de medicina o compõe: entradas em minúscula, letras de grupo na cor de destaque, subentradas recuadas um eme, a página que define o termo em negrito, see e see also em itálico. Nenhum número de página ali foi digitado. Cada termo é marcado no capítulo, onde o texto o explica, e o índice lê as páginas em que essas marcas caíram, os fólios 297 a 304.
Esta receita responde a
- Como faço um índice remissivo cujos números de página mudem sozinhos quando o texto se move?
A resposta curta
// The chapters mark each term where the text discusses it:
// the :index[stroke volume]{main} prints the words, files them, bold page
// mitral:index{term="heart!valves!mitral"} prints nothing, files the word before it
// ## Venous return :index{term="venous return" range="start" main} … range="end"
// :index{term="inotropy" see="contractility"} a cross-reference, no page
// The last chapter is `# Index {style="index"}` and `:::index`. buildBundle hands it every
// chapter's marks with the pages they landed on, and lays the book out again until those
// pages stop moving.
const indexStyle = {
id: 'index', numbered: false, toc: false, // not counted: no chapter 16
layout: { layoutType: 'double', gutterWidth: mm(6) }, // two columns in this section only
advancedDesign: opener(INDEX_BAND), // the chapters' band, shallower and with no number
header: runningHeads(t({ en: 'Index', es: 'Índice analítico' })),
};
const index = {
fontFamily: SERIF, fontSize: pt(8.6), lineHeight: pt(11.4),
indent: em(1), turnoverIndent: em(2), // sub-entries step in 1 em; wrapped lines hang 2 em
// English: Chicago's short ranges (301–3; 298–300 keeps the digit that changes). Spanish
// writes both numbers in full and joins them with a hyphen (301-303).
rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
main: { bold: true }, // the defining page in bold
see: { italic: true }, // See / See also, Véase / Véase también by the document's locale
groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
};
Ingredientes
- Funcionalidades
- Índice remissivoLivros compostos capítulo a capítuloEstilos de títuloAberturas desenhadasAtributos de títuloTítulos numeradosCabeços e fóliosCabeços por tipo de páginaMargens espelhadasColuna de margem para flutuantesNotas na margemLegendas lateraisCapítulos sem númeroBoxes flutuantesBoxesLegendas numeradasExportação para PDF
- Também usa
- Coluna e meiaCitações que posicionam as figurasFigura e Tabela no seu idiomaFaixa de capítulo em largura totalEstilos de parágrafoFontes incorporadas ao PDFTipos de recurso personalizadosFiguras e tabelas como recursosElementos pré-textuais em romanosGeometria por seçãoCabeços por seçãoSobrescritos e subscritos
- Tipografia
- Literata, Libre Franklin (SIL OFL 1.1)
- Materiais
- Nenhum: todas as imagens são desenhadas em código
Preparo
#1 · Marque a passagem, não a palavra
// The chapters mark each term where the text discusses it:
// the :index[stroke volume]{main} prints the words, files them, bold page
// mitral:index{term="heart!valves!mitral"} prints nothing, files the word before it
// ## Venous return :index{term="venous return" range="start" main} … range="end"
// :index{term="inotropy" see="contractility"} a cross-reference, no page
// The last chapter is `# Index {style="index"}` and `:::index`. buildBundle hands it every
// chapter's marks with the pages they landed on, and lays the book out again until those
// pages stop moving.
const indexStyle = {
id: 'index', numbered: false, toc: false, // not counted: no chapter 16
layout: { layoutType: 'double', gutterWidth: mm(6) }, // two columns in this section only
advancedDesign: opener(INDEX_BAND), // the chapters' band, shallower and with no number
header: runningHeads(t({ en: 'Index', es: 'Índice analítico' })),
};
const index = {
fontFamily: SERIF, fontSize: pt(8.6), lineHeight: pt(11.4),
indent: em(1), turnoverIndent: em(2), // sub-entries step in 1 em; wrapped lines hang 2 em
// English: Chicago's short ranges (301–3; 298–300 keeps the digit that changes). Spanish
// writes both numbers in full and joins them with a hyphen (301-303).
rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
main: { bold: true }, // the defining page in bold
see: { italic: true }, // See / See also, Véase / Véase también by the document's locale
groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
};
Quem faz um índice marca os lugares onde um termo é explicado, não cada lugar em que a palavra aparece. Os dois capítulos usam stroke volume doze vezes, e o índice manda o leitor a dois lugares: a página 298, onde o termo é definido, e 299–300, onde o texto explica o que o regula. Uma marca visível, :index[cardiac output]{main}, imprime as palavras e as registra. Uma invisível, mitral:index{term="heart!valves!mitral"}, não imprime nada e pega a página da palavra anterior; é assim que a passagem sobre as quatro valvas registra mitral, tricuspid, aortic e pulmonary sob heart sem mudar a frase. O ! separa os níveis, de modo que heart ganha três: valvas e depois cada valva. Uma marca também funciona num título (os intervalos de 14.1 e 15.6 começam ali) e num boxe (heart failure é definido na nota lateral da página 300).
#2 · Páginas principais, intervalos e remissivas
// The chapters mark each term where the text discusses it:
// the :index[stroke volume]{main} prints the words, files them, bold page
// mitral:index{term="heart!valves!mitral"} prints nothing, files the word before it
// ## Venous return :index{term="venous return" range="start" main} … range="end"
// :index{term="inotropy" see="contractility"} a cross-reference, no page
// The last chapter is `# Index {style="index"}` and `:::index`. buildBundle hands it every
// chapter's marks with the pages they landed on, and lays the book out again until those
// pages stop moving.
const indexStyle = {
id: 'index', numbered: false, toc: false, // not counted: no chapter 16
layout: { layoutType: 'double', gutterWidth: mm(6) }, // two columns in this section only
advancedDesign: opener(INDEX_BAND), // the chapters' band, shallower and with no number
header: runningHeads(t({ en: 'Index', es: 'Índice analítico' })),
};
const index = {
fontFamily: SERIF, fontSize: pt(8.6), lineHeight: pt(11.4),
indent: em(1), turnoverIndent: em(2), // sub-entries step in 1 em; wrapped lines hang 2 em
// English: Chicago's short ranges (301–3; 298–300 keeps the digit that changes). Spanish
// writes both numbers in full and joins them with a hyphen (301-303).
rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
main: { bold: true }, // the defining page in bold
see: { italic: true }, // See / See also, Véase / Véase también by the document's locale
groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
};
main põe em negrito a página que define um termo, por isso um estudante que procura preload vai primeiro à página 299. range="start" e range="end", com o mesmo termo, delimitam uma discussão que atravessa uma quebra de página: stroke volume, regulation, 299–300, baroreceptor reflex, 303–4. Um main no início põe o intervalo inteiro em negrito. Uma página marcada de novo dentro do próprio intervalo se funde com ele, e um main ali põe o intervalo em negrito. see substitui os números de página (inotropy. See contractility), e seealso vem depois deles (heart failure, 300. See also ejection fraction). Um destino com níveis é escrito com ! e impresso com dois-pontos: See blood pressure: mean arterial.
#3 · Um capítulo de índice em duas colunas
// The chapters mark each term where the text discusses it:
// the :index[stroke volume]{main} prints the words, files them, bold page
// mitral:index{term="heart!valves!mitral"} prints nothing, files the word before it
// ## Venous return :index{term="venous return" range="start" main} … range="end"
// :index{term="inotropy" see="contractility"} a cross-reference, no page
// The last chapter is `# Index {style="index"}` and `:::index`. buildBundle hands it every
// chapter's marks with the pages they landed on, and lays the book out again until those
// pages stop moving.
const indexStyle = {
id: 'index', numbered: false, toc: false, // not counted: no chapter 16
layout: { layoutType: 'double', gutterWidth: mm(6) }, // two columns in this section only
advancedDesign: opener(INDEX_BAND), // the chapters' band, shallower and with no number
header: runningHeads(t({ en: 'Index', es: 'Índice analítico' })),
};
const index = {
fontFamily: SERIF, fontSize: pt(8.6), lineHeight: pt(11.4),
indent: em(1), turnoverIndent: em(2), // sub-entries step in 1 em; wrapped lines hang 2 em
// English: Chicago's short ranges (301–3; 298–300 keeps the digit that changes). Spanish
// writes both numbers in full and joins them with a hyphen (301-303).
rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
main: { bold: true }, // the defining page in bold
see: { italic: true }, // See / See also, Véase / Véase también by the document's locale
groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
};
O índice é o último documento Markdown do livro, # Index {style="index"} seguido de :::index. O estilo de título troca a coluna e meia dos capítulos por duas colunas separadas por 6 mm, só na própria seção, e dá ao índice uma abertura e um cabeço próprios. O índice é composto na letra do texto em 8,6/11,4 pt, um eme por subnível, e uma linha que quebra fica recuada dois emes, por isso uma linha continuada nunca se alinha com uma subentrada. rangeFormat: 'chicago' corta os algarismos que um intervalo repete (303–4, mas 299–300). A edição em espanhol escreve os intervalos completos com hífen (303-304), a prática habitual nos livros em espanhol.
#4 · Por que os números acompanham o texto
const text = chapters.map((chapter) => chapter.markdown).join('\n');
await loadSvg('pv-loop.svg', pvLoop());
await prepareFonts(text, config, kitFonts(FONTS));
const docs = await withLoadedFonts(() => buildBundle({ chapters, config, resources }),
{ ...kitFonts(FONTS), text });
showPages(docs, { title: t({ en: 'Principles of Human Physiology',
es: 'Principios de fisiología humana' }) });
offerPdf(() => renderToPdf(docs, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
`${RECIPE}.pdf`);
buildBundle diagrama os capítulos em ordem e descobre que o terceiro contém :::index. Depois da primeira passada, ele reúne todas as marcas de todos os capítulos com a página em que cada uma caiu e entrega essa lista ao capítulo do índice como estrutura. Em seguida diagrama o livro de novo, até três passadas, até que nenhum número de página se mova. Reescreva um parágrafo do capítulo 14, mude o formato ou o corpo, e o índice é reimpresso com as páginas novas. No PDF, cada número de página é um link para a página.
#5 · Aberturas e cabeços
function opener(band = BAND, kicker = '') {
const onBand = { color: col('paper'), align: 'left', overflow: 'wrap' }; // wrap: never '…'
const inBand = band - MARGIN.top - 8; // the title's box: it stands on a line 8 mm above the foot
return { enabled: true, minHeight: mm(inBand + 8 + 31), slot: { elements: [
{ kind: 'box', id: 'band', style: { backgroundColor: col('accent') },
placement: { ...at('bleed', 'top-left', 0, 0), size: { height: mm(band) } } },
{ kind: 'text', id: 'kicker', content: kicker, ...label, ...onBand, fontSize: pt(8.5),
placement: at('container', 'top-left', 0, -6) },
{ kind: 'text', id: 'title', content: '{titleText}', ...onBand, fontFamily: SANS,
fontWeight: 800, fontSize: pt(30), lineHeight: 1.05, // a multiple, never pt()
verticalAlign: 'bottom', // one line or two, the title sits on the same line
placement: { ...at('container', 'top-left', 0, 0),
size: { width: mm(170), height: mm(inBand) } } },
{ kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: SERIF, italic: true,
fontSize: pt(10.5), lineHeight: 1.4, color: col('ink'), align: 'left', overflow: 'wrap',
inlineMarks: true, // *See* in the index's lead
placement: { ...at('container', 'top-left', 0, inBand + 15),
size: { width: mm(118) } } },
] } };
}
Os capítulos e o índice compartilham uma abertura: uma faixa do refile até 62 mm (46 mm no índice), com o título apoiado no pé dela por uma caixa alinhada embaixo, de modo que um título de duas linhas e um de uma linha terminam na mesma linha. O antetítulo imprime {chapterNumber}, que o atributo de título {startAt=14} define como 14, e page.pageNumbering.startAt: 297 coloca a parte onde ela ficaria no livro. O estilo do índice tem numbered: false, de modo que ele não vira o capítulo 16.
A receita completa
// ═══ Postext Cookbook · Nº 072 · A textbook index that follows the text ═══════════════
// https://postext.dev/en/cookbook/back-of-book-index
// Code: MIT · Text: original (CC BY 4.0) · Drawing: generated in code (CC BY 4.0)
// Fonts: Literata, Libre Franklin (SIL OFL 1.1) · Needs postext ≥ 1.28.0
// Two chapters of a physiology textbook and the index that closes them, laid out by
// buildBundle as one book: the terms are marked where the text discusses them, and the
// index chapter prints them with the pages they land on.
import {
buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas, registerResourceImage,
defaultResourceTypes,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'back-of-book-index';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // every colour in the config links to one of these ids
ink: '#1f1a1c', // text: a warm near-black
accent: '#9e1b32', // the one accent (7.4:1 on paper): bands, letter heads, numbers, labels
tint: '#f7ebe9', // the loop in Figure 14.1
rule: '#d9c6c3', // hairlines
muted: '#6b5f61', // running heads, notes, the colophon
paper: '#ffffff', // type on the bands
};
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' } })),
// The engine's defaults link to 'main-color': point it at the accent, so nothing prints blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// A textbook trim, mirrored, in mm. The body is a column and a half: text in the main column,
// figures' captions and clinical notes in the outer channel.
const TRIM = { width: 210, height: 277 };
const MARGIN = { top: 24, bottom: 22, inner: 20, outer: 14 };
const LEAD = 13.6; // body leading in pt: the baseline grid
const [SERIF, SANS] = ['Literata', 'Libre Franklin'];
const [BAND, INDEX_BAND] = [62, 46]; // mm from the trim to the foot of the opener bands
const HEAD_Y = 13; // mm from the top trim to the running heads
const at = (to, edge, x, y) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const label = { fontFamily: SANS, fontSize: pt(7.5), fontWeight: 700, letterSpacing: pt(1.3),
textTransform: 'uppercase' };
// #region answer: marks in the chapters, and an index chapter set in two columns
// The chapters mark each term where the text discusses it:
// the :index[stroke volume]{main} prints the words, files them, bold page
// mitral:index{term="heart!valves!mitral"} prints nothing, files the word before it
// ## Venous return :index{term="venous return" range="start" main} … range="end"
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
#Escreva todos os intervalos por inteiro
Alguns padrões editoriais imprimem os dois números de um intervalo por inteiro.
- rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
+ rangeFormat: 'full', rangeSeparator: t({ en: '–', es: '-' }),#Um índice sem letras de grupo
Um índice curto costuma emendar os grupos, separados só por uma linha em branco.
- groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
+ groups: { enabled: false },Erros comuns
- A captura desta receita não acusa
indexSeeUnknown: uma remissiva cujo destino está escrito de outro jeito que a entrada (Reynolds number contra number, Reynolds) é impressa sem reclamação. Confira cada See do índice pronto com o destino. - Uma lista de subentradas que quebra entre colunas não repete a entrada principal numa linha heart (cont.); uma entrada sem página própria fica sempre com a primeira subentrada, por isso uma entrada principal nunca termina uma coluna sozinha.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Fontes
- Literata (SIL OFL 1.1) · Libre Franklin (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)


