En bref
Deux chapitres d’un manuel de physiologie avec un index à la fin. Les mots sont marqués dans le texte, et le livre trouve leurs numéros de page tout seul : aucun n’est saisi à la main.
Ce que vous allez composer
La partie IV de Principles of Human Physiology, un manuel sur une page de 210 × 277 mm : le chapitre 14, The heart as a pump, et le chapitre 15, Vessels and blood pressure, s’ouvrent sur des rectos sous un bandeau rouge et composent leurs notes cliniques et leurs légendes dans un couloir extérieur. La partie se termine par un index d’environ quatre-vingt-dix entrées et trente sous-entrées sur deux colonnes, comme le compose un manuel de médecine : entrées en minuscules, lettres de groupe dans la couleur d’accent, sous-entrées en retrait d’un cadratin, page de définition en gras, see et see also en italique. Aucun numéro de page n’y a été saisi. Chaque terme est marqué dans le chapitre, là où le texte l’explique, et l’index relève les pages où ces marques sont tombées, folios 297 à 304.
Cette recette répond à
- Comment construire un index en fin de livre dont les numéros de page changent d’eux-mêmes quand le texte bouge ?
La réponse courte
// 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') },
};
Ingrédients
- Fonctionnalités
- IndexLivres construits chapitre par chapitreStyles de titreOuvertures composéesAttributs de titreTitres numérotésTitres courants et foliosTitres courants selon le rôle de la pageMarges en miroirColonne marginale pour les flottantsNotes marginalesLégendes latéralesChapitres non numérotésEncadrés flottantsEncadrésLégendes numérotéesExport PDF
- Utilise aussi
- Colonne et demieDes citations qui placent les figuresFigure et Tableau dans votre langueBandeau de chapitre sur toute la largeurStyles de paragraphePolices intégrées au PDFTypes de ressource personnalisésFigures et tableaux comme ressourcesPages liminaires en chiffres romainsGéométrie de sectionTitres courants par sectionExposants et indices
- Typographie
- Literata, Libre Franklin (SIL OFL 1.1)
- Ressources
- Aucune : chaque image est dessinée en code
Préparation
#1 · Marquez le passage, pas le mot
// 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') },
};
Un indexeur marque les endroits où un terme est expliqué, pas chaque endroit où le mot apparaît. Les deux chapitres emploient stroke volume douze fois, et l’index renvoie le lecteur à deux endroits : la page 298, où le terme est défini, et 299–300, où le texte explique ce qui le régule. Une marque visible, :index[cardiac output]{main}, imprime ses mots et les classe. Une marque invisible, mitral:index{term="heart!valves!mitral"}, n’imprime rien et prend la page du mot qui la précède : c’est ainsi que le passage sur les quatre valves classe mitral, tricuspid, aortic et pulmonary sous heart sans reformuler la phrase. Le ! sépare les niveaux : heart en reçoit donc trois, les valves, puis chaque valve. Une marque fonctionne aussi dans un titre (les étendues de 14.1 et 15.6 commencent là) et dans un encadré (heart failure est défini dans la note latérale de la page 300).
#2 · Pages principales, étendues et renvois
// 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 compose en gras la page qui définit un terme : un étudiant qui cherche preload va d’abord en page 299. range="start" et range="end", avec le même terme, bornent une discussion qui passe un saut de page : stroke volume, regulation, 299–300, baroreceptor reflex, 303–4. Un main sur le début met toute l’étendue en gras. Une page marquée de nouveau à l’intérieur de sa propre étendue s’y fond, et un main à cet endroit met l’étendue en gras. see remplace les numéros de page (inotropy. See contractility), et seealso les suit (heart failure, 300. See also ejection fraction). Une cible à plusieurs niveaux s’écrit avec ! et s’imprime avec un deux-points : See blood pressure: mean arterial.
#3 · Un chapitre d’index sur deux colonnes
// 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’index est le dernier document Markdown du livre, # Index {style="index"} suivi de :::index. Le style de titre remplace la colonne et demie des chapitres par deux colonnes espacées de 6 mm, dans sa seule section, et donne à l’index sa propre ouverture et son propre titre courant. L’index est composé dans le caractère du texte en 8,6/11,4 pt, un cadratin par sous-niveau, et une ligne de suite se place en retrait de deux cadratins : une ligne renvoyée ne s’aligne jamais sur une sous-entrée. rangeFormat: 'chicago' supprime les chiffres qu’une étendue répète (303–4, mais 299–300). L’édition espagnole écrit les étendues en entier avec un trait d’union (303-304), l’usage courant dans les livres espagnols.
#4 · Pourquoi les numéros suivent le texte
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 met les chapitres en page dans l’ordre et découvre que le troisième contient :::index. Après la première passe, il rassemble chaque marque de chaque chapitre avec la page où elle est tombée, et transmet cette liste au chapitre d’index comme plan. Puis il remet le livre en page, jusqu’à trois passes, jusqu’à ce qu’aucun numéro de page ne bouge. Réécrivez un paragraphe du chapitre 14, changez le format ou le corps du texte courant, et l’index se réimprime avec les nouvelles pages. Dans le PDF, chaque numéro de page renvoie à sa page.
#5 · Ouvertures et titres courants
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) } } },
] } };
}
Les chapitres et l’index partagent une même ouverture : un bandeau du bord de coupe jusqu’à 62 mm (46 mm pour l’index), le titre posé sur son pied par une boîte alignée en bas : un titre de deux lignes et un titre d’une ligne finissent donc sur la même ligne. Le surtitre imprime {chapterNumber}, que l’attribut de titre {startAt=14} règle à 14, et page.pageNumbering.startAt: 297 place la partie là où elle se trouverait dans le livre. Le style d’index est numbered: false : il ne devient donc pas le chapitre 16.
La recette complète
// ═══ 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"
Le script.js composé s’exécute tel quel : collez-le dans le script de module de n’importe quelle page, ou ouvrez la recette sur CodePen. Dossier de la recette sur GitHub ↗ (s’ouvre dans un nouvel onglet)
Variantes
#Écrivez chaque étendue en entier
Certaines chartes maison impriment en entier les deux numéros d’une étendue.
- rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
+ rangeFormat: 'full', rangeSeparator: t({ en: '–', es: '-' }),#Un index sans lettres de groupe
Un index court enchaîne souvent ses groupes, séparés seulement par une ligne blanche.
- groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
+ groups: { enabled: false },Erreurs fréquentes
- La capture de cette recette ne signale pas
indexSeeUnknown: un renvoi dont la cible s’écrit autrement que l’entrée (Reynolds number contre number, Reynolds) s’imprime sans protester. Relisez chaque See de l’index terminé en le comparant à sa cible. - Une liste de sous-entrées coupée entre deux colonnes ne répète pas son entrée principale sous forme de ligne heart (cont.) ; une entrée sans page propre reste toujours avec sa première sous-entrée : une entrée principale ne finit donc jamais seule une colonne.
Crédits
- Recette
- Ignacio Ferro
- Texte
- Texte original, CC BY 4.0
- Polices
- Literata (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)
Modifier ce texte ↗ (s’ouvre dans un nouvel onglet)Dossier de la recette sur GitHub ↗ (s’ouvre dans un nouvel onglet)


