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

レシピ集 · 第2章 · 文字と本文

実験レポート:化学式、上付き下付き、滴定曲線

A4判4ページの化学の実験レポート。本文中の化学式と単位は~と^で示し、反応式と方程式にはTeXを使います。

このページの内容

1ページ(全4ページ)

  • スペイン語の見本:日本語版はまだありません
  • 仕上がり210 × 297 mm
  • 1段
  • Inria Serif 10.5/15
  • Inria Sans
  • Sometype Mono
  • 4ページ
  • レベル
  • Postext 1.57.1
  • 組版時間116 ms
  • コード237行

かんたんな説明

食酢を調べる学校の化学実験レポート4ページ。小さく上げ下げした数字で化学式や単位を書く方法と、いくつかの独立した数式の組み方を示します。

できあがり

高校最終学年(Year 12)の生徒3人が、リンゴ酢を水酸化ナトリウムで滴定して酢酸の含有量を求め、化学の授業の実験4として報告書にまとめます。レポートはA4判の片面印刷で4ページです。55 mmの左余白に節番号を置くので、すべての題と段落は同じ端から始まります。ビュレットと表の見出し行はスレートグレーで、色はフェノールフタレインのピンクだけです。レポートの見出しの帯と曲線上の指示薬の変色域には淡いピンクを、節番号とpHの読みには濃いピンクを使います。本文中の化学式と単位は本文書体のまま上付き・下付きで組み、反応式と3つの独立した数式はTeXで組みます。表1と図1の曲線は、どちらもサンプル内のビュレットの読みの配列1つから計算します。

このレシピが答える質問

  • 数式を使わずに、上付き文字、下付き文字、化学式を書くには?
  • 数式(インライン、ディスプレイ、方程式)を組み、PDFでもベクターのまま保つには?
  • 見出しに番号(1、1.1、1.1.1)を振り、レベルごとに異なるスタイルにするには?
  • 番号付きキャプションのある図を加え、本文で参照するには(「図3.2を参照」)?
  • 見出し行、結合セル、列幅、セルごとのそろえを備えた表を作るには?
  • 「図」や「表」のラベルを文書の言語で表示するには?
  • 参考文献や用語集を組むには(ぶら下げインデント、小さめの文字)?

手短な答え

script.js · 39〜53行コード全体で見る
// In the Markdown, ~…~ lowers a run and ^…^ raises it, in the text's own face at 58 % of
// its size: CH~3~COOH, OH^−^ (the minus is U+2212), 25,0 cm^3^, 0,100 mol·dm^−3^, p*K*~a~.
// The marks also work in captions and table cells, which keep their own face ($…$ there
// brings the maths face): the column heads this file writes, each a quantity over its unit:
const units = { cm3: 'cm^3^', conc: 'mol·dm^−3^' }; // the dot keeps a unit one word
const heads = t({ es: ['Valoración', 'V~inicial~', 'V~final~', 'V~b~ gastado'],
  en: ['Titration', 'V~initial~', 'V~final~', 'V~b~ used'] })
  .map((head, i) => (i ? `${head} / ${units.cm3}` : head)); // 'V~b~ gastado / cm^3^'
// Between $$ and $$ is TeX, set by MathJax as vector paths: the reaction, with mhchem's
// \ce{…} (it lowers the 3 of CH3COOH by itself), and the equations. initMathEngine() loads
// MathJax; a build that starts before it resolves prints grey boxes (gotcha: math-bundle).
await initMathEngine();
// A formula's x-height is TeX's 0.442 em of the type size and Inria Serif's is 0.495 em, so
// math.fontSizeScale lifts the formulas' lowercase to the height of the text's.
const MATH_SCALE = 0.495 / 0.442; // about 1.12

材料

種類
Inria Serif, Inria Sans, Sometype Mono (SIL OFL 1.1)
素材
なし:画像はすべてコードで描画

作り方

#1 · 化学式はテキストで書き、方程式にはTeXを使う

コードは上の手短な答えにあります。~…~と^…^は、その部分を本文と同じ書体で本文サイズの58 %に組みます。そのためCH~3~COOH、OH^−^(マイナスはU+2212)、cm^3^は、周りの文の太さと色を保ちます。この記法はキャプションや表のセルでも使え、キャプションやセルの書体のまま組まれます。インラインの$…$もそこで組めますが、数式の書体になります。mhchemの\ce{…}で書いた反応式と方程式は、$$で挟んだTeXです。await initMathEngine()が組版の前に数式エンジンを起動します。ほかの記号と同じインポートから読み込みます。math.fontSizeScaleは0.495 / 0.442(約1.12)にします。数式のxハイトはTeXの0.442 emで、Inria Serifのxハイトは0.495 emなので、この倍率で数式と本文の小文字が同じ高さにそろいます。

