本文へスキップ
レシピ番号48

レシピ集 · 第6章 · 囲みと注

コードリストとキーキャップ

シェルの入門書。フェンス付きコードを字句ごとに色分けした濃色のリストの囲みに組み、キーをキーキャップのチップにします。

50〜51ページ · 2〜3/3

  • 英語の見本:日本語版はまだありません
  • 仕上がり178 × 229 mm
  • 1段半組み, 段間6 mm
  • Charis SIL 10/14.5
  • JetBrains Mono
  • Sora
  • 3ページ
  • レベル
  • Postext 1.57.1
  • 組版時間89 ms
  • コード147行

かんたんな説明

コマンドライン入門書の3ページ。コードの例を濃い色の箱に組み、Ctrlのようなキーを文中の小さなボタンとして描く方法を示します。

できあがり

『The Shell, Gently』という架空のコマンドライン小型入門書から、第4章の3ページを178 × 229 mmの判型で組みます。本文はCharis SILの両端そろえで、100 mmの段に組みます。小口側には傍注用の余白段を設けます。コードリストはどれもJetBrains Monoを組んだ黒に近い囲みで、この余白段まで張り出し、ファイル名かセッション名を記したタブを上に付けます。キーワードと入力コマンドは琥珀色、文字列は緑、コメントはグレーで印刷されます。CtrlやTabなどのキーは両端そろえの行の中に輪郭線付きの小さなキーキャップとして入り、50ページの下端はCtrlショートカットの2段組みチートシートが占めます。Markdownには普通のフェンス付きコードブロックを残し、エンジンがそれをそのまま組みます。

このレシピが答える質問

  • コードリストを表示するには?
  • キーボードのキー、タグ、練習問題の語群などのインラインのチップを作るには?
  • 会話のダッシュ、段落頭の年号、価格、記号そのものを、Markdownに誤読させずに書くには?

手短な答え

script.js · 26〜41行コード全体で見る
// A ``` fence is a listing set line by line as written: indents, blank lines and the output
// columns of a session are kept. The rest of the fence line (Terminal, backup.sh) is its
// title; with a label set, it goes on the tab.
// The text after a listing goes in :::paragraphs{style="resume"}: flush, as after a heading.
const resume = { id: 'resume', firstLineIndent: ZERO };
const codeStyle = {
  fontFamily: MONO, fontSize: pt(8.6), lineHeight: pt(12.4), color: col('code'),
  background: col('night'), span: 'page', // across the text and the margin
  padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
  marginTop: mm(6), marginBottom: mm(2.5),
  label: { fontFamily: MONO, fontSize: pt(7), fontWeight: 700, color: col('phosphor'),
    background: col('night'), height: mm(5), offset: mm(5), paddingX: mm(3), // the tab
    position: 'top-left' },
  tokens: tokens(), // the colours, below
  inline: { fontSize: em(0.88) }, // `grep` in running text: the code face, no box
};

材料

