Vai al contenuto principale
Ricetta numero 72

Ricettario · Capitolo 5 · Struttura del libro

Un indice analitico che segue il testo

Termini marcati dove il testo ne parla, stampati da :::index su due colonne con le pagine trovate da buildBundle, intervalli e rimandi.

In questa pagina
Output
Canvas · PDF
Livello
Avanzato
Postext
Provata con Postext 1.65.0
Richiede ≥ 1.28.0 · postext-pdf ≥ 1.28.0
Licenza
Aggiornata il 11 ott 2026
Codice MIT · Testo CC BY 4.0

pp. 304–305 · 8–9 di 10

  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 210 × 277 mm
  • Colonna e mezza, Intercolonna di 7 mm
  • Literata 9,6/13,6
  • Libre Franklin
  • 10 pagine
  • Livello
  • Postext 1.57.1
  • Impaginato in 43 ms
  • 213 righe di codice

In breve

Due capitoli di un manuale di fisiologia con un indice analitico in fondo. Le parole sono marcate nel testo e il libro trova da solo i loro numeri di pagina: nessuno è scritto a mano.

Che cosa comporrai

La parte IV di Principles of Human Physiology, un manuale su una pagina di 210 × 277 mm: il capitolo 14, The heart as a pump, e il capitolo 15, Vessels and blood pressure, si aprono su recto sotto una fascia rossa e compongono le note cliniche e le didascalie in un canale esterno. La parte si chiude con un indice di circa novanta voci e trenta sottovoci su due colonne, come lo compone un manuale di medicina: voci in minuscolo, lettere di gruppo nel colore d’accento, sottovoci rientrate di un quadratone, la pagina che definisce il termine in grassetto, see e see also in corsivo. Nessun numero di pagina è stato scritto a mano. Ogni termine è marcato nel capitolo, dove il testo lo spiega, e l’indice legge le pagine su cui quelle marche sono cadute, pagine da 297 a 304.

Questa ricetta risponde a

  • Come costruisco un indice analitico i cui numeri di pagina cambiano da soli quando il testo si sposta?

La risposta breve

script.js · righe 45–68nel codice completo
// 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') },
};

Ingredienti

Tipo
Literata, Libre Franklin (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Marca il passo, non la parola

script.js · righe 45–68nel codice completo
// 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') },
};

Chi compila un indice marca i punti in cui un termine viene spiegato, non ogni punto in cui la parola compare. I due capitoli usano stroke volume dodici volte, e l’indice manda il lettore in due posti: pagina 298, dove il termine è definito, e 299–300, dove il testo spiega che cosa lo regola. Una marca visibile, :index[cardiac output]{main}, stampa le sue parole e le archivia. Una invisibile, mitral:index{term="heart!valves!mitral"}, non stampa nulla e prende la pagina della parola che la precede: è così che il passo sulle quattro valvole archivia mitral, tricuspid, aortic e pulmonary sotto heart senza riformulare la frase. Il ! separa i livelli, quindi heart ne riceve tre: le valvole, poi ciascuna valvola. Una marca funziona anche in un titolo (gli intervalli di 14.1 e 15.6 cominciano lì) e in un riquadro (heart failure è definito nella nota laterale di pagina 300).

#2 · Pagine principali, intervalli e rimandi

script.js · righe 45–68nel codice completo
// 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 mette in grassetto la pagina che definisce un termine, così uno studente che cerca preload va prima a pagina 299. range="start" e range="end", con lo stesso termine, delimitano una trattazione che scavalca un’interruzione di pagina: stroke volume, regulation, 299–300, baroreceptor reflex, 303–4. Un main sull’inizio rende grassetto tutto l’intervallo. Una pagina marcata di nuovo nel proprio intervallo vi si fonde, e un main in quel punto rende grassetto l’intervallo. see prende il posto dei numeri di pagina (inotropy. See contractility), e seealso li segue (heart failure, 300. See also ejection fraction). Un bersaglio con più livelli si scrive con ! e si stampa con i due punti: See blood pressure: mean arterial.

