Saltar al contenido principal
Receta número 72

Recetario · Capítulo 5 · Estructura del libro

Un índice analítico que sigue al texto

Términos marcados donde el texto los explica, impresos por :::index a dos columnas con las páginas que les da buildBundle, intervalos y remisiones.

En esta página
Salida
Canvas · PDF
Postext
Probada con Postext 1.65.0
Requiere ≥ 1.28.0 · postext-pdf ≥ 1.28.0
Licencia
Actualizada el 11 oct 2026
Código MIT · Texto CC BY 4.0

pp. 304–305 · 8–9 de 10

  • Formato 210 × 277 mm
  • Columna y media, medianil de 7 mm
  • Literata 9,6/13,6
  • Libre Franklin
  • 10 páginas
  • Nivel
  • Postext 1.57.1
  • Compuesto en 47 ms
  • 213 líneas de código

En pocas palabras

Dos capítulos de un libro de fisiología con un índice al final. Las palabras se marcan en el texto y el libro encuentra solo sus números de página, sin escribirlos a mano.

Lo que vas a componer

La parte IV de Principios de fisiología humana, un manual en página de 210 × 277 mm: el capítulo 14, El corazón como bomba, y el 15, Los vasos y la presión arterial, se abren en página impar bajo una banda roja y llevan los recuadros clínicos y los pies en una columna lateral exterior. La parte se cierra con un índice analítico de unas noventa entradas y treinta subentradas a dos columnas, como lo compone un manual de medicina: entradas en minúscula, letras de grupo en el color de acento, subentradas a un cuadratín, la página que define el término en negrita, véase y véase también en cursiva. Ningún número de página se ha tecleado. Cada término está marcado en el capítulo, donde el texto lo explica, y el índice lee las páginas en que han caído esas marcas, de la 297 a la 304.

Esta receta responde a

  • ¿Cómo hago un índice analítico cuyos números de página cambien solos cuando el texto se mueve?

La respuesta corta

script.js · líneas 45–68en el código 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') },
};

Ingredientes

Tipografía
Literata, Libre Franklin (SIL OFL 1.1)
Recursos
Ninguno: todas las imágenes se dibujan en código

Elaboración

#1 · Marca el pasaje, no la palabra

script.js · líneas 45–68en el código 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') },
};

Quien hace un índice marca los lugares donde se explica un término, no cada vez que aparece la palabra. Los dos capítulos dicen volumen sistólico una docena de veces, y el índice manda al lector a dos sitios: la página 298, donde se define, y la 299-300, donde se explica qué lo regula. Una marca visible, :index[gasto cardíaco]{main}, imprime sus palabras y las archiva. Una invisible, mitral:index{term="corazón!válvulas!mitral"}, no imprime nada y toma la página de la palabra anterior; así el pasaje de las cuatro válvulas archiva mitral, tricúspide, aórtica y pulmonar bajo corazón sin tocar la frase. El ! separa niveles: corazón tiene tres, válvulas y luego cada válvula. Una marca funciona también en un título (los intervalos de 14.1 y 15.6 empiezan ahí) y en un recuadro (insuficiencia cardíaca se define en la nota lateral de la página 300).

#2 · Páginas principales, intervalos y remisiones

script.js · líneas 45–68en el código 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 pone en negrita la página que define un término, de modo que quien busca precarga va primero a la 299. range="start" y range="end", con el mismo término, acotan una explicación que cruza un salto de página: volumen sistólico, regulación, 299-300. Un main en el inicio pone en negrita todo el intervalo. Una página marcada otra vez dentro de su propio intervalo se funde con él, y un main ahí pone el intervalo en negrita. see sustituye a los números de página (inotropismo. Véase contractilidad) y seealso va detrás de ellos (insuficiencia cardíaca, 300. Véase también fracción de eyección). Un destino con niveles se escribe con ! y se imprime con dos puntos: Véase presión arterial: media.

#3 · Un capítulo de índice a dos columnas

script.js · líneas 45–68en el código 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') },
};

El índice es el último documento Markdown del libro: # Índice analítico {style="index"} y, debajo, :::index. El estilo de encabezado cambia la columna y media de los capítulos por dos columnas separadas 6 mm, solo en su sección, y le da al índice su propia apertura y su cabecera. Se compone en la letra del texto a 8,6/11,4 pt, un cuadratín por nivel de subentrada, y las líneas que se parten sangran dos cuadratines, para que nunca queden alineadas con una subentrada. En español los intervalos se escriben completos y con guion (303-304), como en los libros en castellano; la edición inglesa usa rangeFormat: 'chicago', que suprime las cifras que se repiten (303–4, pero 299–300).

#4 · Por qué los números siguen al texto

script.js · líneas 371–379en el código 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 compone los capítulos en orden y ve que el tercero contiene :::index. Tras la primera pasada reúne las marcas de todos los capítulos con la página en que ha caído cada una y se las da al capítulo del índice como esquema. Después vuelve a componer el libro, tres pasadas como mucho, hasta que ningún número se mueve. Reescribe un párrafo del capítulo 14, cambia el formato o el cuerpo de letra, y el índice se reimprime con las páginas nuevas. En el PDF cada número de página es un enlace a su página.

#5 · Aperturas y cabeceras

script.js · líneas 72–91en el código 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) } } },
  ] } };
}

Capítulos e índice comparten una apertura: una banda desde el corte hasta 62 mm (46 mm en el índice), con el título apoyado en su pie mediante una caja alineada abajo, de modo que un título de dos líneas y uno de una acaban en la misma línea. El antetítulo imprime {chapterNumber}, que el atributo {startAt=14} del título fija en 14, y page.pageNumbering.startAt: 297 coloca la parte donde estaría en el libro. El estilo del índice lleva numbered: false, así que no se convierte en el capítulo 16.

La receta 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 = '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"

El script.js compuesto funciona tal cual: pégalo como script de módulo en cualquier página o abre la receta en CodePen. Carpeta de la receta en GitHub ↗ (se abre en una nueva pestaña)

Variantes

#Escribe todos los intervalos completos

Algunos libros ingleses también escriben completos los dos números de un intervalo.

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

#Un índice sin letras de grupo

Un índice corto suele encadenar sus grupos, separados solo por una línea en blanco.

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

Errores frecuentes

Error frecuente

Las celdas combinadas necesitan hiddenBy: usa mergeCells

Las celdas se colocan según su posición en la fila, así que una celda combinada necesita celdas de relleno marcadas con hiddenBy donde se extiende; omitirlas, como en HTML, desplaza todas las columnas siguientes. Combina celdas con mergeCells. Desde postext 1.5 una tabla con una rejilla irregular se anota en doc.contentWarnings como raggedTableGrid, y parseTSV(texto, { headerRows }) marca las filas de cabecera. Tablas a partir de datos →

  • La captura de esta receta no avisa de indexSeeUnknown: una remisión cuyo destino está escrito de otra forma que la entrada (número de Reynolds frente a Reynolds, número de) se imprime sin queja. Coteja cada Véase del índice terminado con su destino.
  • Una lista de subentradas que se parte entre columnas no repite su entrada principal en una línea corazón (cont.); una entrada sin página propia va siempre con su primera subentrada, así que un encabezado nunca cierra una columna solo.

Créditos

Texto
Texto original, CC BY 4.0
Fuentes
Literata (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)
SandboxPDF