併用する機能
数式
種類
Charis SIL, Sora, JetBrains Mono (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · フェンスを囲みに組む

この手順のコードは上の手短な答えにあります。Markdownの```フェンスはどれもコードブロックです。Postextはその行を書いたとおりに、コードの1行を組版の1行として組み、インデントも、スクリプトの空行も、duの2段の出力も保ちます。codeStyleはすべてのコードリストの体裁をまとめて決めます(コードリスト)。書体とその行送り、黒に近い塗り、パディング、上下のアキです。フェンス行で言語名の後に書いたもの(Terminal、backup.sh)はコードリストのタイトルです。codeStyle.labelを設定しているので、タイトルはタイトル行ではなく囲みの上辺のラベルタブに印刷されます。codeStyle.inlineは、本文中のインラインコード(lsやgrep -c)を同じ書体の0.88 emで組みます(インラインコード)。リストの後の段落は:::paragraphs{style="resume"}に入れるので、見出しの後と同じく字下げなしで始まります。

#2 · 本文は狭く、コードは余白まで

script.js · 124〜127行コード全体で見る
  page: { sizePreset: 'custom', width: mm(178), height: mm(229), margins: {
    top: mm(22), bottom: mm(21), left: mm(20), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'oneAndHalf', sideColumnPercent: 26, gutterWidth: mm(6),
    sideColumnRole: 'floats', sideColumnSide: 'outer' },

10 ptのCharis SILは、100 mmの段に約62字入ります。この1段半組みのサイド段はフロートと傍注だけを受け持つので、本文がそこへ流れ込むことはありません。codeStyleのspan: 'page'は、すべてのリストを両方の段にまたがる143 mmに広げます。内側余白の内側には8.6 ptのJetBrains Monoが73字入ります。これらのページで最も長い行、backup.shの冒頭のコメントは71字です。

#3 · 字句ごとにコードに色を付ける

script.js · 45〜54行コード全体で見る
function tokens() {
  const plain = { color: col('code') }; // every other kind in the listing's own colour
  return {
    keyword: { color: col('amber'), bold: true }, function: { color: col('amber'), bold: true },
    string: { color: col('phosphor'), italic: true },
    comment: { color: col('slate'), italic: false }, // upright: the default comment is italic
    prompt: { color: col('amber'), bold: true }, output: plain, // what you type, the answer
    number: plain, type: plain, variable: plain, meta: plain, operator: plain, punctuation: plain,
  };
}

フェンスの言語(console、bash)が組み込みの字句解析器を選び、codeStyle.tokensが字句の種類ごとに色、太さ、傾きを与えます(構文の色分け)。backup.shでは、forやdoneなどのキーワードとsetやechoなどの組み込みコマンドが琥珀色の太字、文字列が緑のイタリック、コメントがグレーで印刷されます。mkdirやrsyncのようなプログラムは装飾しません。既定のスタイルはコメントをイタリックにするので、italic: falseで正体に戻します。consoleフェンスでは、プロンプトで始まる行がpromptの字句、それ以外の行がoutputの字句になります。そのため入力するコマンドは琥珀色の太字で印刷され、シェルの応答はリストの明るいグレーのままです。このレシピで色を付けない種類(数値、変数、オプションなど)も、同じグレーにします。

#4 · キーをチップにする

script.js · 58〜65行コード全体で見る
// Chips never break or stretch, so a line with keys puts all its slack in its word spaces;
// the breaker tries other breaks before a space passes 140 % (default 200 %).
const spacing = { maxWordSpacing: 1.4 }; // spread into bodyText
const chipStyles = [
  { id: 'key', fontFamily: MONO, fontSize: pt(7.8), bold: true, color: col('ink'),
    background: col('code'), borderColor: col('slate'), borderWidth: pt(0.6),
    borderRadius: pt(1.6), paddingX: em(0.45), paddingY: em(0.14), gap: em(0.3) },
];

キーはkeyチップで、淡い塗りと0.6 ptの輪郭線が付きます。大きさをポイントで指定しているので、キーは10 ptの本文でも、8.6 ptの傍注でも、8.4 ptのチートシートでも7.8 ptになります。em(0.78)で指定すると、チートシートのキーは6.6 ptに縮みます。チップは行をまたいで分割されず、伸縮もしません(インラインのチップ)。そのためキーを含む行では、余りがすべて語間に回ります。spacingを指定すると、改行処理はスペースが通常幅の140 %を超えて広がる前に別の改行位置を試します。既定の200 %では、これらのページの6行がそれ以上に広がります。この設定を入れると、最も広い行でも132 %に収まります。

#5 · 手順の番号をグリッドに乗せる

script.js · 91〜94行コード全体で見る
const orderedLists = { fontFamily: DISPLAY, fontWeight: 800, color: col('ember'),
  gap: em(0.7), separator: '›', separatorGap: em(0.25), separatorFontFamily: MONO,
  separatorFontWeight: 700, separatorColor: col('muted'),
  marginTop: ZERO, marginBottom: ZERO }; // the default 1.5 em opens 5.3 mm above and below

番号はアクセント色のSora 800、区切りはグレーの等幅の›です。区切りは独自の書体と色が指定されているので、別のランとして描かれます(番号付きリスト)。リストの余白はゼロなので、手順は周囲の本文と同じ14.5 ptのグリッドに乗り続けます。既定の1.5 emでは手順の上に5.3 mmの空きができ、チートシートが51ページへ押し出されます。

#6 · チートシートをページの下端にフロートさせる

script.js · 69〜76行コード全体で見る
const sheet = { id: 'sheet', background: col('night'), span: 'page', placement: 'bottom',
  marginTop: mm(6), marginBottom: mm(2.5),
  columnGap: mm(8), padding: { top: mm(5), right: mm(6), bottom: mm(5.5), left: mm(6) },
  titleStyle: { fontFamily: MONO, fontSize: pt(7.5), fontWeight: 700, gap: mm(3.5),
    color: col('phosphor'), textTransform: 'uppercase', letterSpacing: pt(1.5) },
  body: { fontFamily: DISPLAY, fontSize: pt(8.4), lineHeight: pt(13), textAlign: 'left',
    color: col('code'), boldColor: col('amber'), italicColor: col('phosphor'),
    paragraphSpacing: false, firstLineIndent: ZERO } };

チートシートはリストと同じ塗りの囲みスタイルで、動作の説明にはSoraを使います。placement: 'bottom'で、50ページの下端にフロートします(フロートする囲み)。流れの中に置いたままだと、ページ幅の囲みは自身の高さに加えて、その下に本文2行分の余地を必要とします。ここでは囲みが51ページに移り、手順の下に58 mmの空白が残り、章は4ページに延びてしまいます。Markdownでは、:::columns{count=2 breaks="8"}が8番目のブロック、つまり見出しから右の段を始めます。段末そろえだけでは高さで切るので、ある動作の説明が2行目に回ると、見出し「Commands and history」が左の段の下端に取り残されます。どの項目も同じ2つのチップ、Ctrlと英字で始まり、どちらも等幅書体なので、各動作の説明は段の左端から同じ距離で始まります。

レシピの全体

Sandbox
// ═══ Postext Cookbook · Nº 048 · Code listings and keycaps ═══
// https://postext.dev/en/cookbook/code-listings-and-keycaps
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Charis SIL, Sora, JetBrains Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, prepareFonts, withLoadedFonts, renderPageToCanvas,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'code-listings-and-keycaps';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#1b1f24', muted: '#5c636b', ember: '#9a5410', // text, heads, accent
  night: '#0e1116', code: '#d3d9df', amber: '#f2b134', phosphor: '#3ddc84', // the listings
  slate: '#8a939d' }; // comments in a listing, the outline of a key (code is its face)
// Every colour is linked to its palette entry by id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the accent, so nothing prints blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.ember })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, MONO] = ['Charis SIL', 'Sora', 'JetBrains Mono'];
const LEAD = 14.5; // pt: the body leading, the page's baseline grid
const ZERO = pt(0);

// #region answer: a fence is a code listing; codeStyle gives it a dark box
// A ``` fence is a listing set line by line as written: indents, blank lines and the output
// columns of a session are kept. The rest of the fence line (Terminal, backup.sh) is its
// title; with a label set, it goes on the tab.
// The text after a listing goes in :::paragraphs{style="resume"}: flush, as after a heading.
const resume = { id: 'resume', firstLineIndent: ZERO };
const codeStyle = {
  fontFamily: MONO, fontSize: pt(8.6), lineHeight: pt(12.4), color: col('code'),
  background: col('night'), span: 'page', // across the text and the margin
  padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
  marginTop: mm(6), marginBottom: mm(2.5),
  label: { fontFamily: MONO, fontSize: pt(7), fontWeight: 700, color: col('phosphor'),
    background: col('night'), height: mm(5), offset: mm(5), paddingX: mm(3), // the tab
    position: 'top-left' },
  tokens: tokens(), // the colours, below
  inline: { fontSize: em(0.88) }, // `grep` in running text: the code face, no box
};
// #endregion

// #region paint: keywords amber, strings green, comments slate; a session's typed lines amber
function tokens() {
  const plain = { color: col('code') }; // every other kind in the listing's own colour
  return {
    keyword: { color: col('amber'), bold: true }, function: { color: col('amber'), bold: true },

組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)

アレンジ

#タブを右に掛ける

タブは囲みの右上の角に移ります。奇数ページでは、そこが余白段の上に当たります。

-    position: 'top-left' },
+    position: 'top-right' },