#3 · Un capitolo indice su due colonne

script.js · righe 45–68nel codice completo
// 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') },
};

L’indice è l’ultimo documento Markdown del libro, # Index {style="index"} seguito da :::index. Lo stile del titolo sostituisce la colonna e mezza dei capitoli con due colonne a 6 mm l’una dall’altra, solo nella propria sezione, e dà all’indice un’apertura e una testatina proprie. L’indice è composto nel carattere del testo a 8,6/11,4 pt, un quadratone per ogni sottolivello, e una riga di rientro sporge di due quadratoni, così una riga che va a capo non si allinea mai a una sottovoce. rangeFormat: 'chicago' elimina le cifre che un intervallo ripete (303–4, ma 299–300). L’edizione spagnola scrive gli intervalli per intero con un trattino (303-304), l’uso comune nei libri spagnoli.

#4 · Perché i numeri seguono il testo

script.js · righe 377–385nel codice completo
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 impagina i capitoli in ordine e scopre che il terzo contiene :::index. Dopo la prima passata raccoglie ogni marca di ogni capitolo con la pagina su cui è caduta, e passa quell’elenco al capitolo indice come sua struttura. Poi impagina di nuovo il libro, fino a tre passate, finché nessun numero di pagina si sposta. Riscrivi un paragrafo del capitolo 14, cambia il formato o il corpo del testo, e l’indice si ristampa con le pagine nuove. Nel PDF ogni numero di pagina è un collegamento alla sua pagina.

#5 · Aperture e testatine

script.js · righe 72–91nel codice completo
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) } } },
  ] } };
}

I capitoli e l’indice condividono un’unica apertura: una fascia dal rifilo fino a 62 mm (46 mm per l’indice), con il titolo composto sul suo piede da un riquadro allineato in basso, così un titolo su due righe e uno su una riga finiscono sulla stessa riga. L’occhiello stampa {chapterNumber}, che l’attributo del titolo {startAt=14} porta a 14, e page.pageNumbering.startAt: 297 colloca la parte dove starebbe nel libro. Lo stile dell’indice è numbered: false, quindi non diventa il capitolo 16.

La ricetta completa

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

Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)

Varianti

#Scrivi ogni intervallo per intero

Alcune norme redazionali stampano per intero entrambi i numeri di un intervallo.

-  rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
+  rangeFormat: 'full', rangeSeparator: t({ en: '–', es: '-' }),

#Un indice senza lettere di gruppo

Un indice breve spesso fa scorrere i gruppi uno dopo l’altro, separati solo da una riga bianca.

-  groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
+  groups: { enabled: false },

Errori frequenti

Errore frequente

Le celle unite richiedono segnaposto hiddenBy: usa mergeCells

Le celle si dispongono secondo la loro posizione nell’array della riga, quindi una cella unita richiede celle segnaposto marcate hiddenBy dove si estende; ometterle, come fa l’HTML, sposta tutte le colonne successive. Costruisci le unioni con mergeCells. Da postext 1.5 una tabella con una griglia irregolare viene segnalata in doc.contentWarnings come raggedTableGrid, e parseTSV(text, { headerRows }) marca le righe di testa. Tabelle dai dati →

  • La cattura di questa ricetta non segnala indexSeeUnknown: un rimando il cui bersaglio è scritto in modo diverso dalla voce (Reynolds number contro number, Reynolds) si stampa senza proteste. Confronta ogni See dell’indice finito con il suo bersaglio.
  • Un elenco di sottovoci che si spezza tra due colonne non ripete la sua voce principale come riga heart (cont.); una voce senza una pagina propria resta sempre con la sua prima sottovoce, così un titolo di voce non chiude mai da solo una colonna.

Crediti

Testo
Testo originale, CC BY 4.0
Font
Literata (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)
SandboxPDF