# 付録を小さな文字の二段組にする

> 一段組の果樹栽培の手引きで、付録だけ組み方を変える。部が章スタイルを指定し、付録の一つは独自のスタイルを指定し、後書きは本のデザインに戻る。

- HTML版: https://postext.dev/ja/cookbook/appendices-in-two-columns
- レシピ No. 187 · 本の構成 · 難易度 2 (中級) · 出力: Canvas
- ジャンル: マニュアル・ガイド・リファレンス
- 必要なもの postext ≥ 1.79.0 · テスト環境 1.79.0 ／テスト日 2026-11-12
- ページ: [1](https://postext.dev/cookbook/appendices-in-two-columns/en/p01.webp?v=a5470155), [2](https://postext.dev/cookbook/appendices-in-two-columns/en/p02.webp?v=a5470155), [4](https://postext.dev/cookbook/appendices-in-two-columns/en/p04.webp?v=a5470155), [6](https://postext.dev/cookbook/appendices-in-two-columns/en/p06.webp?v=a5470155), [7](https://postext.dev/cookbook/appendices-in-two-columns/en/p07.webp?v=a5470155), [8](https://postext.dev/cookbook/appendices-in-two-columns/en/p08.webp?v=a5470155), [9](https://postext.dev/cookbook/appendices-in-two-columns/en/p09.webp?v=a5470155), [10](https://postext.dev/cookbook/appendices-in-two-columns/en/p10.webp?v=a5470155)
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=appendices-in-two-columns&lang=en (.postext: https://postext.dev/cookbook/appendices-in-two-columns/en/appendices-in-two-columns.postext)
- 最終更新: 2026-11-12
- 他の言語: [en](https://postext.dev/en/cookbook/appendices-in-two-columns.md), [es](https://postext.dev/es/cookbook/appendices-in-two-columns.md), [ca](https://postext.dev/ca/cookbook/appendices-in-two-columns.md), [de](https://postext.dev/de/cookbook/appendices-in-two-columns.md), [fr](https://postext.dev/fr/cookbook/appendices-in-two-columns.md), [it](https://postext.dev/it/cookbook/appendices-in-two-columns.md), [pt](https://postext.dev/pt/cookbook/appendices-in-two-columns.md), [zh](https://postext.dev/zh/cookbook/appendices-in-two-columns.md), [ar](https://postext.dev/ar/cookbook/appendices-in-two-columns.md)

## かんたんな説明

この本の章は広い一段組です。付録からは本文が小さな文字の二段組になり、付録の一つは三段組になります。ページの大きさと言語は最後まで変わりません。

## できあがり

寒い谷でリンゴを育てる人のための小さな手引きです。判型は150 × 220 mmで、六つのMarkdown文書で書き、一冊の本として組みます。第I部の二つの章は、Source Serif 4 の両端揃えの一段組です。第II部の付録では組み方が変わります。台木の表と月ごとの作業暦は、小さな文字のラグ組みの二段組です。作業小屋で作業台に本を開いて読む類いの内容だからです。品種の一覧はサンセリフの三段組です。後書きは部扉を入れずに本のデザインに戻ります。判型、余白、ハイフネーション、言語はどのページでも同じです。

**このレシピが答える問い:**

- 本の付録や一つの部だけを、小さな文字の二段組のような別のデザインで組むには？
- 本を部や節に分け、それぞれに専用の色と中扉を付けるには？

## 手短な答え

```js
// script.js, 行 29–48
const smallOpener = { minHeight: mm(24), slot: { elements: [{ id: 'title', fontSize: pt(16) }] } };
// In the Markdown:  :::part{number="II" title="Appendices" style="appendix"}  sets every
// chapter from there to the next part; a chapter's own  chapterStyle: reference  wins.
const chapterStyles = [
  { id: 'appendix', name: t({ en: 'Appendix', es: 'Apéndice' }), config: {
    layout: { layoutType: 'double', gutterWidth: mm(6) },
    bodyText: { fontSize: pt(8.8), lineHeight: pt(11.6), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(4) },
    // Lists merge entry by entry on their id or level: only what is named here changes.
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
  { id: 'reference', name: t({ en: 'Reference list', es: 'Lista de consulta' }), config: {
    layout: { layoutType: 'multiple', columnCount: 3, gutterWidth: mm(4.5) },
    bodyText: { fontFamily: SANS, fontSize: pt(7.8), lineHeight: pt(10.4), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(3.5), boldColor: col('accent') },
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
];
// The trim, the language and the fonts stay the book's: a style that sets page.width or
// locale is ignored there, with a chapterStyleBookSetting warning.
```

## 材料

**学べること**

- [章スタイル](https://postext.dev/ja/docs/configuration-styles.md#章スタイル): 名前つきの設定のまとまり（config.chapterStyles）です。章はフロントマターの chapterStyle: で、部のすべての章は :::part{style="…"} でそれを使います。段組み、余白、書体、見出し、柱は変えられ、判型や言語など本全体の設定は本のままです。
- [部扉](https://postext.dev/ja/docs/configuration-styles.md#partコンテナー): :::partは、番号、タイトル、任意の章一覧を持つデザインした部扉（とその裏のページ）を、それがまとめる章の前に置きます。

**ほかに使うもの**

- [章ごとに組む本](https://postext.dev/ja/docs/configuration-bundles.md#バンドルを組んで描画する)
- [1段組みと2段組み](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウトの種類)
- [3段以上の段組み](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウトの種類)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [見開きの余白](https://postext.dev/ja/docs/configuration-page-layout.md#見開きの余白)
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [ウィドウ、オーファン、ラント](https://postext.dev/ja/docs/configuration-page-flow.md#オーファンウィドウラント分割禁止の規則)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [段抜きの章見出し帯](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`chapterStyles`](https://postext.dev/ja/docs/configuration-styles.md#章スタイル), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル), [`parts`](https://postext.dev/ja/docs/configuration-styles.md#部)

**API**

- [`buildBundle`](https://postext.dev/ja/docs/configuration-bundles.md#バンドルを組んで描画する), [`prepareFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`withLoadedFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む)

**書体**

- Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)

## 作り方

### 1 · スタイルには変える部分だけを書く

コードは上の[手短な答え](https://postext.dev/ja/cookbook/appendices-in-two-columns.md#手短な答え)にあります。章スタイルは、id、Sandbox に表示する名前、`config` を持ちます。`config` は、言語ごとの層と同じように本の設定に重ねてマージされます。オブジェクトはキーごとに、リストは `id` か `level` で項目ごとにマージされます。そのため `smallOpener` は章頭の要素の一つである題だけを指して文字を小さくし、その下の罫やほかのすべては本の設定のまま残ります。付録のスタイルが決めるのは、二段組、小さめの本文サイズ、ラグ組み、項目間のアキだけです。

本全体に属する設定もあります。`page` の判型・解像度・製本、言語と書字方向、数字、フォント、印刷と PDF の出力です。スタイルでこれらを設定しても、その部分は無視され、`chapterStyleBookSetting` の警告が出ます。そのため付録も、章と同じ150 mmの判型とイギリス英語のハイフネーションのままです。

### 2 · 部がスタイルを指定する

```js
// script.js, 行 264–266
// Only the first document's front matter is the book's; a later one keeps its chapterStyle.
const chapters = [front, rootstocks, appendices, calendar, varieties, afterword]
  .map((markdown) => ({ markdown }));
```

三つ目の文書は `:::part{number="II" title="Appendices" style="appendix"}` で始まり、そこから次の部までの章はすべて付録のスタイルで組まれます。五つ目の文書は front matter で `chapterStyle: "reference"` と独自のスタイルを指定し、こちらが部のスタイルより優先されます。本では、最初の文書の front matter だけが本全体のものです。二つ目以降の文書では `chapterStyle:` の行だけが生きます。

![Opening page 9: Appendix C · Varieties for a short season.](https://postext.dev/cookbook/appendices-in-two-columns/en/p09.webp?v=a5470155)

*付録C。部の二段組に代わって、この章独自のスタイルであるサンセリフの三段組。*

### 3 · 部扉のある部と、ない部

```js
// script.js, 行 52–66
const text = (id, content, family, size, extra) => ({ kind: 'text', id, content, align: 'left',
  fontFamily: family, fontSize: pt(size), color: col('ink'), overflow: 'wrap', ...extra });
const at = (to, edge, x, y, width) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(width && { size: { width: mm(width), height: 'auto' } }) });
const parts = {
  breakBefore: { parity: 'any' }, // the book is short: a part opens on the next page
  design: { elements: [ // the container is the trim: the margins are measured from its edges
    { kind: 'box', id: 'band', style: { backgroundColor: col('leaf') },
      placement: { ...at('page', 'top-left', 0, 0), size: { width: 'fill', height: mm(96) } } },
    text('number', '{number}', SERIF, 40, { fontWeight: 600, color: col('paper'),
      placement: at('page', 'top-left', MARGIN.inner, 46, MEASURE) }),
    text('title', '{titleText}', SERIF, 24, { fontWeight: 600, color: col('paper'),
      placement: at('#number', 'below', 0, 2, MEASURE) }),
  ] },
};
```

`:::part` はそれぞれ部扉を開き、部の番号と題を緑の帯に置きます。後書きは `:::part{title="Afterword" page=false}` で始まります。部扉は刷られず、この部はスタイルを指定していないので、その章はまた本の設定で組まれます。`page=false` の部は、付録のあとに続けて置く後付に向いています。

![Part title page 6: II Appendices.](https://postext.dev/cookbook/appendices-in-two-columns/en/p06.webp?v=a5470155)

*第II部の部扉。*

### 4 · 一つの章頭を二つの大きさで

```js
// script.js, 行 70–75
const opener = { enabled: true, minHeight: mm(40), slot: { elements: [
  text('title', '{titleText}', SERIF, 22, { fontWeight: 600, lineHeight: 1.12,
    placement: at('container', 'top-left', 0, 8, MEASURE - 10) }),
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.5), color: col('accent'),
    placement: { ...at('#title', 'below', 0, 4), size: { width: mm(14) } } },
] } };
```

章頭はページの幅いっぱいに広がるので、付録では二つの段の上をまたぎ、本文はその下から二段で始まります。付録と参照用のスタイルは、要素の id を通じて題を16 ptに、章頭下げを24 mmに縮めます。本の後ろのほうの内容は場所を取らず、題は本文よりはっきり大きいままです。

### 5 · 柱は本の設定から

```js
// script.js, 行 79–91
const head = (id, content, parity, edge, x, extra = {}) => text(id, content, SANS, 7.5, {
  parity, pages: 'body', fontWeight: 600, letterSpacing: pt(1.2), textTransform: 'uppercase',
  color: col('muted'), overflow: 'clip', placement: at('page', edge, x, 12, 90), ...extra });
const folio = { fontWeight: 700, color: col('ink') };
const right = { align: 'right' };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', MARGIN.outer, folio),
  head('verso-title', '{title}', 'even', 'top-left', MARGIN.outer + 9), // the book's title
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(MARGIN.outer + 9), right),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -MARGIN.outer, { ...folio, ...right }),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'bottom', 0, {
  ...folio, align: 'center', pages: 'opener', placement: at('page', 'bottom', 0, -14, 20) })] };
```

左ページの柱に書名、右ページの柱に章名が入ります。どのスタイルも柱を変えないので、本のどの部でも柱は同じです。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: https://github.com/drnachio/postext/tree/main/cookbook/appendices-in-two-columns

### script.js

```js
// ═══ Postext Cookbook · Nº 187 · Appendices in two columns ═══════════════════════════════
// https://postext.dev/en/cookbook/appendices-in-two-columns
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.79.0
// A growers' handbook in six Markdown documents: the chapters in one column, the appendices
// in two columns of smaller type, one appendix in three, and an afterword back in one.
import {
  buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'appendices-in-two-columns';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: russet for the accent, leaf green for the part pages
const palette = { ink: '#211f1b', accent: '#8e3b24', leaf: '#46603a', muted: '#6c665c',
  rule: '#cfc6b6', paper: '#fffdf8' };
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, SANS] = ['Source Serif 4', 'Source Sans 3'];
const TRIM = { width: 150, height: 220 }; // mm, a handbook for the shed shelf
const MARGIN = { top: 22, bottom: 24, inner: 19, outer: 15 }; // mirrored
const MEASURE = TRIM.width - MARGIN.inner - MARGIN.outer; // 116 mm
const LEAD = 14; // pt, the book's leading

// #region answer: two chapter styles; a part names one, a chapter names the other
const smallOpener = { minHeight: mm(24), slot: { elements: [{ id: 'title', fontSize: pt(16) }] } };
// In the Markdown:  :::part{number="II" title="Appendices" style="appendix"}  sets every
// chapter from there to the next part; a chapter's own  chapterStyle: reference  wins.
const chapterStyles = [
  { id: 'appendix', name: t({ en: 'Appendix', es: 'Apéndice' }), config: {
    layout: { layoutType: 'double', gutterWidth: mm(6) },
    bodyText: { fontSize: pt(8.8), lineHeight: pt(11.6), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(4) },
    // Lists merge entry by entry on their id or level: only what is named here changes.
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
  { id: 'reference', name: t({ en: 'Reference list', es: 'Lista de consulta' }), config: {
    layout: { layoutType: 'multiple', columnCount: 3, gutterWidth: mm(4.5) },
    bodyText: { fontFamily: SANS, fontSize: pt(7.8), lineHeight: pt(10.4), textAlign: 'left',
      firstLineIndent: pt(0), paragraphSpacing: pt(3.5), boldColor: col('accent') },
    headings: { levels: [{ level: 1, advancedDesign: smallOpener }] },
  } },
];
// The trim, the language and the fonts stay the book's: a style that sets page.width or
// locale is ignored there, with a chapterStyleBookSetting warning.
// #endregion

// #region parts: a divider page for each :::part, none where the fence says page=false
const text = (id, content, family, size, extra) => ({ kind: 'text', id, content, align: 'left',
  fontFamily: family, fontSize: pt(size), color: col('ink'), overflow: 'wrap', ...extra });
const at = (to, edge, x, y, width) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(width && { size: { width: mm(width), height: 'auto' } }) });
const parts = {
  breakBefore: { parity: 'any' }, // the book is short: a part opens on the next page
  design: { elements: [ // the container is the trim: the margins are measured from its edges
    { kind: 'box', id: 'band', style: { backgroundColor: col('leaf') },
      placement: { ...at('page', 'top-left', 0, 0), size: { width: 'fill', height: mm(96) } } },
    text('number', '{number}', SERIF, 40, { fontWeight: 600, color: col('paper'),
      placement: at('page', 'top-left', MARGIN.inner, 46, MEASURE) }),
    text('title', '{titleText}', SERIF, 24, { fontWeight: 600, color: col('paper'),
      placement: at('#number', 'below', 0, 2, MEASURE) }),
  ] },
};
// #endregion

// #region opener: the chapter title and a short rule, the text sunk under them
const opener = { enabled: true, minHeight: mm(40), slot: { elements: [
  text('title', '{titleText}', SERIF, 22, { fontWeight: 600, lineHeight: 1.12,
    placement: at('container', 'top-left', 0, 8, MEASURE - 10) }),
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1.5), color: col('accent'),
    placement: { ...at('#title', 'below', 0, 4), size: { width: mm(14) } } },
] } };
// #endregion

// #region running-heads: the book on the verso, the chapter on the recto, folios outside
const head = (id, content, parity, edge, x, extra = {}) => text(id, content, SANS, 7.5, {
  parity, pages: 'body', fontWeight: 600, letterSpacing: pt(1.2), textTransform: 'uppercase',
  color: col('muted'), overflow: 'clip', placement: at('page', edge, x, 12, 90), ...extra });
const folio = { fontWeight: 700, color: col('ink') };
const right = { align: 'right' };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', MARGIN.outer, folio),
  head('verso-title', '{title}', 'even', 'top-left', MARGIN.outer + 9), // the book's title
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(MARGIN.outer + 9), right),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -MARGIN.outer, { ...folio, ...right }),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'bottom', 0, {
  ...folio, align: 'center', pages: 'opener', placement: at('page', 'bottom', 0, -14, 20) })] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }), colorPalette, chapterStyles, parts, header, footer,
  page: { sizePreset: 'custom', width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150,
    backgroundColor: col('paper'), margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom),
      left: mm(MARGIN.inner), right: mm(MARGIN.outer), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: SERIF, fontSize: pt(10.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4.5), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: SANS, color: col('accent'), fontWeight: 600, levels: [
    // span 'page': in the appendices' columns the opener still runs across the page.
    { level: 1, breakBefore: { enabled: true, parity: 'any' }, span: 'page',
      advancedDesign: opener },
    { level: 2, fontSize: pt(11), lineHeight: pt(LEAD), marginTop: pt(LEAD),
      marginBottom: pt(0) },
  ] },
  paragraphStyles: [{ id: 'colophon', fontFamily: SANS, fontSize: pt(7.5), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const front = String.raw`---
title: "Apples for a Cold Valley"
author: "Elena Arrieta"
---

:::part{number="I" title="The orchard"}
:::

# Choosing the ground

An apple tree planted today will still be bearing when the person who planted it has stopped climbing ladders. The choice of ground is the one decision that cannot be put right later, and in a valley where the frost comes in September and stays until May it decides more than the choice of variety does.

## Cold air runs downhill

On a still night the air that cools against the ground grows heavy and slides down the slope, the way water would, and pools wherever the land stops falling: in the valley floor, behind a hedge, against a wall at the bottom of a field. Two trees a hundred metres apart can see five degrees of difference on a May morning, and five degrees is the gap between a crop and a tree in flower that sets nothing.

Plant on the slope, never in the hollow below it. A third of the way up is usually the warmest band, above the frost pocket and below the wind. If the orchard has to sit low, leave a gap in the bottom hedge so the cold air can drain away instead of backing up into the trees.

## Facing the sun

A slope that faces south or south-west warms first in spring and ripens the wood in autumn, and ripe wood is what carries a tree through a hard winter. A north slope delays blossom by a week or more, which can save it from a late frost, but the fruit may not colour before the first snow. In this valley the south-west slopes above the river have always carried the old orchards, and the farmhouses below them sit just above the line where the fog settles.

## Soil and water

Apples want deep soil that drains. A tree will put up with poor ground, but it will not put up with its roots standing in water through the winter: the roots die back, the bark at the collar rots, and the tree goes yellow the following summer for no reason anyone can see. Dig a hole sixty centimetres deep in March and fill it with water. If the water is still there the next day, the ground needs draining or the tree needs a mound to stand on.

Heavy clay holds water and cold; it also holds nutrients, and an apple on clay crops for a long time once it is established. Light sand warms early and drains well but dries out in August, when the fruit is swelling. Most valley soils sit somewhere between the two, and the rootstock, the subject of the next chapter, does more to match a tree to its soil than any amount of digging.
`; // the book's front matter, Part I and the first chapter
const rootstocks = String.raw`# Rootstocks and spacing

An apple does not come true from seed. Every named variety is grafted: a bud or a shoot of the variety is joined to the roots of another apple, and those roots decide how large the tree will grow, how soon it will crop and how well it stands cold, wet or drought. The variety decides the fruit. The rootstock decides almost everything else.

## Small trees, early fruit

Most rootstocks in use today come from the research station at East Malling, in Kent, and carry its initial: M9, M26, MM106. The lower the vigour, the sooner the tree bears and the smaller it stays. A tree on M9 may give a few apples in its second summer and will stand about two and a half metres tall, small enough to prune and pick from the ground. It pays for that with a weak root system: it needs a stake for the whole of its life and good soil to grow in.

## Large trees, long lives

A tree on a vigorous rootstock such as MM111 or M25 takes five or six years to crop and grows into a tree that needs a ladder, but it roots deep, finds water in a dry summer and will stand in grass without help. These are the trees of the old orchards on the slopes, some of them older than the farmhouses. Where sheep graze under the branches, or where nobody will water a young tree in August, a vigorous stock is the safer choice.

## The cold

Hardiness belongs to the rootstock as much as to the variety. The Malling stocks were raised for English winters, and in a valley that drops below minus twenty-five some of them suffer. The Budagovsky stocks, bred in central Russia, were raised for that cold: Bud 9 makes a tree the size of one on M9 and comes through winters that kill M9 roots. Seedlings of Antonovka, an old Russian apple, give a full-sized tree that is hardier still.

## How far apart

Spacing follows from the rootstock. Trees on M9 can stand a metre and a half apart in rows three and a half metres wide; on MM106, four metres apart; on M25, eight or more. The appendices give the figures for each stock and the work of each month, set close so that they can be read in the shed with the book open on the bench.
`;
const appendices = String.raw`:::part{number="II" title="Appendices" style="appendix"}
:::

# Appendix A · Rootstocks at a glance

Heights are those of a mature tree on average soil, kept by ordinary pruning. Spacing is between trees in the row; rows need at least a metre more than the height of the trees.

**M27.** The most dwarfing of the common stocks. A tree of a metre and a half to two metres, often in fruit in its second year. It needs a stake for life, rich soil and regular watering. Suited to pots and to a few trees in a garden, not to an orchard on poor ground. Spacing: one metre.

**M9.** Dwarfing, two to three metres. The stock of most modern orchards: early and heavy cropping, fruit of good size. Brittle roots that need a stake for life; sensitive to drought, woolly aphid and fireblight. Its roots can be killed in the hardest winters. Spacing: one and a half metres.

**Bud 9.** Raised at Michurinsk, in Russia. A tree of the size of one on M9 that stands much harder winters. Needs a stake and good soil, like M9. Spacing: one and a half metres.

**M26.** Semi-dwarfing, about three metres. Hardier than M9 and more anchored, though it needs a stake while young. Does badly in wet soil, where the collar rots. Spacing: two and a half metres.

**MM106.** Semi-vigorous, three and a half to four and a half metres. Resists woolly aphid, crops in its third or fourth year and stands on its own after the first years. Prone to collar rot on wet clay, and it grows late into autumn, which leaves the wood soft when the first hard frost arrives. Spacing: four metres.

**MM111.** Vigorous, four and a half to five and a half metres. Deep roots that tolerate drought and light soils; resists woolly aphid. Slow to crop but long-lived. Spacing: five metres.

**M25.** Very vigorous, six metres and more: a full standard tree for a grazed orchard. Crops after five or six years and lives for generations. Spacing: eight metres.

**Antonovka seedling.** Full size and the hardiest of all, grown from the seed of the Russian apple. Trees vary, as seedlings do. Spacing: eight metres.
`; // opens Part II in the 'appendix' style
const calendar = String.raw`# Appendix B · The orchard year

The months are those of this valley, where the last frost can come in late May and the first in late September. Higher up, everything moves a week or two later.

**January.** Prune on days when the wood is not frozen, starting with the oldest trees. Check the guards round young trunks: voles work under snow, and hares strip bark when the ground is white.

**February.** Finish the winter pruning of standards. Take scion wood for grafting from last summer's shoots, label it and keep it wrapped and cool until April.

**March.** Plant bare-root trees as soon as the soil can be worked and is not sticky. Stake trees on dwarfing stocks the day they go in.

**April.** Graft when the buds of the rootstock begin to open. Keep a thermometer in the lowest part of the orchard and watch the forecast: open blossom is killed at about minus two.

**May.** Blossom, a week later on the north slopes. Leave the grass long under the trees until the bees have finished. On a clear, still night after a cold day, expect frost before dawn.

**June.** After the natural drop at the end of the month, thin the fruit to one per cluster, and to one every fifteen centimetres on young trees.

**July.** Water young trees in dry spells, a full bucket each, once a week.

**August.** Summer-prune cordons and espaliers once the new shoots are woody at the base. Pick the early varieties when they part from the spur with a lift and a twist.

**September.** The main picking begins. Handle the fruit as you would eggs, and store only sound apples, in a cool, dark, airy place.

**October.** Finish picking before the hard frosts. Rake up fallen leaves where scab was bad: the fungus spends the winter in them.

**November.** Plant and move trees while the soil is still warm. Paint the trunks of young trees white against the winter sun, which warms the bark by day and lets it crack at night.

**December.** Go through the store once a week and take out anything that has started to rot.
`;
const varieties = String.raw`---
chapterStyle: "reference"
---

# Appendix C · Varieties for a short season

Varieties that ripen before the first hard frost and stand a valley winter, in order of picking.

**Yellow Transparent.** From the Baltic; reached America in 1870. Pale, soft, picked in early August. Will not keep: for sauce within the week.

**Duchess of Oldenburg.** Russian, known since the eighteenth century. Striped, sharp, picked in August. A cooking apple from a very hardy tree.

**Antonovka.** Russian and very old. Large, green, sour and scented. Cooks to a froth; keeps until Christmas. The hardiest tree on this list.

**Wealthy.** Raised from seed in Minnesota by Peter Gideon in the 1860s. Red, crisp, for eating in September.

**Lobo.** A McIntosh seedling released at Ottawa in 1930. Dark red, soft, sweet. Picked in mid-September.

**McIntosh.** Found as a seedling in Ontario in 1811. Scented, white-fleshed, tender. Hardy, but scab spots the fruit in wet summers.

**Fameuse.** Also called Snow, for its white flesh. Grown in Quebec since the eighteenth century. Probably a parent of McIntosh.

**Liberty.** From the Geneva station in New York, 1978. Bred to resist scab: the tree for an orchard that is never sprayed.

**Honeycrisp.** Minnesota, released in 1991. Very crisp and juicy; keeps for months. Cracks and spots on some soils.

**Haralson.** Minnesota, 1922. Tart, firm, for cooking and eating. One of the hardiest trees that carry a good keeper.

**Belle de Boskoop.** Dutch, from 1856. Russeted, sharp, large. Keeps until March. A triploid: plant two other varieties to pollinate it, and do not use its pollen for them.

**Northern Spy.** New York, about 1800. Slow to start cropping, then excellent. Firm, aromatic, the best keeper on the list.
`; // chapterStyle: reference, in its front matter
const afterword = String.raw`:::part{title="Afterword" page=false}
:::

# The valley in March

The snow goes from the south slopes first, and for a week or two the orchards above the river stand on bare brown ground while the valley floor is still white. That is the time to walk the rows with a pair of secateurs and a notebook, before the buds break.

Most of the trees in this valley were planted by people who never ate from them at their best. The old standards on M25 and on seedling roots took ten years to crop well and then cropped for sixty. The small trees on M9 that now stand in rows below them will be in full bearing by their fifth summer and finished by their twenty-fifth. Neither is the right choice for every grower. A family that wants apples soon and has a small plot will plant dwarf trees and replant them; a farm that grazes sheep and thinks in generations will plant standards and leave them to the next owner.

What matters in either case is the ground under the tree and the air around it. A tree on the right slope, in soil that drains, on a rootstock that suits the place, will forgive a great deal of bad pruning.

:::paragraphs{style="colophon"}
Set in Source Serif 4 and Source Sans 3. Text: original, CC BY 4.0.
:::
`; // a part with page=false and no style
// #region chapters: six documents in reading order; each part's style runs to the next part
// Only the first document's front matter is the book's; a later one keeps its chapterStyle.
const chapters = [front, rootstocks, appendices, calendar, varieties, afterword]
  .map((markdown) => ({ markdown }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Source Serif 4': ['400', '400i', '600'], 'Source Sans 3': ['300', '400', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const all = chapters.map((chapter) => chapter.markdown).join('\n');
await prepareFonts(all, config, kitFonts(FONTS));
const docs = await withLoadedFonts(() => buildBundle({ chapters, config }),
  { ...kitFonts(FONTS), text: all });
const TITLE = t({ en: 'Apples for a Cold Valley', es: 'Manzanos para un valle frío' });
showPages(docs, { title: TITLE });

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## アレンジ

### 本全体の設定をスタイルで変えようとする

判型や言語を設定したスタイルは、そのキーについては無視されます。キーごとに `chapterStyleBookSetting` の警告が出て、付録は本の判型のままです。

```diff
   { id: 'appendix', name: t({ en: 'Appendix', es: 'Apéndice' }), config: {
+    page: { width: mm(170) }, locale: 'fr',
     layout: { layoutType: 'double', gutterWidth: mm(6) },
```

### デザインを別の本で使う

コマンドラインツールは、本のデザインを章スタイルも含めてデザインファイルに書き出し、`--design` で別の本をそのデザインで組みます。[design コマンド](https://postext.dev/ja/docs/command-line.md#design)を参照してください。

```bash
postext design apples.postext -o handbook.postext
postext pdf pears/ --design handbook.postext -o pears.pdf
```

## よくあるつまずき

- `:::part` の行は章の冒頭、見出しの前に置きます。章の本文が始まったあとに部の行を置くと `partStyleMidChapter` が出て、スタイルは次の章から始まります。
- `chapterStyles` にないスタイル名を書くと `chapterStyleUnknown` が出て、その章は本の設定で組まれます。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 書体: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 019 · ひとつの属性で部ごとに色を変える](https://postext.dev/ja/cookbook/parts-in-colour.md): ポケット判の野外図鑑。:::partごとにパレットの1項目を設定し、部扉、色を敷いた偶数ページ、つめ見出し、識別点、目次の行をその色で刷ります。 · 難易度 3 (上級) · マニュアル・ガイド・リファレンス
- [No. 007 · 章ごとのファイルから1冊の本を組む](https://postext.dev/ja/cookbook/book-from-chapters.md): buildBundleで5つのMarkdownファイルを1冊の本として組みます。各章は奇数ページから始まり、ページ番号、章番号、図番号はファイルをまたいで続きます。 · 難易度 3 (上級) · マニュアル・ガイド・リファレンス
- [No. 031 · 学位論文の後付け：付録、用語集、索引](https://postext.dev/ja/cookbook/thesis-back-matter.md): 白黒で組む学位論文の最後のページ。文字番号の付録、2段組みの用語集、APA式の文献一覧、本文中の印から作る索引。 · 難易度 3 (上級) · 論文・学術書