#2 · 節番号を余白にぶら下げる

script.js · 57〜78行コード全体で見る
const face = (size, extra) => ({ fontFamily: SANS, fontWeight: 700, fontSize: pt(size),
  lineHeight: 1.1, align: 'left', overflow: 'wrap', ...extra });
// The title starts on the text edge; the number hangs off its left side ('left-of') in a box
// of fixed width, set right. An auto width is clamped to the room the column leaves on that
// side, which is none: the box shrinks to 0 mm, the number wraps a character to a line and
// the heads grow by one to three lines (gotcha: negative-offsets).
const hang = (id, content, size, color, extra) => ({ kind: 'text', id, content,
  ...face(size, extra), color: col(color), align: 'right',
  placement: { ...at('#title', 'left-of', -GAP), size: { width: mm(HANG) } } });
const hung = (size, color) => ({ enabled: true, slot: { elements: [
  { kind: 'text', id: 'title', content: '{titleText}', ...face(size), color: col('ink'),
    placement: at('container', 'top-left') },
  hang('number', '{number}', size, color),
] } });
const levels = [
  { level: 1, breakBefore: { enabled: true, parity: 'any' } }, // the next page, either side
  // One grid line per head: the design sets the type, the level's size and leading the flow.
  { level: 2, numberingTemplate: '{2}', fontSize: pt(13), lineHeight: pt(LEAD),
    marginTop: pt(LEAD), marginBottom: pt(0), advancedDesign: hung(13, 'phenol') }, // 5
  { level: 3, numberingTemplate: '{2}.{3}', fontSize: pt(BODY), lineHeight: pt(LEAD),
    marginTop: pt(LEAD), marginBottom: pt(0), advancedDesign: hung(BODY, 'muted') }, // 5.1
];

見出しの各レベルのデザインは、2つの要素を置いたスロットです。題を本文の端に置き、{number}をそのleft-ofに4 mm離して、幅33 mmの右そろえのボックスに入れます。ボックスの幅は固定にします。自動の幅は段がその左に残す余地に制限されますが、余地はまったくないので、ボックスは0 mmに縮み、見出しが1〜3行増えてしまいます。レベルのfontSizeとlineHeightは、見出しが流れの中で占める高さ、つまり15 ptの1行分を決めるだけです。文字はデザインが決めます。節は{2}をピンクの13 ptで、小節は{2}.{3}を本文サイズのグレーで組みます。

#3 · H1からレポートの見出しを描く

script.js · 82〜113行コード全体で見る
const BAND = 104; // mm from the top of the page to the band's foot, where the flask stands
// The byline: values from the H1's attributes and the frontmatter, one per line, each
// with its label hung in the margin like a section number.
const byline = [['{attr.authors}', t({ es: 'Autores', en: 'Authors' })],
  ['{attr.group}', t({ es: 'Grupo', en: 'Class' })],
  ['{attr.teacher}', t({ es: 'Profesora', en: 'Teacher' })],
  ['{publishDate}', t({ es: 'Fecha', en: 'Date' })]].flatMap(([content, label], i) => [
  { kind: 'text', id: `value${i}`, content, fontFamily: SERIF, fontSize: pt(10), align: 'left',
    color: col('ink'), overflow: 'clip', placement: at('#title', 'below', 0, 7 + 4.6 * i) },
  { kind: 'text', id: `label${i}`, content: label, fontFamily: MONO, fontWeight: 500,
    fontSize: pt(7.5), letterSpacing: pt(1.2), textTransform: 'uppercase', color: col('ink'),
    align: 'right', overflow: 'clip',
    placement: { ...at(`#value${i}`, 'left-of', -GAP, 0.7), size: { width: mm(HANG) } } },
]);
const report = { id: 'report', numbered: false, advancedDesign: { enabled: true,
  // The band is a box, and boxes count towards the height a head reserves, so the text
  // would start below its foot at 104 mm (where the burette ends too). minHeight sets a floor
  // 8 mm lower, which the H1's bottom margin and the 15 pt grid round up to 15 mm.
  minHeight: mm(BAND + 8 - TOP), slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col('blush') },
      placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(BAND) } } },
    { kind: 'image', id: 'burette', resourceId: 'burette', // its stand 12 mm into the margin
      placement: { ...at('page', 'top-right', 12 - RIGHT), size: { width: mm(34) } } },
    { kind: 'text', id: 'course', content: '{attr.course}', fontFamily: MONO, fontWeight: 600,
      fontSize: pt(7.5), letterSpacing: pt(1.2), textTransform: 'uppercase',
      color: col('phenol'), overflow: 'clip', placement: at('container', 'top-left', 0, 2) },
    { kind: 'text', id: 'title', content: '{titleText}', ...face(27, { lineHeight: 1.06 }),
      color: col('ink'), placement: { ...at('#course', 'below', 0, 5), size: { width: mm(96) } } },
    hang('practice', '{attr.practice}', 27, 'phenol', { lineHeight: 1.06 }), // as a section's
    ...byline,
  ] } } };
