@threepenny/md2pdf 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/fit.js ADDED
@@ -0,0 +1,266 @@
1
+ // Shrinks each displayed formula under `root` that is wider than its column until it fits, on screen and
2
+ // in print. KaTeX draws a displayed formula as one line that never wraps, so a long one runs off the page.
3
+ //
4
+ // Runs in the browser, once the page is rendered and its fonts have loaded. It measures each formula's
5
+ // width in proportion to its font size, which doesn't depend on the column, and sizes it with container
6
+ // query units. So the browser fits it to whatever column it ends up in, including the printed page's,
7
+ // which a script can't measure: when printing starts, the page is still laid out at screen width. A
8
+ // formula that fits keeps its size. Running it again is harmless.
9
+ //
10
+ // Self-contained, so the CLI can put its source in the page. md2pdf.me fits formulas its own way, with
11
+ // the page's width, which its preview knows.
12
+ export function fitFormulas(root = document) {
13
+ for (const formula of root.querySelectorAll('eqn > .katex-display > .katex')) {
14
+ const display = formula.parentElement;
15
+ const section = display.parentElement.parentElement;
16
+ if (!section) continue;
17
+ formula.style.fontSize = '';
18
+ display.style.containerType = '';
19
+ display.style.width = 'max-content';
20
+ // A \tag number sits at the column's edge, outside the formula's own width. The formula is centred,
21
+ // so clearing the number takes its width on both sides.
22
+ const tag = formula.querySelector('.katex-html > .katex-tag');
23
+ const width = formula.getBoundingClientRect().width + 2 * (tag?.getBoundingClientRect().width ?? 0);
24
+ display.style.width = '';
25
+ const size = parseFloat(getComputedStyle(formula).fontSize);
26
+ const parentSize = parseFloat(getComputedStyle(display).fontSize);
27
+ if (!(width > 0 && size > 0 && parentSize > 0)) continue;
28
+ // The container is the formula's own block, whose margins collapse with the text around it as before:
29
+ // a container's children's margins don't. A container sizes without its content, so one in a box that
30
+ // sizes to its content, such as a table cell, would collapse it. Leave such a formula as it was.
31
+ const before = section.getBoundingClientRect().width;
32
+ display.style.containerType = 'inline-size';
33
+ if (section.getBoundingClientRect().width !== before) {
34
+ display.style.containerType = '';
35
+ continue;
36
+ }
37
+ // Only the formula's own text scales, so the space above and below it stays the style's. Glyphs land on
38
+ // rounded positions, so a formula's width doesn't scale exactly with its size: 99% of the column leaves room.
39
+ formula.style.fontSize = `min(${size / parentSize}em, calc(99cqi * ${size / width}))`;
40
+ }
41
+ }
42
+
43
+ // Fits each table under `root` that runs past its box on the printed page, so every column prints. KaTeX's
44
+ // formulas never wrap, and a cell can't be narrower than its longest word, so a table of long words or a
45
+ // long formula can be wider than the page.
46
+ //
47
+ // Runs in the browser after fitFormulas, which resets every displayed formula's size, once the page is
48
+ // rendered and its fonts have loaded. A table's width depends on the column it ends up in, so it lays the
49
+ // page out at the printed column's width, read from the page's @page rules, while it measures. Then, for a
50
+ // table that runs past its box:
51
+ // 1. A formula in one of its cells shrinks, down to half size, keeping every word whole.
52
+ // 2. If that isn't enough, the body cells of its columns whose longest word is longer than 8 characters
53
+ // break their words, widest column first, measuring after each, until it fits. A break that doesn't
54
+ // narrow its column is taken back. If the table still doesn't fit, those columns' headers break too,
55
+ // all at once, so the broken columns share the width; then every cell.
56
+ // 3. Its formulas then grow back as large as fits, or shrink further if they must.
57
+ // A table that fits isn't written to, so it prints as it did. If the printed width can't be read, nothing
58
+ // changes. Running it again is harmless.
59
+ //
60
+ // Self-contained, so the CLI can put its source in the page.
61
+ export function fitTables(root = document) {
62
+ const FIT = 'data-md2pdf-fit';
63
+ // Puts back an element's style attribute as it was. Chrome keeps an empty one after a script has
64
+ // written its style, even through removeAttribute, unless the attribute is set first.
65
+ const restore = (el, style) => {
66
+ el.setAttribute('style', style ?? '');
67
+ if (style === null) el.removeAttribute('style');
68
+ };
69
+ const unset = (el, ...properties) => {
70
+ for (const property of properties) el.style.removeProperty(property);
71
+ restore(el, el.getAttribute('style') || null);
72
+ el.removeAttribute(FIT);
73
+ };
74
+ for (const el of root.querySelectorAll(`[${FIT}]`)) unset(el, 'overflow-wrap', 'font-size');
75
+ const tables = [...root.querySelectorAll('table')];
76
+ if (!tables.length) return;
77
+
78
+ // The printed page's width and side margins: the last rule without a page selector that sets each.
79
+ const page = {};
80
+ const read = (rules) => {
81
+ for (const rule of rules) {
82
+ if (rule instanceof CSSPageRule) {
83
+ if (rule.selectorText) continue;
84
+ for (const name of ['size', 'margin-left', 'margin-right']) {
85
+ const value = rule.style.getPropertyValue(name);
86
+ if (value) page[name] = value;
87
+ }
88
+ } else if (rule instanceof CSSImportRule) {
89
+ if (!rule.media.length || [...rule.media].some((m) => /\b(all|print)\b/i.test(m) && !/\bnot\b/i.test(m))) {
90
+ try {
91
+ read(rule.styleSheet.cssRules);
92
+ } catch {
93
+ // A stylesheet from another origin can't be read.
94
+ }
95
+ }
96
+ } else if (rule instanceof CSSMediaRule) {
97
+ if ([...rule.media].some((m) => /\b(all|print)\b/i.test(m) && !/\bnot\b/i.test(m))) read(rule.cssRules);
98
+ } else if (rule.cssRules && !(rule instanceof CSSStyleRule)) {
99
+ read(rule.cssRules);
100
+ }
101
+ }
102
+ };
103
+ for (const sheet of document.styleSheets) {
104
+ try {
105
+ read(sheet.cssRules);
106
+ } catch {
107
+ // As above.
108
+ }
109
+ }
110
+ const html = document.documentElement;
111
+ const box = document.createElement('div');
112
+ box.style.cssText = 'position: absolute; visibility: hidden; height: 0; padding: 0; border: 0';
113
+ const probe = box.cloneNode();
114
+ box.append(probe);
115
+ html.append(box);
116
+ const px = (length) => {
117
+ if (!length || /v(w|h|min|max)$/i.test(length)) return NaN;
118
+ probe.style.width = '';
119
+ probe.style.width = length;
120
+ return probe.style.width ? probe.getBoundingClientRect().width : NaN;
121
+ };
122
+ const PAPER = {
123
+ a5: ['148mm', '210mm'], a4: ['210mm', '297mm'], a3: ['297mm', '420mm'], b5: ['176mm', '250mm'],
124
+ b4: ['250mm', '353mm'], 'jis-b5': ['182mm', '257mm'], 'jis-b4': ['257mm', '364mm'],
125
+ letter: ['8.5in', '11in'], legal: ['8.5in', '14in'], ledger: ['11in', '17in'],
126
+ };
127
+ // Chrome prints `auto`, or an orientation alone, on Letter paper.
128
+ const words = (page.size || 'auto').trim().toLowerCase().split(/\s+/);
129
+ const paper = PAPER[words.find((word) => PAPER[word]) ?? 'letter'];
130
+ const width = /^[\d.+]/.test(words[0]) ? px(words[0]) : px(words.includes('landscape') ? paper[1] : paper[0]);
131
+ // A margin in % is a share of the page's width.
132
+ box.style.width = `${width}px`;
133
+ const column = width - px(page['margin-left']) - px(page['margin-right']);
134
+ box.remove();
135
+ if (!(column > 0)) return;
136
+
137
+ const style = html.getAttribute('style');
138
+ html.style.width = `${column}px`;
139
+ try {
140
+ for (const table of tables) fit(table);
141
+ } finally {
142
+ restore(html, style);
143
+ }
144
+
145
+ function fit(table) {
146
+ // How far the table reaches past its box.
147
+ const past = () => {
148
+ const parent = table.parentElement;
149
+ const s = getComputedStyle(parent);
150
+ const edge = parent.getBoundingClientRect().right - parseFloat(s.borderRightWidth) - parseFloat(s.paddingRight);
151
+ let right = table.getBoundingClientRect().right;
152
+ for (const row of table.rows) right = Math.max(right, row.getBoundingClientRect().right);
153
+ return right - edge;
154
+ };
155
+ // A table is fitted when it runs past its box by more than a pixel: less only reaches into the page
156
+ // margin, and the slack keeps a rounding difference from the printed page's width from changing a table
157
+ // that fits. Fitted, it stays inside its box.
158
+ if (!table.parentElement || !(past() > 1)) return;
159
+ const fits = () => past() <= 0;
160
+
161
+ // The table's own cells, by column. A cell that spans columns is broken only with every cell (step 2).
162
+ const columns = [];
163
+ const taken = [];
164
+ [...table.rows].forEach((row, r) => {
165
+ let c = 0;
166
+ for (const cell of row.cells) {
167
+ while (taken[r]?.[c]) c++;
168
+ for (let i = 0; i < (cell.rowSpan || 1); i++) {
169
+ for (let j = 0; j < cell.colSpan; j++) (taken[r + i] ??= [])[c + j] = true;
170
+ }
171
+ if (cell.colSpan === 1) (columns[c] ??= []).push(cell);
172
+ c += cell.colSpan;
173
+ }
174
+ });
175
+ // Each column's width with every cell at its narrowest, as wide as its longest word or formula.
176
+ const narrowest = () => {
177
+ const before = table.getAttribute('style');
178
+ table.style.width = 'min-content';
179
+ const widths = columns.map((cells) => {
180
+ if (!cells?.length) return 0;
181
+ const s = getComputedStyle(cells[0]);
182
+ const edges = ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'].reduce((sum, p) => sum + parseFloat(s[p]), 0);
183
+ return cells[0].getBoundingClientRect().width - edges;
184
+ });
185
+ restore(table, before);
186
+ return widths;
187
+ };
188
+ const eight = (cell) => {
189
+ const span = document.createElement('span');
190
+ span.style.cssText = 'position: absolute; visibility: hidden; width: 8ch; padding: 0; border: 0';
191
+ cell.append(span);
192
+ const width = span.getBoundingClientRect().width;
193
+ span.remove();
194
+ return width;
195
+ };
196
+ const mark = (cell) => {
197
+ cell.style.overflowWrap = 'anywhere';
198
+ cell.setAttribute(FIT, '');
199
+ };
200
+ const long = (widths, c) => columns[c]?.length && widths[c] > eight(columns[c][0]);
201
+ const body = (c) => columns[c].filter((cell) => cell.localName === 'td');
202
+ // Breaks the body cells of the long columns, widest first, until the table fits. Returns whether it does.
203
+ const breakBodies = () => {
204
+ const tried = new Set();
205
+ while (!fits()) {
206
+ const widths = narrowest();
207
+ let best = -1;
208
+ widths.forEach((w, c) => {
209
+ if (!tried.has(c) && long(widths, c) && body(c).length && (best < 0 || w > widths[best])) best = c;
210
+ });
211
+ if (best < 0) return false;
212
+ tried.add(best);
213
+ body(best).forEach(mark);
214
+ if (narrowest()[best] >= widths[best] - 0.5) for (const cell of body(best)) unset(cell, 'overflow-wrap');
215
+ }
216
+ return true;
217
+ };
218
+
219
+ // Its formulas: displayed ones, and inline ones with a part longer than 8 characters that can't wrap.
220
+ const formulas = [...table.querySelectorAll(':is(td, th) .katex')]
221
+ .filter((formula) => formula.closest('table') === table)
222
+ .filter((formula) => {
223
+ if (formula.parentElement.classList.contains('katex-display')) return true;
224
+ const parts = [...formula.querySelectorAll(':scope > .katex-html > .base')];
225
+ return parts.some((part) => part.getBoundingClientRect().width > eight(formula.closest('td, th')));
226
+ })
227
+ .map((formula) => [formula, parseFloat(getComputedStyle(formula).fontSize) / parseFloat(getComputedStyle(formula.parentElement).fontSize)]);
228
+ const scale = (factor) => {
229
+ for (const [formula, size] of formulas) {
230
+ formula.style.fontSize = `${size * factor}em`;
231
+ formula.setAttribute(FIT, '');
232
+ }
233
+ };
234
+ // The largest size from `small`, at which the table fits, up to `large`. At full size, they're left as
235
+ // they were.
236
+ const largest = (small, large) => {
237
+ scale(large);
238
+ if (fits()) {
239
+ if (large === 1) for (const [formula] of formulas) unset(formula, 'font-size');
240
+ return;
241
+ }
242
+ while (large - small > 0.01) {
243
+ const middle = (small + large) / 2;
244
+ scale(middle);
245
+ if (!fits()) large = middle;
246
+ else small = middle;
247
+ }
248
+ scale(small);
249
+ };
250
+
251
+ if (formulas.length) {
252
+ scale(0.5);
253
+ if (fits()) return largest(0.5, 1);
254
+ }
255
+ if (!breakBodies()) {
256
+ const widths = narrowest();
257
+ columns.forEach((cells, c) => long(widths, c) && cells.forEach(mark));
258
+ if (!fits()) for (const row of table.rows) for (const cell of row.cells) mark(cell);
259
+ }
260
+ if (!formulas.length) return;
261
+ if (fits()) return largest(0.5, 1);
262
+ scale(0.05);
263
+ if (!fits()) scale(0.5);
264
+ else largest(0.05, 0.5);
265
+ }
266
+ }
package/lib/math.js CHANGED
@@ -1,10 +1,12 @@
1
1
  // TeX math, rendered by KaTeX: $…$ and \(…\) inline, $$…$$, \[…\] and \begin{env}…\end{env} displayed,
