跳到主要内容
食谱编号48

排版食谱 · 第6章 · 框与注释

代码清单和按键

一本Shell指南:围栏代码排成深色清单框,按记号着色,按键排成键帽标签。

本页内容

页码50–51 · 第2–3页,共3页

  • 英文样例:尚无中文版本
  • 成品尺寸178 × 229 mm
  • 一栏半, 栏间距6 mm
  • Charis SIL 10/14.5
  • JetBrains Mono
  • Sora
  • 3页
  • 难度
  • Postext 1.57.1
  • 排版用时89 ms
  • 147行代码

简单来说

一本命令行入门小书的三页。示例演示怎样把代码示例排进彩色的深底框,并把Ctrl这样的按键画成正文里的小键帽。

成品一览

The Shell, Gently第4章的三页。这是一本虚构的命令行袖珍指南,页面尺寸178 × 229 mm。正文用Charis SIL在100 mm宽的栏里两端对齐排版,外侧另有一栏放旁注。每段代码清单是一个近黑色的JetBrains Mono框,伸进那一栏,顶上有个页签写着文件名或会话名。关键字和输入的命令印成琥珀色,字符串绿色,注释灰色。Ctrl、Tab等按键是两端对齐行内的小号描边键帽,第50页下部是一张两栏的Ctrl快捷键速查表。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按原样排它的各行,一行代码对应一行文字,缩进、脚本里的空行和du的两栏输出都保留下来。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个字符。这种一栏半版面的侧栏只放浮动体和注释,正文永远不会流进去。codeStyle里的span: 'page'让每段清单横跨两栏,宽143 mm。扣除内边距后,一个框能容纳73个8.6 pt的JetBrains Mono字符;这几页最长的一行,即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,所以输入的命令印成琥珀色粗体,Shell的回应保持清单的浅灰色。这个示例不想着色的类别,包括数字、变量和选项,也用这种灰色。

#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描边。其大小以pt给出,所以无论在10 pt正文、8.6 pt旁注还是8.4 pt速查表里,按键都是7.8 pt;若用em(0.78),速查表里的按键会缩到6.6 pt。行内标签永远不跨行断开,也不会拉伸(行内标签),所以带按键的行把全部多余空间都放进词间空格。spacing让断行程序在空格超过正常宽度140 %之前先尝试其他断点。按默认的200 %,这几页有六行的空格拉得比这更宽;加上这项设置后,最宽的是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页下部(浮动框)。留在文本流里的话,一个通栏的框需要容纳自身和下面两行文字的空间。这里框会移到第51页,步骤下面空出58 mm,这一章也会排成四页。在Markdown里,:::columns{count=2 breaks="8"}在第八个块,也就是其标题处开启右栏。只靠齐底会按高度切分,一旦某条操作折成两行,Commands and history就会落在左栏底部。每一条都以同样的两个标签开头,Ctrl和一个字母,都用等宽字体,所以每条操作都从距所在栏左边缘相同的位置开始。

完整食谱

沙盒
// ═══ 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行。单段清单可以在围栏行上写{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,会整个移到下一行,可能在它前面留下一行松散的字距。

致谢

文本
原创文字, CC BY 4.0
字体
Charis SIL (SIL OFL 1.1) · Sora (SIL OFL 1.1) · JetBrains Mono (SIL OFL 1.1)
沙盒