En poques paraules
Dos capítols d'un llibre de fisiologia amb un índex al final. Les paraules es marquen al text i el llibre troba sol els números de pàgina, sense escriure'ls a mà.
Què compondràs
La part IV de Principios de fisiología humana, un manual en pàgina de 210 × 277 mm: el capítol 14, El corazón como bomba, i el 15, Los vasos y la presión arterial, s'obren en pàgina senar sota una banda vermella i porten els requadres clínics i els peus en una columna lateral exterior. La part es tanca amb un índex analític d'unes noranta entrades i trenta subentrades a dues columnes, com el compon un manual de medicina: entrades en minúscula, lletres de grup en el color d'accent, subentrades a un quadratí, la pàgina que defineix el terme en negreta, véase i véase también en cursiva. No s'ha teclejat cap número de pàgina. Cada terme està marcat al capítol, on el text l'explica, i l'índex llegeix les pàgines on han caigut aquestes marques, de la 297 a la 304.
Aquesta recepta respon a
- Com faig un índex analític els números de pàgina del qual canviïn sols quan el text es mou?
La 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') },
};
Ingredients
- Funcions
- Índex analíticLlibres construïts capítol a capítolEstils de títolObertures dissenyadesAtributs de títolTítols numeratsCapçaleres i folisCapçaleres segons el tipus de pàginaMarges simètricsColumna al marge per a flotantsNotes al margePeus lateralsCapítols sense númeroRequadres flotantsRequadresPeus numeratsExportació a PDF
- També fa servir
- Columna i mitjaCites que col·loquen les figuresFigura i Taula en la teva llenguaBanda de capítol d'amplada completaEstils de paràgrafFonts incrustades al PDFTipus de recurs propisFigures i taules com a recursosPreliminars en romansGeometria per seccióCapçaleres per seccióSuperíndexs i subíndexs
- Tipografia
- Literata, Libre Franklin (SIL OFL 1.1)
- Recursos
- Cap: totes les imatges es dibuixen en codi
Elaboració
#1 · Marca el passatge, no la paraula
// 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') },
};
Qui fa un índex marca els llocs on s'explica un terme, no cada vegada que apareix la paraula. Els dos capítols diuen volumen sistólico una dotzena de vegades, i l'índex envia el lector a dos llocs: la pàgina 298, on es defineix, i la 299-300, on s'explica què el regula. Una marca visible, :index[gasto cardíaco]{main}, imprimeix les seves paraules i les arxiva. Una d'invisible, mitral:index{term="corazón!válvulas!mitral"}, no imprimeix res i pren la pàgina de la paraula anterior; així el passatge de les quatre vàlvules arxiva mitral, tricúspide, aórtica i pulmonar sota corazón sense tocar la frase. El ! separa nivells: corazón en té tres, vàlvules i després cada vàlvula. Una marca funciona també en un títol (els intervals de 14.1 i 15.6 hi comencen) i en un requadre (insuficiencia cardíaca es defineix a la nota lateral de la pàgina 300).
#2 · Pàgines principals, intervals i remissions
// 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 posa en negreta la pàgina que defineix un terme, de manera que qui cerca precarga va primer a la 299. range="start" i range="end", amb el mateix terme, delimiten una explicació que travessa un salt de pàgina: volumen sistólico, regulación, 299-300. Un main a l'inici posa en negreta tot l'interval. Una pàgina marcada una altra vegada dins del seu propi interval s'hi fon, i un main en aquest punt posa l'interval en negreta. see substitueix els números de pàgina (inotropismo. Véase contractilidad) i seealso va darrere seu (insuficiencia cardíaca, 300. Véase también fracción de eyección). Una destinació amb nivells s'escriu amb ! i s'imprimeix amb dos punts: Véase presión arterial: media.
#3 · Un capítol d'índex a dues columnes
// 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'índex és l'últim document Markdown del llibre: # Índice analítico {style="index"} i, a sota, :::index. L'estil d'encapçalament canvia la columna i mitja dels capítols per dues columnes separades 6 mm, només a la seva secció, i dona a l'índex la seva pròpia obertura i la seva capçalera. Es compon en la lletra del text a 8,6/11,4 pt, un quadratí per nivell de subentrada, i les línies que es parteixen sagnen dos quadratins, perquè mai no quedin alineades amb una subentrada. En castellà els intervals s'escriuen complets i amb guionet (303-304), com als llibres en castellà; l'edició anglesa fa servir rangeFormat: 'chicago', que suprimeix les xifres que es repeteixen (303–4, però 299–300).
#4 · Per què els números segueixen el text
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 compon els capítols en ordre i veu que el tercer conté :::index. Després de la primera passada reuneix les marques de tots els capítols amb la pàgina on ha caigut cadascuna i les dona al capítol de l'índex com a esquema. Després torna a compondre el llibre, tres passades com a màxim, fins que cap número no es mou. Reescriu un paràgraf del capítol 14, canvia el format o el cos de lletra, i l'índex es reimprimeix amb les pàgines noves. Al PDF cada número de pàgina és un enllaç a la seva pàgina.
#5 · Obertures i capçaleres
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) } } },
] } };
}
Capítols i índex comparteixen una obertura: una banda des del tall fins a 62 mm (46 mm a l'índex), amb el títol recolzat al seu peu mitjançant una caixa alineada a baix, de manera que un títol de dues línies i un d'una acaben a la mateixa línia. L'avanttítol imprimeix {chapterNumber}, que l'atribut {startAt=14} del títol fixa en 14, i page.pageNumbering.startAt: 297 col·loca la part on seria dins del llibre. L'estil de l'índex porta numbered: false, així que no es converteix en el capítol 16.
La recepta 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 = 'es'; // @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"
L'script.js compost funciona tal com és: enganxa'l com a script de mòdul en qualsevol pàgina o obre la recepta a CodePen. Carpeta de la recepta a GitHub ↗ (s'obre en una pestanya nova)
Variants
#Escriu tots els intervals complets
Alguns llibres anglesos també escriuen complets els dos números d'un interval.
- rangeFormat: t({ en: 'chicago', es: 'full' }), rangeSeparator: t({ en: '–', es: '-' }),
+ rangeFormat: 'full', rangeSeparator: t({ en: '–', es: '-' }),#Un índex sense lletres de grup
Un índex curt sol encadenar els grups, separats només per una línia en blanc.
- groups: { ...label, fontSize: pt(9.5), letterSpacing: pt(0), color: col('accent') },
+ groups: { enabled: false },Errors freqüents
- La captura d'aquesta recepta no avisa de
indexSeeUnknown: una remissió amb una destinació escrita d'una altra manera que l'entrada (número de Reynolds davant de Reynolds, número de) s'imprimeix sense queixa. Confronta cada Véase de l'índex acabat amb la seva destinació. - Una llista de subentrades que es parteix entre columnes no repeteix la seva entrada principal en una línia corazón (cont.); una entrada sense pàgina pròpia va sempre amb la seva primera subentrada, així que un encapçalament mai no tanca una columna tot sol.
Crèdits
- Recepta
- Ignacio Ferro
- Text
- Text original, CC BY 4.0
- Fonts
- Literata (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)
- Codi
- MIT, com Postext
Editar aquest text ↗ (s'obre en una pestanya nova)Carpeta de la recepta a GitHub ↗ (s'obre en una pestanya nova)