const back = { id: 'back', numbered: false, advancedDesign: hung(13, 'phenol') }; // no number

レポートに1つだけあるH1はreport見出しスタイルを使い、描画した見出しに置き換わります。ページ上部を横切るピンクの帯、ビュレット、科目名の行、節番号と同じように実験番号をぶら下げた題、著者行です。著者行の値は見出しの属性とフロントマターのpublishDateから取ります。帯はボックスで、ボックスは見出しが確保する高さに数えられるので、minHeightがなくても本文は帯の下端、ページ上端から104 mmの位置より下から始まります。minHeightは帯の8 mm下に下限を設けます。H1の下のアキと15 ptのグリッドと合わせて、要旨の上のアキは4.7 mmではなく15 mmになります。

#4 · 表と図をレポートの言語で呼ぶ

script.js · 134〜144行コード全体で見る
// The built-in types follow the locale; defaultResourceTypes(LANG) hands them over so one can
// change. Their '{h1}.{n}' prints a plain 1: the H1 is unnumbered, and an empty {h1} drops out
// with its dot.
const resourceTypes = defaultResourceTypes(LANG).map((type) => (type.id === 'table'
  ? { ...type, captionStyle: { position: 'above' } } : type)); // a table's caption goes on top
const tableStyle = { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
  headerBackground: col('slate'), headerColor: col('paper'), headerFontFamily: SANS,
  headerFontSize: pt(8.5), bodyFontFamily: MONO, bodyFontSize: pt(8.8), bodyColor: col('ink'),
  cellPadding: mm(1.5) }; // figures in a monospace face, so the decimal separators line up
const captionStyle = { fontFamily: SANS, fontSize: pt(8.8), color: col('ink'), gap: mm(2.5),
  labelColor: col('phenol'), note: { fontFamily: SANS, fontSize: pt(7.4), color: col('muted') } };

組み込みの種類は文書のlocaleに従うので、スペイン語版は何も設定しなくてもTablaとFiguraになります。defaultResourceTypes(LANG)でその種類を受け取るのは、1つだけ変えるためです。番号のテンプレート{h1}.{n}は、ここではただの1を印刷します。レポートのH1には番号がなく、空の{h1}はピリオドごと消えるからです。表のキャプションは、レポートの慣例どおり表の上に置きます。本文は表と図を:ref{id="lecturas" style="full"}で参照し、参照は周りの語と同じ色と太さで組まれます。

#5 · 表と曲線を同じ読みから計算する

script.js · 293〜311行コード全体で見る
const READINGS = [[0.00, 21.30], [0.40, 21.25], [1.10, 22.00], [0.25, 21.10]]; // cm³: synthetic
const titres = READINGS.map(([from, to]) => to - from); // the first is the rough titration
const fair = titres.slice(1);
const mean = fair.reduce((a, b) => a + b) / fair.length; // 20.87 cm³
const sd = Math.sqrt(fair.reduce((s, v) => s + (v - mean) ** 2, 0) / (fair.length - 1)); // 0.03
const num = (x) => x.toFixed(2).replace('.', t({ es: ',', en: '.' })); // the decimal comma
const cell = (content, align = 'right') => ({ content, align }); // figures set right
const label = (es, en) => cell(t({ es, en }), 'left');
// A summary row: its label set right, against its value, and two cells for the merge to cover.
const total = (es, en, x) => [cell(t({ es, en })), cell(''), cell(''), cell(num(x))];
const rows = [heads.map((head, i) => ({ ...cell(head, i ? 'right' : 'left'), isHeader: true })),
  ...READINGS.map(([from, to], i) => [i ? cell(String(i), 'left') : label('Orientativa', 'Rough'),
    cell(num(from)), cell(num(to)), cell(num(titres[i]))]),
  total('Media de 1–3', 'Mean of 1–3', mean), total('Desviación típica', 'Standard deviation', sd)];