#行に番号を付ける

どのリストにも、囲みの内側に設けた欄にグレーの行番号が付きます。この欄は73字のうち約4字分を取るので、backup.shの冒頭のコメントは収まらなくなります。backupの後で折り返し、disk.が次の行の»の後に続きます。Cookbookの検査はこれをcodeOverflow警告として報告します。スクリプトを13行のままにするには、コメントを短くします。1つのリストだけに番号を付けるには、そのコードブロックの開始行に{lineNumbers}と書きます。

+  lineNumbers: true, lineNumberColor: col('slate'),
   tokens: tokens(), // the colours, below

#コメントを文字列と同じ色にする

コメントが文字列と同じ緑のイタリックになります。

-    comment: { color: col('slate'), italic: false }, // upright: the default comment is italic
+    comment: { color: col('phosphor'), italic: true }, // the strings' green italic

よくあるつまずき

つまずき

サイド段の囲みは、囲みを開く位置の次のブロックと同じ高さから始まる

postext 1.4.1では、span: 'side'の囲みは、囲みを開く位置で本文が達した高さの次のグリッド行から、すでにある囲みがあればその下に、サイド段に置かれます。注釈は説明する段落の直前で開いてください。段落のあとで開くと、注釈は次の段落の横から始まります。段の末尾を越える囲みは、上の囲みが許す範囲で、下端が段の末尾にそろうまで上にずれます。それでも収まらない囲みは、次のページのサイド段まで待ちます。 欄外の注 →

  • コードの各行は73字以内に収めます。長い行は収まる最後のスペースか約物の後で折り返し、続きを次の行の»の後に組みます。このときエンジンはcodeOverflow警告を出します。overflow: 'shrink'にするとリスト全体を小さく組み、'clip'にすると行を囲みの端で切ります。
  • リストの中のタブは、次の4桁の倍数の位置まで進みます(codeStyle.tabSize)。エディターで8桁幅に表示されるタブでインデントしたスクリプトは、ここでは幅が狭くなります。
  • codeStyle.inlineを設定すると、インラインコードはチップと同じく行をまたいで分割されません。~/Pictures/2025/IMG_0977.MOVのような本文中の長いパスは丸ごと次の行に移り、その前の行の語間が広がることがあります。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Charis SIL (SIL OFL 1.1) · Sora (SIL OFL 1.1) · JetBrains Mono (SIL OFL 1.1)
Sandbox