2
- // and a number in parentheses after a displayed formula, `$$E = mc^2$$ (1)`. The syntax is that of
2
+ // and a number in parentheses after a displayed formula on its last line, `$$E = mc^2$$ (1)`. The syntax is that of
3
3
  // markdown-it-texmath 1.0.0 with its brackets, dollars and beg_end delimiters and outerSpace, except that
4
- // a $ formula may also start or end beside a line break. texmath searches for the closing delimiter from
5
- // every opening one, which takes quadratic time on a line of openers, so these rules find closers through
6
- // tables built in one pass over the source. A displayed formula also ends inside the blockquote it starts
7
- // in; texmath's could run on past it, so that each of a run of quotes echoed the rest of the document.
4
+ // a $ formula may also start or end beside a line break, start after ( * or _, or end before ) * _ ? ! or :,
5
+ // and can't hold an unescaped $, and that starred environments such as align* start a block too. texmath
6
+ // searches for the closing delimiter from every opening one, which takes quadratic time on a line of
7
+ // openers, so these rules find closers through tables built in one pass over the source. A displayed
8
+ // formula also ends inside the blockquote it starts in; texmath's could run on past it, so that each of a
9
+ // run of quotes echoed the rest of the document.
8
10
 
9
11
  import { first, nextWhere } from './scan.js';