// The last two labels span the first three columns. The cells a merge covers stay in the
// row, marked hiddenBy, which mergeCells writes (gotcha: merged-cells-hiddenby).
const table = [rows.length - 2, rows.length - 1].reduce((model, row) => mergeCells(model,
  { start: { row, col: 0 }, end: { row, col: 2 } }), { headerRowCount: 1, rows,
  columnWidths: [1.8, 1, 1, 1.15] }); // relative: the first column holds the longest labels

ビュレットの読み4組から、表1のすべてのセルと平均、標準偏差が決まります。平均の体積は、図1が描くpHモデルの当量点になります。1行目は見出し行(headerRowCount: 1)で、columnWidthsはラベルの列に幅の1.8単位分を与えます。各セルはそれぞれalignを指定し、mergeCellsは平均と偏差のラベルを最初の3列にまたがらせて、値の手前に右そろえで置きます。数値はSometype Monoで組むので、小数点の位置がそろいます。列見出しはV~b~ used / cm^3^のように量を単位で割った形で、本文と同じ記法で書きます。

#6 · ぶら下げインデントの参考文献で締める

script.js · 162〜167行コード全体で見る
const paragraphStyles = [
  { id: 'references', fontSize: pt(9), lineHeight: pt(12.5), textAlign: 'left',
    hangingIndent: mm(6), spaceBetween: pt(4) }, // ragged, so never hyphenated
  { id: 'colophon', fontFamily: SANS, fontSize: pt(7.4), lineHeight: pt(10), color: col('muted'),
    textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) },
];

:::paragraphs{style="references"}のブロックは、各文献に段落スタイルを適用します。9 pt、行送り12.5 ptの左そろえで、6 mmのぶら下げインデントと項目間4 ptのアキを取ります。左そろえの段落は、bodyText.hyphenation.raggedで指定しないかぎりハイフネーションされないので、『Fundamentals of Analytical Chemistry』のような長い書名も語の間でしか改行されません。奥付には独自のスタイルがあり、Inria Sansの7.4 ptで、上に15 ptの1行分のアキを置きます。

レシピの全体

Sandbox
// ═══ Postext Cookbook · Nº 028 · Lab report: formulas, subscripts and a titration curve ═══
// https://postext.dev/en/cookbook/lab-report-formulas
// Code: MIT · Text: original (CC BY 4.0) · Figures: drawn in code (CC BY 4.0)
// Fonts: Inria Serif, Inria Sans, Sometype Mono (SIL OFL 1.1) · Needs postext ≥ 1.57.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
  initMathEngine, renderMath, mergeCells,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'es'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'lab-report-formulas';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // white paper and phenolphthalein: pale at the end point, deep past it
  ink: '#1d2126', // text: a blue-black
  phenol: '#ad2c5f', // the accent: numbers, kickers, stripes, the flask's liquid (6.4:1)
  blush: '#f6d5e2', // the end-point pink: the head's band, the indicator's range on the curve
  slate: '#5b6b7a', // the burette's steel, the table head
  rule: '#cfd4da', // hairlines
  muted: '#626a73', // running heads, notes (5.5:1)
  paper: '#ffffff',
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// 'main-color' as well: the engine's defaults are linked to it, so any left over turn pink.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.phenol })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [SERIF, SANS, MONO] = ['Inria Serif', 'Inria Sans', 'Sometype Mono'];
const [BODY, LEAD] = [10.5, 15]; // pt: text size and leading
// mm: A4, printed on one side, so not mirrored; the wide left margin holds the numbers
const [TRIM_W, TRIM_H, TOP, BOTTOM, LEFT, RIGHT] = [210, 297, 24, 22, 55, 31];
const MEASURE = TRIM_W - LEFT - RIGHT; // mm: 124, about 74 characters of Inria Serif
const GAP = 4; // mm between a hanging number and the text edge
const HANG = LEFT - GAP - 18; // mm: the number column, 18 mm clear of the trim
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });

// #region answer: formulas and units in the text face; TeX for the reaction and equations
// In the Markdown, ~…~ lowers a run and ^…^ raises it, in the text's own face at 58 % of
// its size: CH~3~COOH, OH^−^ (the minus is U+2212), 25,0 cm^3^, 0,100 mol·dm^−3^, p*K*~a~.
// The marks also work in captions and table cells, which keep their own face ($…$ there
// brings the maths face): the column heads this file writes, each a quantity over its unit:
const units = { cm3: 'cm^3^', conc: 'mol·dm^−3^' }; // the dot keeps a unit one word
const heads = t({ es: ['Valoración', 'V~inicial~', 'V~final~', 'V~b~ gastado'],
  en: ['Titration', 'V~initial~', 'V~final~', 'V~b~ used'] })
  .map((head, i) => (i ? `${head} / ${units.cm3}` : head)); // 'V~b~ gastado / cm^3^'
