简单来说
一本为小木屋计算太阳能板和蓄电池的简短手册。第3章回指第1章的表,或第1章预告第2章的某一节时,印出的编号和页码都正确,而且可以点击。
成品一览
一本简短的技术手册《Power for a Cabin》(西班牙文版为《Energía para una cabaña》),用IBM Plex排在178 × 233 mm的页面上:封面上的太阳轨迹由代码绘制,一页目录,三章都以夜蓝色色带开篇。书讲的是为一座小木屋配置太阳能系统,所以各章互相依靠。第3章引用第1章的用电量表和第2章的日照图;第1章把读者引向2.3节,并给出页码。作者在四个独立的Markdown文件里按pandoc-crossref的写法写@tbl:loads和@sec:array-size。buildBundle把它们排成一本书,每个引用都印出目标在本章得到的编号、所在页码,并做成链接。
这道食谱解答
- 怎样按pandoc-crossref的写法引用另一章的图、表或节,并让编号始终正确?
- 怎样引用某一节及其所在页码,并在书变动时保持正确?
简短回答
// buildBundle lays the chapters out in order. Each chapter whose text names a target it
// does not hold (`@sec:array-size` in chapter 1, `@tbl:loads` in chapter 3) is laid out
// with the outline of the whole book, so the reference prints "section 2.3" and its page,
// and links to it. Headings carry their ids in the Markdown, `## Sizing the array
// {#sec:array-size}`; figures and tables are resources whose ids are what follows the @.
const book = () => buildBundle({ chapters, config: config(), resources });
const crossRefs = {
chapter: t({ en: 'chapter {n}', es: 'capítulo {n}' }), // @sec:array → "chapter 2"
section: t({ en: 'section {n}', es: 'apartado {n}' }), // @sec:losses → "section 2.2"
page: t({ en: 'p. {n}', es: 'pág. {n}' }), // :ref{id="sec:losses" style=page} → "p. 7"
};
// Figures and tables count per chapter ({h1}.{n}) and carry on from one document to the
// next. A reference prints the type's shortLabel: @fig:sun → "Fig. 2.1", @Tbl:loads (capital
// T, at the start of a sentence) → "Table 1.1", [-@tbl:loads] → the bare "1.1".
const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
shortLabel: type.id === 'table' ? t({ en: 'table', es: 'tabla' })
: t({ en: 'fig.', es: 'figura' }),
...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));
用料
- 类型
- IBM Plex Serif, IBM Plex Sans Condensed, IBM Plex Mono(SIL OFL 1.1)
- 素材
- 无:所有图片都用代码绘制
做法
#1 · 每个目标在全书只命名一次
代码就是上面的简短回答。标题带前缀的Pandoc标识符,## Sizing the array {#sec:array-size}。图和表是在脚本里声明的资源,标识符写法相同,fig:sun和tbl:loads,所以无论图在两段之前还是两章之前,正文都写@fig:sun。标识符必须在全书唯一,而不只是在本章唯一。
#2 · 把各章排成一本书
// buildBundle lays the chapters out in order. Each chapter whose text names a target it
// does not hold (`@sec:array-size` in chapter 1, `@tbl:loads` in chapter 3) is laid out
// with the outline of the whole book, so the reference prints "section 2.3" and its page,
// and links to it. Headings carry their ids in the Markdown, `## Sizing the array
// {#sec:array-size}`; figures and tables are resources whose ids are what follows the @.
const book = () => buildBundle({ chapters, config: config(), resources });
const crossRefs = {
chapter: t({ en: 'chapter {n}', es: 'capítulo {n}' }), // @sec:array → "chapter 2"
section: t({ en: 'section {n}', es: 'apartado {n}' }), // @sec:losses → "section 2.2"
page: t({ en: 'p. {n}', es: 'pág. {n}' }), // :ref{id="sec:losses" style=page} → "p. 7"
};
// Figures and tables count per chapter ({h1}.{n}) and carry on from one document to the
// next. A reference prints the type's shortLabel: @fig:sun → "Fig. 2.1", @Tbl:loads (capital
// T, at the start of a sentence) → "Table 1.1", [-@tbl:loads] → the bare "1.1".
const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
shortLabel: type.id === 'table' ? t({ en: 'table', es: 'tabla' })
: t({ en: 'fig.', es: 'figura' }),
...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));
buildBundle把图表计数器从一章带到下一章,所以第3章的第一张表是3.1,而第3章里的@tbl:loads仍印成table 1.1。如果某章正文提到不在本章的标题,这一章就会带着全书的大纲来排,并重排(最多三轮)直到大纲里的页码不再变化。所以第1章在第2章还没排出来之前就能印出section 2.1 … p. 6。
#3 · 选择引用印出的词
crossRefs设定chapter、section和p.(西班牙文为capítulo、apartado和pág.)。图或表的引用印出其类型的shortLabel,这里像pandoc-crossref一样用小写:fig. 2.1、table 1.1。前缀首字母大写,如@Tbl:loads或@Sec:array,会让句首的标签大写;[-@tbl:losses]只印编号,用于tables 2.1 and 3.1这样的写法。
#4 · 向前引用节,向后引用图
图或表在第一次被引用的地方编号并放置。在第1章写@fig:soc会让它成为图1.2,并放进第1章。所以第1章向前引用的是@sec:autonomy,每张图、每张表都先在本章被引用,后面各章再自由回指。页码跟着节走,:ref{id="sec:sun-hours" style=page}:对资源的引用只印标签和编号,不印页码。
#5 · 章首和封面出自同一条色带
const BAND = 52; // mm from the trim's top
const opener = { enabled: true, minHeight: mm(54), slot: { elements: [
{ kind: 'box', id: 'band', style: { backgroundColor: col('night') },
placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(BAND + 3) } } },
{ kind: 'text', id: 'kicker', content: t({ en: 'Chapter', es: 'Capítulo' }), ...caps(8.5),
color: col('sun'), placement: at('container', 'top-left', 0, 2) },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: COND, fontWeight: 600,
fontSize: pt(30), lineHeight: 1.05, color: col('paper'), align: 'left', overflow: 'wrap',
placement: { ...at('#kicker', 'below', 0, 3), size: { width: mm(MEASURE - 26) } } },
{ kind: 'text', id: 'number', content: '{chapterNumber}', fontFamily: COND, fontWeight: 600,
fontSize: pt(84), lineHeight: 1, color: col('sun'), align: 'right',
placement: { ...at('container', 'top-right', 0, -6), size: { width: mm(40) } } },
{ kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: SERIF, italic: true,
fontSize: pt(11), lineHeight: 1.38, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { ...at('container', 'top-left', 0, BAND - MARGIN.top + 8),
size: { width: mm(MEASURE - 10) } } },
] } };
// The contents page wears the same band, with the book's subtitle as its kicker.
const contentsOpener = { ...opener, minHeight: mm(BAND - MARGIN.top + 4), slot: { elements:
opener.slot.elements.filter((e) => ['band', 'kicker', 'title'].includes(e.id))
.map((e) => (e.id === 'kicker' ? { ...e, content: '{subtitle}' } : e)) } };
每章和目录页的色带都从裁切线顶部向下55 mm,目录页复用同样的元素;章号是{chapterNumber},导语是标题属性。
const COVER_BAND = 168; // mm
const cover = { enabled: true, slot: { elements: [
{ kind: 'box', id: 'band', style: { backgroundColor: col('night') },
placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(COVER_BAND) } } },
{ kind: 'image', id: 'art', resourceId: 'cover',
placement: { ...at('bleed', 'top-left'), size: { width: 'fill' } } },
// Stacked upwards from the subtitle, so a title of one line or two keeps its distance.
{ kind: 'text', id: 'subtitle', content: '{subtitle}', fontFamily: SERIF, italic: true,
fontSize: pt(14), color: col('tint'), align: 'left',
placement: at('page', 'top-left', MARGIN.inner, COVER_BAND - 22) },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: COND, fontWeight: 600,
fontSize: pt(52), lineHeight: 1, color: col('paper'), align: 'left', overflow: 'wrap',
placement: { ...at('#subtitle', 'above', 0, -4), size: { width: mm(140) } } },
{ kind: 'text', id: 'kicker', content: '{attr.kicker}', ...caps(8.5), color: col('sun'),
placement: at('#title', 'above', 0, -4) },
{ kind: 'text', id: 'author', content: '{author}', fontFamily: COND, fontWeight: 600,
fontSize: pt(13), color: col('ink'), align: 'left',
placement: at('page', 'top-left', MARGIN.inner, COVER_BAND + 14) },
{ kind: 'text', id: 'edition', content: '{attr.edition}', ...caps(7.5), color: col('muted'),
placement: at('#author', 'below', 0, 2.5) },
] } };
完整食谱
// ═══ Postext Cookbook · Nº 094 · A technical book whose references cross chapters ═══
// https://postext.dev/en/cookbook/technical-book-crossref-chapters
// Code: MIT · Text: original (CC BY 4.0) · Charts: generated in code (CC BY 4.0)
// Fonts: IBM Plex Serif, Sans Condensed and Mono (SIL OFL 1.1) · Needs postext ≥ 1.28.0
// A small handbook in four Markdown documents. The text writes @fig:sun, @tbl:loads and
// @sec:array-size the way pandoc-crossref reads them, and buildBundle resolves each one to
// the right number, title or page wherever in the book its target lies.
import {
buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas, registerResourceImage,
defaultResourceTypes, parseTSV, setAlignment, inlineSvgFonts,
} 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 = 'technical-book-crossref-chapters';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a night-blue band, one burnt-orange accent, an amber for the charts
const palette = {
ink: '#1c1f24', // text: a cool near-black
night: '#1f3247', // openers, the cover, table heads
accent: '#a8471a', // numbers, kickers, references (5.6:1 on paper)
sun: '#e9a33a', // the charts and the cover only, never text on paper
tint: '#f5ede3', // daylight in the charts
rule: '#cfc7bc', // hairlines
muted: '#5e636a', // running heads, colophon, chart labels
paper: '#ffffff',
};
// Each colour names its palette entry and carries its hex.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = Object.entries({ ...palette, 'main-color': palette.accent })
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// #endregion
const SERIF = 'IBM Plex Serif', COND = 'IBM Plex Sans Condensed', MONO = 'IBM Plex Mono';
const TRIM = { w: 178, h: 233 }; // mm: a technical-book trim
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 32 }; // a 126 mm measure
const LEAD = 13.8; // pt: the body leading
const MEASURE = TRIM.w - MARGIN.inner - MARGIN.outer;
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const caps = (size, extra = {}) => ({ fontFamily: MONO, fontSize: pt(size), fontWeight: 600,
letterSpacing: pt(size * 0.14), textTransform: 'uppercase', align: 'left', ...extra });
// #region answer: one set of identifiers for the whole book, resolved across chapters
// buildBundle lays the chapters out in order. Each chapter whose text names a target it
// does not hold (`@sec:array-size` in chapter 1, `@tbl:loads` in chapter 3) is laid out
// with the outline of the whole book, so the reference prints "section 2.3" and its page,
// and links to it. Headings carry their ids in the Markdown, `## Sizing the array
// {#sec:array-size}`; figures and tables are resources whose ids are what follows the @.
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#正文里印“Figure 2.1”
把引用写全的书用类型的全名代替简短标签。
- shortLabel: type.id === 'table' ? t({ en: 'table', es: 'tabla' })
- : t({ en: 'fig.', es: 'figura' }),
+ shortLabel: type.id === 'table' ? t({ en: 'Table', es: 'Tabla' })
+ : t({ en: 'Figure', es: 'Figura' }),#用段落符号给节编号
- section: t({ en: 'section {n}', es: 'apartado {n}' }), // @sec:losses → "section 2.2"
+ section: '§ {n}',常见问题
易错点
图在首次被引用处编号和定位
对图或表的第一次:ref或@fig:引用决定它的编号和位置,所以前面章节里的引用会把它拉到那里。向后引用时指向包含它的节,等图已经排出之后再直接引用图本身。 交叉引用 →
- 引用一个没有任何章定义的标识符会印出*?*。在某一章改了标题之后要检查标识符:引用它的地方在别的章里。
- 用
buildDocument逐章排版会丢掉计数器和全书大纲:每章的图都从1重新编号,引用别章会印出*?*。请用buildBundle,或者自己串联continuation并传入outline。 - Postext的公式没有自己的编号,所以
@eq:只能找到你设置的锚点并印出它的文字;本书的两行公式不编号。 - 开页的节标题,或者像第9页的3.3节那样排在页首表格之下的节标题,默认会去掉上方的全部空白,对齐网格所需的不足一行的空白于是落在标题下方,正文离它比页中的标题更远。
headings.columnHeadSpace: 'remainder'把这不足一行的空白留在标题上方(标题)。它适合单栏的书:旁边没有另一栏,看不出标题比页首略低。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- IBM Plex Serif (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1) · IBM Plex Mono (SIL OFL 1.1)