10
12
 
@@ -19,8 +21,9 @@ const DEFINITION = /\\(?:[egx]?def|let|futurelet|global|long|(?:re|provide)?newc
19
21
  // Caps how far a formula can reach (\rule, \raisebox, \hspace). Negative sizes aren't capped.
20
22
  const MAX_SIZE = 30;
21
23
  // The HTML a document's formulas may add up to, in characters, by default. KaTeX's HTML is about 50 to 250 times
22
- // its TeX for ordinary formulas and over 500 times for a matrix of empty cells; a formula that would take
23
- // the HTML past the budget, and every one after it, shows as its source.
24
+ // its TeX for ordinary formulas and over 500 times for a matrix of empty cells, and the MathML adds 10% to
25
+ // 30% to that, or nearly doubles a one-letter formula. A formula that would take the HTML past the budget,
26
+ // and every one after it, shows as its source.
24
27
  const MAX_HTML = 10_000_000;
25
28
 
26
29
  // How deeply {…} nest in `tex`, not counting a brace after a backslash.
@@ -48,15 +51,16 @@ const closeBracket = (s, i) => s.startsWith('\\]', i);
48
51
  const dollar = (s, i) => s[i] === '$';
49
52
  // A $ that can close an inline formula: not after a space or a backslash.
50
53
  const dollarCloser = (s, i) => s[i] === '$' && i > 0 && !SPACE.test(s[i - 1]) && s[i - 1] !== '\\';
54
+ const bareDollar = (s, i) => s[i] === '$' && s[i - 1] !== '\\';
51
55
  const lineBreak = (s, i) => isBreak(s[i]);
52
56
  const nonSpace = (s, i) => !SPACE.test(s[i]);
53
57
  const bracketNumberStop = (s, i) => ')$\r\n'.includes(s[i]);
54
58
  const dollarNumberStop = (s, i) => s[i] === ')' || SPACE.test(s[i]);
55
59
 
56
- // Whether the $ at `at` opens or closes a formula: whitespace or the paragraph's edge is outside it,
57
- // or after a closing $, punctuation that ends a clause.
58
- const dollarPre = (src, at) => at === 0 || SPACE.test(src[at - 1]);
59
- const dollarPost = (src, at) => at + 1 >= src.length || /[\s.,;]/.test(src[at + 1]);
60
+ // Whether the $ at `at` opens or closes a formula: whitespace or the paragraph's edge is outside it, or
61
+ // emphasis or a parenthesis, or after a closing $, punctuation that ends a clause.
62
+ const dollarPre = (src, at) => at === 0 || /[\s(*_]/.test(src[at - 1]);
63
+ const dollarPost = (src, at) => at + 1 >= src.length || /[\s.,;:?!)*_]/.test(src[at + 1]);
60
64
  // texmath's own test for $$ inside a paragraph, which outerSpace doesn't reach: no backslash or digit
61
65
  // before the opening $$, and no digit after the closing one.
62
66
  const isDigit = (c) => c >= '0' && c <= '9';
@@ -72,7 +76,8 @@ function* doubleDollar(state, at) {
72
76
  if (src[d + 1] === '$' && src[d + 2] === '$') yield { content: src.slice(at + 2, d + 1), end: d + 3 };
73
77
  }
74
78
 
75
- // $…$ from `at`, as texmath's \$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$ matches it, or null.
79
+ // $…$ from `at`, as texmath's \$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$ matches it, or null. Unlike texmath's,
80
+ // a formula can't hold an unescaped $ of its own, so in `From $5 to $10, $x$` only $x$ is a formula.
76
81
  function singleDollar(state, at) {
77
82
  const { src } = state;
78
83
  const c = src[at + 1];
@@ -82,6 +87,8 @@ function singleDollar(state, at) {
82
87
  if (close < 0) return null;
83
88
  const br = first(state, lineBreak, at + 2);
84
89
  if (br >= 0 && br < close) return null;
90
+ const inner = first(state, bareDollar, at + 1);
91
+ if (inner >= 0 && inner < close) return null;
85
92
  return { content: src.slice(at + 1, close), end: close + 1 };
86
93
  }
87
94
 
@@ -125,10 +132,14 @@ function inline(state, silent) {
125
132
  return true;
126
133
  }
127
134
 
128
- // An equation number after a displayed formula that ends at `from`: whitespace, then (number).
135
+ // An equation number after a displayed formula that ends at `from`: spaces, then (number), on the closing
136
+ // delimiter's own line. texmath's could start on any later line, so it took the (a) that starts the next
137
+ // paragraph.
129
138
  function equationNumber(state, from, stop) {
130
139
  const open = first(state, nonSpace, from);
131
140
  if (open < 0 || state.src[open] !== '(') return null;
141
+ const br = first(state, lineBreak, from);
142
+ if (br >= 0 && br < open) return null;
132
143
  const close = first(state, stop, open + 1);
133
144
  if (close <= open + 1 || state.src[close] !== ')') return null;
134
145
  return { info: state.src.slice(open + 1, close), end: close + 1 };
@@ -138,7 +149,7 @@ function equationNumber(state, from, stop) {
138
149
  function environmentEnd(state, name, from) {
139
150
  if (!state.md2pdfEnds) {
140
151
  state.md2pdfEnds = new Map();
141
- for (const m of state.src.matchAll(/\\end\{([a-z]+)\}/g)) {
152
+ for (const m of state.src.matchAll(/\\end\{([a-z]+\*?)\}/g)) {
142
153
  if (!state.md2pdfEnds.has(m[1])) state.md2pdfEnds.set(m[1], []);
143
154
  state.md2pdfEnds.get(m[1]).push(m.index);
144
155
  }
@@ -154,7 +165,7 @@ function environmentEnd(state, name, from) {
154
165
  return lo < ends.length ? ends[lo] : -1;
155
166
  }
156
167
 
157
- const BEGIN = /\\begin\{([a-z]+)\}/y;
168
+ const BEGIN = /\\begin\{([a-z]+\*?)\}/y;
158
169
 
159
170
  // The displayed formula starting at `at`, trying texmath's block rules in their order, or null.
160
171
  function displayed(state, at) {
@@ -256,7 +267,8 @@ export default function math(md, { katex, maxHtml = MAX_HTML }) {
256
267
  try {
257
268
  return katex.renderToString(tex, {
258
269
  displayMode,
259
- output: 'html',
270
+ // MathML, which KaTeX's stylesheet hides, gives screen readers the formula; KaTeX hides its HTML from them.
271
+ output: 'htmlAndMathml',
260
272
  throwOnError: false,
261
273
  trust: false,
262
274
  maxSize: MAX_SIZE,
@@ -0,0 +1,20 @@
1
+ // The @page sizes md2pdf takes, shared by the CLI and buildDocument: auto, a paper name, an orientation or
2
+ // both, or one or two lengths. Chrome prints a size it can't read at Letter without a word. It also reads
3
+ // calc() and newer units, which aren't taken here.
4
+
5
+ export const PAPER = ['a5', 'a4', 'a3', 'b5', 'b4', 'jis-b5', 'jis-b4', 'letter', 'legal', 'ledger'];
6
+ const ORIENTATION = ['portrait', 'landscape'];
7
+ const LENGTH = /^\+?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?(?:in|cm|mm|q|pt|pc|px|em|rem|ex|ch|vw|vh|vmin|vmax)$/;
8
+ // buildDocument writes a size that passes straight into its <style> element, so this is checked first, on the
9
+ // string as given: whatever the word rules below come to accept, nothing else can reach the stylesheet. Only
10
+ // CSS's whitespace separates words; to CSS, a no-break space is part of a word.
11
+ const CHARACTERS = /^[A-Za-z0-9.+\- \t\n\r\f]*$/;
12
+
13
+ export function isPageSize(size) {
14
+ if (typeof size !== 'string' || !CHARACTERS.test(size)) return false;
15
+ const words = size.trim().toLowerCase().split(/\s+/);
16
+ if (words.length > 2) return false;
17
+ if (words.every((w) => LENGTH.test(w)) || size.trim().toLowerCase() === 'auto') return true;
18
+ const count = (list) => words.filter((w) => list.includes(w)).length;
19
+ return count(PAPER) <= 1 && count(ORIENTATION) <= 1 && count(PAPER) + count(ORIENTATION) === words.length;
20
+ }
package/lib/render.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Markdown → HTML rendering shared by the CLI and the md2pdf.me website.
2
2
 
3
+ import { decodeHTML } from 'entities';
3
4
  import MarkdownIt from 'markdown-it';
4
5
  import footnote from 'markdown-it-footnote';
5
6
  import { full as emoji } from 'markdown-it-emoji';
@@ -7,7 +8,9 @@ import callouts from './callouts.js';
7
8
  import footnotes from './footnotes.js';
8
9
  import ids, { ID_PREFIX } from './ids.js';
9
10
  import mathRules from './math.js';
11
+ import { PAPER, isPageSize } from './page-size.js';
10
12
  import taskLists from './tasklists.js';
13
+ import typography from './typography.js';
11
14
  import wikilinks from './wikilinks.js';
12
15
 
13
16
  // YAML front matter: a `---` line at the very start of the document, closed by another `---` line.
@@ -17,6 +20,16 @@ const YAML_KEY = /^[^\s#:-][^:]*:(?:[ \t]|$)/;
17
20
  // Any other line properties can have: a `- item`, an indented continuation or a # comment.
18
21
  const YAML_OTHER = /^(?:-(?:[ \t]|$)|[ \t]+\S|#)/;
19
22
 
23
+ // Windows editors start a file with U+FEFF, which isn't whitespace to markdown-it: left in, the first line
24
+ // is no longer a heading or the start of front matter.
25
+ const withoutByteOrderMark = (s) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
26
+
27
+ function byteOrderMark(md) {
28
+ md.core.ruler.before('normalize', 'byte_order_mark', (state) => {
29
+ state.src = withoutByteOrderMark(state.src);
30
+ });
31
+ }
32
+
20
33
  // The front matter block at the start of `markdown` and the YAML inside it, or null. A `---…---` block
21
34
  // that isn't YAML properties is Markdown after a divider, as AI answers write it. A # line could be a
22
35
  // comment or a heading, and a - line a list, so the first other line must be a property.
@@ -114,10 +127,12 @@ export function createRenderer({ hljs, math, html = true, idPrefix = '', highlig
114
127
  .use(footnote)
115
128
  .use(footnotes, { idPrefix })
116
129
  .use(taskLists)
130
+ .use(typography)
117
131
  .use(emoji)
118
132
  .use(callouts)
119
133
  .use(wikilinks, { slugify })
120
- .use(frontMatter);
134
+ .use(frontMatter)
135
+ .use(byteOrderMark);
121
136
  if (math) md.use(mathRules, { katex: math.katex, maxHtml: math.maxHtml });
122
137
  return md;
123
138
  }
@@ -133,34 +148,145 @@ function trimSpaceTab(s) {
133
148
  return s.slice(start, end);
134
149
  }
135
150
 
136
- // The document title: the text of the first level-one heading as it renders, else the front matter's
137
- // `title:`, else the fallback.
151
+ // A block scalar's header: > or |, with its chomping and indentation indicators.
152
+ const BLOCK_SCALAR = /^[>|][+-]?\d?[+-]?(?:[ \t]+#[^]*)?$/;
153
+
154
+ // The first `title:` in front matter's YAML that has a value, or ''. A lowercase key only, as YAML's keys
155
+ // are case-sensitive. A `>` or `|` block reads as one line, and a quoted value loses its quotes.
156
+ function yamlTitle(yaml) {
157
+ const lines = yaml.split(/\r?\n/);
158
+ for (let i = 0; i < lines.length; i++) {
159
+ if (!/^title:(?:[ \t]|$)/.test(lines[i])) continue;
160
+ let value = trimSpaceTab(lines[i].slice('title:'.length));
161
+ // [^]* and not .*, here and below: a line can hold a lone \r or a line separator, which . stops at, and
162
+ // the search would then run again from every #.
163
+ const quoted = value.match(/^(["'])(.*?)\1[ \t]*(?:#[^]*)?$/);
164
+ if (BLOCK_SCALAR.test(value)) {
165
+ const text = [];
166
+ for (let j = i + 1; j < lines.length && (/^[ \t]/.test(lines[j]) || !lines[j].trim()); j++) text.push(lines[j].trim());
167
+ value = text.filter(Boolean).join(' ');
168
+ } else if (quoted) {
169
+ value = quoted[2];
170
+ } else {
171
+ // A # after a space starts a comment.
172
+ value = value.startsWith('#') ? '' : value.replace(/[ \t]#[^]*$/, '');
173
+ }
174
+ if (value.trim()) return value.trim();
175
+ }
176
+ return '';
177
+ }
178
+
179
+ // Whether a block token is raw HTML, or holds some, whose text matches `pattern`.
180
+ const rawHtml = (token, pattern = /^/) =>
181
+ token.type === 'html_block'
182
+ ? pattern.test(token.content)
183
+ : token.type === 'inline' && token.children.some((t) => t.type === 'html_inline' && pattern.test(t.content));
184
+
185
+ // The document title: the text of the first level-one heading, Markdown or raw HTML, as headingText finds it
186
+ // in a render with raw HTML on; else the front matter's `title:`, else the fallback.
138
187
  export function titleOf(markdown, fallback) {
139
- titleParser ??= createRenderer({});
188
+ if (!titleParser) {
189
+ // Code renders unhighlighted and callouts without icons, with the same text. Each render call starts
190
+ // the icon cap again, so the pieces below would otherwise draw every icon.
191
+ titleParser = createRenderer({ hljs: { getLanguage: () => undefined } });
192
+ titleParser.renderer.rules.callout_title_open = () => '<p class="markdown-alert-title">';
193
+ }
140
194
  const env = {};
141
195
  const tokens = titleParser.parse(markdown, env);
142
- const at = tokens.findIndex((t) => t.type === 'heading_open' && t.tag === 'h1');
143
- const heading = at < 0 ? '' : headingText(titleParser.renderer.render(tokens.slice(at, at + 3), titleParser.options, env));
144
- const yaml = frontMatterOf(markdown)?.yaml ?? '';
145
- const title = trimSpaceTab(yaml.match(/^title:(.+)$/m)?.[1] ?? '').replace(/^(["'])(.*)\1$/, '$2').trim();
146
- return heading || title || fallback;
196
+ // Before the first h1 or raw HTML, a render has no h1 and leaves no tag open, so it can't change what
197
+ // headingText finds: start there. Render in pieces, each ending at a token that may close an h1. No token
198
+ // that ends a piece looks at the next, and none that starts one looks back, so the pieces' text joins as
199
+ // one render's would. Look for the h1 again only once the HTML has doubled, so a document full of </h1 in
200
+ // comments takes linear time; a longer render finds the same first h1.
201
+ const start = tokens.findIndex((t) => (t.type === 'heading_open' && t.tag === 'h1') || rawHtml(t));
202
+ let heading;
203
+ let html = '';
204
+ let scanned = -1;
205
+ for (let from = start, end = start; start >= 0 && end < tokens.length && heading === undefined; end++) {
206
+ const t = tokens[end];
207
+ const last = end === tokens.length - 1;
208
+ if (!last && !(t.type === 'heading_close' && t.tag === 'h1') && !rawHtml(t, /<\/h1/i)) continue;
209
+ html += titleParser.renderer.render(tokens.slice(from, end + 1), titleParser.options, env);
210
+ from = end + 1;
211
+ if (last || html.length >= 2 * scanned) {
212
+ scanned = html.length;
213
+ heading = firstHeading(html);
214
+ }
215
+ }
216
+ return heading || yamlTitle(frontMatterOf(withoutByteOrderMark(markdown))?.yaml ?? '') || fallback;
147
217
  }
148
218
 
149
219
  // A quoted CSS string, safe inside a <style> element.
150
220
  export const cssString = (s) =>
151
221
  `"${s.replace(/[\\"]/g, '\\$&').replace(/[\0-\x1f\x7f<]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `)}"`;
152
222
 
153
- // The text of the first <h1> in rendered HTML, or '' if there is none.
223
+ const TEX = /<annotation encoding="application\/x-tex">([^<]*)<\/annotation>/;
224
+
225
+ // `html` with each formula in <eq> or <eqn> as its TeX between $ or $$, taken from KaTeX's MathML. A
226
+ // formula without it, such as one that failed to render, is left as it is.
227
+ function formulasAsTex(html) {
228
+ for (const [tag, dollars] of [['eq', '$'], ['eqn', '$$']]) {
229
+ const parts = html.split(`</${tag}>`);
230
+ html = parts
231
+ .map((part, i) => {
232
+ if (i === parts.length - 1) return part;
233
+ const at = part.lastIndexOf(`<${tag}>`);
234
+ const tex = at < 0 ? undefined : part.slice(at).match(TEX)?.[1];
235
+ return tex === undefined ? `${part}</${tag}>` : `${part.slice(0, at)}${dollars}${tex}${dollars}`;
236
+ })
237
+ .join('');
238
+ }
239
+ return html;
240
+ }
241
+
242
+ // A comment, or a tag whose > may sit in a quoted attribute value; a quote opens a value only after =. Every
243
+ // alternative matches once it starts, so a scan never backs up, and an unclosed comment, tag or quote runs
244
+ // to the end, as in a browser.
245
+ const TAG = /<!--(?:-?>|[\s\S]*?(?:-->|$))|<[a-zA-Z/!?](?:[^>=]|=[\t\n\f\r ]*(?:"[^"]*(?:"|$)|'[^']*(?:'|$))?)*>?/g;
246
+ const H1_OPEN = /^<h1[\t\n\f\r />]/i;
247
+ const H1_CLOSE = /^<\/h1[\t\n\f\r />]/i;
248
+
249
+ // The text of the first <h1> in rendered HTML, as a browser shows it, or undefined if no <h1> is closed. Raw
250
+ // HTML can write the h1 in any case, inside a comment or with entities. A formula in it shows as its TeX.
251
+ function firstHeading(html) {
252
+ let start = -1;
253
+ TAG.lastIndex = 0;
254
+ for (let tag; (tag = TAG.exec(html)); ) {
255
+ if (start < 0) {
256
+ if (H1_OPEN.test(tag[0])) start = TAG.lastIndex;
257
+ } else if (H1_CLOSE.test(tag[0])) {
258
+ return decodeHTML(formulasAsTex(html.slice(start, tag.index)).replace(TAG, '')).trim();
259
+ }
260
+ }
261
+ return undefined;
262
+ }
263
+
264
+ // The text of the first <h1> in rendered HTML, as a browser shows it, or '' if there is none.
154
265
  export function headingText(html) {
155
- const inner = html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/)?.[1] ?? '';
156
- const text = inner.replace(/<[^>]*>/g, '');
157
- return text.replace(/&(lt|gt|quot|amp);/g, (_, e) => ({ lt: '<', gt: '>', quot: '"', amp: '&' })[e]).trim();
266
+ return firstHeading(html) ?? '';
267
+ }
268
+
269
+ export { isPageSize };
270
+
271
+ // The value in a pageSize error: quoted and cut short, with < > & and everything outside printable ASCII
272
+ // escaped too, for a host that shows the message as HTML or writes it to a log or a terminal.
273
+ function describe(value) {
274
+ if (value === null) return 'null';
275
+ if (typeof value !== 'string') return `${/^[aeiou]/.test(typeof value) ? 'an' : 'a'} ${typeof value}`;
276
+ const text = JSON.stringify(value.length > 80 ? `${value.slice(0, 80)}…` : value);
277
+ return text.replace(/[^\x20-\x7e…]|[<>&]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
158
278
  }
159
279
 
160
280
  // A complete printable HTML document. `css` is the style's on-screen stylesheet followed by its print
161
- // stylesheet.
281
+ // stylesheet, written as given but for a \ before the / of each </style, in any case: the same in CSS, and
282
+ // it can't end the element. `head` and `bodyHtml` are written as given. `pageSize` must pass isPageSize, or this throws.
162
283
  // Styles can show the first heading in a running header with `content: var(--document-title)`.
163
284
  export function buildDocument({ bodyHtml, title, css, pageSize = 'Letter', head = '' }) {
285
+ if (!isPageSize(pageSize)) {
286
+ throw new TypeError(
287
+ `buildDocument: pageSize ${describe(pageSize)} isn't a page size. Use auto, portrait or landscape, a paper name (${PAPER.join(', ')}) alone or with portrait or landscape, or one or two lengths such as "5in 8in"`,
288
+ );
289
+ }
164
290
  return `<!DOCTYPE html>
165
291
  <html lang="en">
166
292
  <head>
@@ -168,7 +294,7 @@ export function buildDocument({ bodyHtml, title, css, pageSize = 'Letter', head
168
294
  <title>${escapeHtml(title)}</title>
169
295
  ${head}
170
296
  <style>
171
- ${css}
297
+ ${String(css).replace(/<\/(style)/gi, '<\\/$1')}
172
298
  @page { size: ${pageSize}; }
173
299
  :root { --document-title: ${cssString(headingText(bodyHtml))}; }
174
300
  </style>
@@ -0,0 +1,32 @@
1
+ // markdown-it's typographic replacements without (c), (r) and (tm), which it turns into ©, ® and ™ wherever
2
+ // they stand: the last of "(a) (b) (c)", "Rule 12(c)", "f(r)". Its one option, typographer, covers them
3
+ // together with the dashes, the ellipsis and ±, so this is its `replacements` rule (15.0.2) with the rest.
4
+
5
+ const RARE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
6
+
7
+ export default function typography(md) {
8
+ md.core.ruler.at('replacements', (state) => {
9
+ if (!state.md.options.typographer) return;
10
+ for (const block of state.tokens) {
11
+ if (block.type !== 'inline' || !RARE.test(block.content)) continue;
12
+ let insideAutolink = 0;
13
+ for (let i = block.children.length - 1; i >= 0; i--) {
14
+ const token = block.children[i];
15
+ if (token.type === 'text' && !insideAutolink && RARE.test(token.content)) {
16
+ token.content = token.content
17
+ .replace(/\+-/g, '±')
18
+ // .., ..., ....... -> …, but ?..... and !..... -> ?.. and !..
19
+ .replace(/\.{2,}/g, '…')
20
+ .replace(/([?!])…/g, '$1..')
21
+ .replace(/([?!]){4,}/g, '$1$1$1')
22
+ .replace(/,{2,}/g, ',')
23
+ .replace(/(^|[^-])---(?=[^-]|$)/gm, '$1—')
24
+ .replace(/(^|\s)--(?=\s|$)/gm, '$1–')
25
+ .replace(/(^|[^-\s])--(?=[^-\s]|$)/gm, '$1–');
26
+ }
27
+ if (token.type === 'link_open' && token.info === 'auto') insideAutolink--;
28
+ if (token.type === 'link_close' && token.info === 'auto') insideAutolink++;
29
+ }
30
+ }
31
+ });
32
+ }