Перейти к основному содержанию
Рецепт номер 72

Рецепты · Глава 5 · Структура книги

Предметный указатель, который следует за текстом

Термины отмечены там, где о них говорит текст; :::index печатает их в две колонки со страницами от buildBundle, диапазонами и отсылками.

На этой странице
Вывод
Canvas · PDF
Postext
Проверено с Postext 1.65.0
Требуется ≥ 1.28.0 · postext-pdf ≥ 1.28.0
Лицензия
Обновлено 11 окт. 2026 г.
Код: MIT · Текст: CC BY 4.0

с. 304–305 · 8–9 из 10

  • Образец на английском: русского издания пока нет
  • Обрезной формат 210 × 277 мм
  • Полторы колонки, средник 7 мм
  • Literata 9,6/13,6
  • Libre Franklin
  • 10 страниц
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 43 мс
  • Строк кода: 213

Коротко

Две главы учебника физиологии с предметным указателем в конце. Слова отмечены в тексте, а номера их страниц книга находит сама, ни один не вписан вручную.

Что получится

Часть IV Principles of Human Physiology, учебника форматом 210 × 277 мм: глава 14, The heart as a pump, и глава 15, Vessels and blood pressure, открываются на правых полосах под красным полем, а клинические заметки и подписи стоят во внешнем канале. Часть закрывает указатель, около девяноста рубрик и тридцати подрубрик в две колонки, как в медицинском учебнике: рубрики со строчной, буквы акцентным цветом, подрубрики с отступом в один em, страница с определением полужирным, see и see also курсивом. Ни один номер страницы не вписан вручную. Каждый термин отмечен в главе там, где текст его объясняет, а указатель читает страницы, на которые попали отметки, с колонцифрами 297–304.

Рецепт отвечает на вопросы

  • Как сделать предметный указатель, номера страниц которого меняются сами, когда текст сдвигается?

Короткий ответ

script.js · строки 45–68в полном коде
// 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') },
};

Ингредиенты

Шрифты
Literata, Libre Franklin (SIL OFL 1.1)
Материалы
Нет: все иллюстрации рисует код

Порядок работы

#1 · Отмечайте место, а не слово

script.js · строки 45–68в полном коде
// 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') },
};

Составитель указателя отмечает места, где термин объясняется, а не каждое место, где встретилось слово. В двух главах stroke volume употреблено двенадцать раз, а указатель отсылает читателя в два места: на страницу 298, где дано определение, и на 299–300, где текст объясняет, чем объём регулируется. Видимая отметка, :index[cardiac output]{main}, печатает свои слова и заносит их в указатель. Невидимая, mitral:index{term="heart!valves!mitral"}, не печатает ничего и берёт страницу слова перед собой: так абзац о четырёх клапанах попадает под heart с рубриками mitral, tricuspid, aortic и pulmonary, а фразу переписывать не нужно. Знак ! разделяет уровни, поэтому у heart их три: клапаны, затем каждый клапан. Отметка работает и в заголовке (там начинаются диапазоны 14.1 и 15.6), и во врезке (heart failure определено в боковой заметке на странице 300).

#2 · Главные страницы, диапазоны и отсылки

script.js · строки 45–68в полном коде
// 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 набирает полужирным страницу с определением термина, и студент, который ищет preload, идёт сразу на 299. range="start" и range="end" с одним и тем же термином ограничивают рассуждение, переходящее на следующую страницу: stroke volume, regulation, 299–300, baroreceptor reflex, 303–4. main в начале делает полужирным весь диапазон. Страница, отмеченная ещё раз внутри своего диапазона, поглощается им, а main там делает диапазон полужирным. see стоит вместо номеров страниц (inotropy. See contractility), а seealso следует за ними (heart failure, 300. See also ejection fraction). Цель с уровнями пишется через !, а печатается с двоеточием: See blood pressure: mean arterial.

#3 · Глава указателя в две колонки

script.js · строки 45–68в полном коде
// 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') },
};

Указатель — последний документ Markdown в книге: # Index {style="index"}, а за ним :::index. Стиль заголовка меняет полторы колонки глав на две с просветом 6 мм, только в своём разделе, и даёт указателю собственные начальную полосу и колонтитул. Указатель набран шрифтом текста, 8,6/11,4 пт, по одному em на уровень, а продолжение строки имеет обратный отступ в два em, поэтому перенесённая строка никогда не совпадает с подрубрикой. rangeFormat: 'chicago' опускает повторяющиеся цифры диапазона (303–4, но 299–300). Испанская версия пишет диапазоны полностью и через дефис (303-304), как принято в испанских книгах.

#4 · Почему номера следуют за текстом

script.js · строки 377–385в полном коде
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 верстает главы по порядку и видит, что в третьей стоит :::index. После первого прохода он собирает все отметки всех глав со страницами, на которые они попали, и передаёт этот список главе указателя как план книги. Потом он верстает книгу снова, не больше трёх проходов, пока номера страниц не перестанут меняться. Перепишите абзац главы 14, поменяйте обрезной формат или кегль текста, и указатель напечатается с новыми страницами. В PDF каждый номер страницы ведёт на свою страницу.

#5 · Начальные полосы и колонтитулы

script.js · строки 72–91в полном коде
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) } } },
  ] } };
}

У глав и указателя общая начальная полоса: поле от обрезного края до 62 мм (у указателя до 46 мм) и название, поставленное на его низ прямоугольником с выключкой по нижнему краю, поэтому название в две строки и название в одну кончаются на одной линии. Надзаголовок печатает {chapterNumber}, которое атрибут заголовка {startAt=14} делает равным 14, а page.pageNumbering.startAt: 297 ставит часть туда, где она стояла бы в книге. Стиль указателя имеет numbered: false, поэтому он не становится главой 16.

Рецепт целиком

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"

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Пишите все диапазоны полностью

В некоторых издательствах принято печатать оба числа диапазона целиком.

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

#Указатель без букв-рубрик

В коротком указателе группы часто идут подряд, разделённые только пустой строкой.

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

Частые ошибки

Подводный камень

Объединённым ячейкам нужны заглушки hiddenBy: берите mergeCells

Ячейки верстаются по позиции в массиве строки, поэтому объединённой ячейке нужны ячейки-заглушки с hiddenBy там, куда она простирается; если их пропустить, как в HTML, все следующие колонки сдвинутся. Объединяйте через mergeCells. Начиная с postext 1.5 таблица с неровной сеткой попадает в doc.contentWarnings как raggedTableGrid, а parseTSV(text, { headerRows }) помечает строки шапки. Таблицы из данных →

  • Снимок этого рецепта не сообщает об indexSeeUnknown: отсылка, цель которой написана не так, как рубрика (Reynolds number вместо number, Reynolds), печатается без предупреждения. Сверьте каждое See в готовом указателе с его целью.
  • Список подрубрик, разрезанный между колонками, не повторяет главную рубрику строкой heart (cont.); рубрика без собственной страницы всегда остаётся с первой подрубрикой, поэтому заголовок никогда не кончает колонку один.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Шрифты
Literata (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)
SandboxPDF