かんたんな説明
山小屋のための太陽光パネルと蓄電池の容量を見積もる、短い手引きです。第3章が第1章の表を振り返るときも、第1章が第2章の節を先取りするときも、正しい番号とページが印字され、リンクになります。
できあがり
短い技術的な手引き『Power for a Cabin』を、178 × 233 mmのページにIBM Plexで組みます。太陽の軌道をコードで描いた表紙、目次のページ、夜空の青の帯の下に3つの章があります。この本は小さな太陽光発電システムの容量を見積もるもので、どの章もほかの章に寄りかかっています。第3章は第1章の負荷の表と第2章の日照時間のグラフを引き、第1章は読者を先の2.3節へ送り、そのページを示します。著者は4つの別々のMarkdownファイルに、pandoc-crossrefが読むとおりに@tbl:loadsや@sec:array-sizeと書きます。buildBundleがそれらを1冊の本として組むので、どの参照も、参照先がその章で得た番号、参照先が置かれたページ、参照先へのリンクを印字します。
このレシピが答える質問
- 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' } }) }));
材料
作り方
#1 · 参照先には本全体で一度だけ名前をつける
コードは上の手短な答えにあります。見出しには## Sizing the array {#sec:array-size}のように、接頭辞つきのPandoc識別子をつけます。図と表はスクリプトで宣言するリソースで、そのidもfig:sun、tbl:loadsと同じ形で書きます。こうすれば、図が2段落先にあっても2章前にあっても、本文には@fig:sunと書けます。idは章の中だけでなく、本全体で一意でなければなりません。
#2 · 章を1冊の本としてレイアウトする
// 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と印字します。自分の持たない見出しを本文で参照する章は、本全体のアウトラインを使って組み、そのアウトラインのページが動かなくなるまで(最大3回)組み直します。第2章がまだ紙の上に存在しないうちに、第1章が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:参照が番号と位置を決めるため、前の章で参照すると図はそこに引き寄せられます。先にあるものは図を含む節で参照し、図そのものを参照するのは配置されてからにしてください。 相互参照 →
- どの章も設定していないidへの参照は「?」と印字されます。ある章で見出しの名前を変えたら、idを確かめてください。その見出しへの参照はほかの章にあります。
buildDocumentで章を1つずつ組むと、カウンターも本のアウトラインも失われます。どの章も図の番号を1から振り直し、ほかの章への参照は「?」と印字されます。buildBundleを使うか、continuationをつないで自分でoutlineを渡してください。- Postextの数式には専用の番号づけがないので、
@eq:が見つけるのは自分で設定したアンカーだけで、そのテキストを印字します。この本では2つの数式を番号なしで書いています。 - ページの頭に来る節見出しや、9ページの3.3節のようにページの頭の表の下に来る節見出しは、既定では上のアキをすべて失います。グリッドにそろえるための1行未満のアキは見出しの下に入るので、本文はページ途中の見出しより離れます。
headings.columnHeadSpace: 'remainder'を指定すると、その1行未満のアキが見出しの上に残ります(見出し)。1段組みの本に向いています。見出しが少し下から始まっても、隣に比べる段の頭がないからです。
クレジット
- 本文
- 書き下ろしの文章, 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)