// Between $$ and $$ is TeX, set by MathJax as vector paths: the reaction, with mhchem's
// \ce{…} (it lowers the 3 of CH3COOH by itself), and the equations. initMathEngine() loads

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

アレンジ

#安全上の注意を枠でなく色で示す

終点のピンクの塗りが枠の代わりになるので、囲みの装飾は1つのままです。

   box('safety', t({ es: 'Seguridad', en: 'Safety' }), {
-    border: { enabled: true, color: col('phenol'), width: pt(0.75) },
+    backgroundEnabled: true, background: col('blush'),

#表と図に節ごとの番号を付ける

結果の表と図は表5.1と図5.1になり、節ごとに数え直します。

-const resourceTypes = defaultResourceTypes(LANG).map((type) => (type.id === 'table'
-  ? { ...type, captionStyle: { position: 'above' } } : type)); // a table's caption goes on top
+const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
+  numberingTemplate: '{h2}.{n}', resetOn: 'h2',
+  ...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));

よくあるつまずき

つまずき

数式には最初のビルドの前にawait initMathEngine()が必要

数式エンジンが動き出す前にレイアウトした数式は、灰色のプレースホルダーの箱になります。initMathEngineをほかのシンボルと一緒にhttps://esm.sh/postextから読み込み、最初のビルドの前にawaitしてください。数式のある文書をこれなしでビルドすると、コンソールに警告が1つ出ます。postext 1.5からは、MathJaxはinitMathEngineが取得する1つのモジュールとしてパッケージに含まれているので、通常のimportがCDNから使え、?bundleは必要ありません(1.4までは、すべてのシンボルをhttps://esm.sh/postext?bundleから読み込む必要がありました)。読み込むURLは1つだけにしてください。URLが2つあると、エンジンが2つ読み込まれます。 数式 →

つまずき

コンテナー基準の負のオフセットでは何も描かれない

幅が自動のデザインのテキストはコンテナーの中に制限されるため、コンテナーからの負のオフセットで外に押し出されると何も描かれません。こうした要素はページか裁ち落としに固定してmm単位のオフセットを明示するか、幅を固定してください。 デザイン要素の基準位置 →

つまずき

結合セルにはhiddenByのプレースホルダーが要る。mergeCellsを使う

セルは行の配列内の位置で配置されるため、結合セルが広がる位置にはhiddenByを付けたプレースホルダーのセルが必要です。HTMLのように省くと、それ以降の列がすべてずれます。結合はmergeCellsで作ってください。postext 1.5からは、グリッドが不ぞろいな表はdoc.contentWarningsにraggedTableGridとして報告され、parseTSV(text, { headerRows })でヘッダー行を指定できます。 データから作る表 →

Sandboxの検査 · invalidMath

無効なLaTeX

原因. MathJaxが数式を解析できなかったため、代わりに赤いプレースホルダーが印字されます。

対処. TeXを修正するか、数式のつもりではないドル記号を\$でエスケープしてください。 ドキュメント →

Markdown警告 · unclosedMath

閉じられていない数式の区切り記号

原因. $でインライン数式が始まっていますが、閉じられていません。たいていは価格に付いたドル記号です。

対処. ドル記号そのものは\$と書くか、同じ行で数式を閉じてください。 ドキュメント →

  • 既定では、独立した数式はそれを導く行と一緒に保たれません。そのため「so」で終わる導入の行がページの最後に残り、式が次のページに送られることがあります。math.keepWithLeadIn: trueにすると、その行も式と一緒に次のページへ送られます。このレシピでは有効にしてあるので、文章の長さが変わっても[OH⁻]の式はその文と離れません。
  • TeXのグリフはInria SerifではなくMathJax自身のものなので、方程式は周りの本文より少し細く見えます。文中の化学式は~と^の記法で書き、TeXはそれが必要な行だけに使います。
  • 曲線の目盛りラベルと軸の題はMathJaxのアウトラインで、方程式と同じグリフを使い、PDFでもベクターのまま残ります。tex()が各ラベルのパスをrenderMathに求め、SVGに配置します。描けるのはinitMathEngine()が完了してからです。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Inria Serif (SIL OFL 1.1) · Inria Sans (SIL OFL 1.1) · Sometype Mono (SIL OFL 1.1)
SandboxPDF