简单来说
一本生理学教材的两章,书末附有索引。词语在正文中做好标记,页码由程序自动找出,不用手工输入。
成品一览
这是Principles of Human Physiology的第四篇,一本210 × 277 mm开本的教科书:第14章The heart as a pump和第15章Vessels and blood pressure都从右页开始,页首有红色横带,临床提示和题注排在外侧的侧栏里。这一篇以一份索引结束,约九十个条目、三十个子条目,按医学教科书的惯例分两栏排:条目用小写,字母标题用强调色,子条目缩进一个em,给出定义的页码用粗体,see和see also用斜体。索引里没有一个页码是手工输入的。每个术语都在正文讲解它的那一章里做了标记,索引读取这些标记落在的页码,即第297页到第304页。
这道食谱解答
- 怎样做一份页码随正文移动自动更新的书末索引?
简短回答
// 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 · 标记段落,而不是词
// 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"}什么也不印,只取它前面那个词所在的页码;讲四个瓣膜的那段文字就是这样把mitral、tricuspid、aortic和pulmonary归到heart之下,而不必改写句子。!用来分隔各级,所以heart下有三级:valves,再到各个瓣膜。标记也可以放在标题里(14.1和15.6的页码范围就从标题开始),或者放在标注框里(heart failure在第300页的旁注中定义)。
#2 · 主要页码、页码范围和交叉引用
// 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 · 分两栏的索引章
// 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 mm,并给索引单独的章首页和书眉。索引用正文字体排,8.6/11.4 pt,每一级子条目缩进一个em,转行悬挂缩进两个em,这样转行永远不会和子条目对齐。rangeFormat: 'chicago'省去页码范围中重复的数字(303–4,但299–300保持不变)。西班牙语版按西班牙语图书的通常做法,用连字符写出完整的范围(303-304)。
#4 · 页码为什么能跟上正文
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 · 章首页和书眉
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 mm处的横带(索引为46 mm),标题由一个底部对齐的框排在横带底边上,所以两行标题和一行标题结束在同一条线上。眉题印出{chapterNumber},由标题属性{startAt=14}设为14;page.pageNumbering.startAt: 297把这一篇放在它在整本书中应处的页码位置。索引样式设为numbered: false,所以它不会成为第16章。
完整食谱
// ═══ 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 },常见问题
- 本食谱的截图不会报告
indexSeeUnknown:交叉引用的目标拼写与条目不一致时(Reynolds number对number, Reynolds),照样印出,不会提示。要对照目标核对成品索引里的每一个See。 - 跨栏断开的子条目列表不会以*heart (cont.)*这样的行重复主标题;没有自身页码的条目总是和它的第一个子条目排在一起,所以标题永远不会单独落在栏尾。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- Literata (SIL OFL 1.1) · Libre Franklin (SIL OFL 1.1)


