@threepenny/md2pdf 2.1.2 → 2.2.3
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/README.md +9 -9
- package/lib/callouts.js +39 -11
- package/lib/footnotes.js +131 -0
- package/lib/ids.js +45 -0
- package/lib/math.js +307 -0
- package/lib/render.js +70 -33
- package/lib/scan.js +19 -0
- package/lib/tasklists.js +44 -0
- package/lib/wikilinks.js +11 -6
- package/package.json +3 -4
package/README.md
CHANGED
|
@@ -122,12 +122,12 @@ A style that [bundles fonts](#adding-a-style) loads them relative to its stylesh
|
|
|
122
122
|
|
|
123
123
|
| Export | What it is |
|
|
124
124
|
| ------ | ---------- |
|
|
125
|
-
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html? })`, `buildDocument(...)`, `titleOf(markdown, fallback)` (the first `#` heading's text as it renders, without Markdown syntax, else the front matter's `title:`, else the fallback), `escapeHtml(s)`, `cssString(s)`, `headingText(html)` |
|
|
125
|
+
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument(...)`, `titleOf(markdown, fallback)` (the first `#` heading's text as it renders, without Markdown syntax, else the front matter's `title:`, else the fallback), `escapeHtml(s)`, `cssString(s)`, `headingText(html)` |
|
|
126
126
|
| `@threepenny/md2pdf/styles` | `pageMargins`: each style's `@page` margin at default spacing, e.g. `pageMargins.classic` is `'1in 1.1in 0.9in'` |
|
|
127
127
|
| `@threepenny/md2pdf/styles/<name>.css` | Each style's on-screen look, scoped to `.markdown-body`. For `github`, load `github-markdown-css/github-markdown-light.css` first |
|
|
128
128
|
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers. Load it after the on-screen file, only in a page that holds nothing but the document |
|
|
129
129
|
|
|
130
|
-
`createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: {
|
|
130
|
+
`createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: { katex }` to render `\( \)`, `\[ \]`, `$` and `$$` formulas with KaTeX; formulas also need KaTeX's stylesheet, `katex/dist/katex.min.css`. (Before 2.2 it also took markdown-it-texmath, as `math: { texmath, katex }`; that still works, and texmath is ignored.) A formula over 8,000 characters, one with braces nested over 100 levels deep, or one that defines a macro (`\def`, `\newcommand`), shows as its source in red. So does a formula that would take the HTML of a document's formulas past 10,000,000 characters, and every formula after it, so that a short document can't make a page hundreds of megabytes; `math: { katex, maxHtml }` changes that budget, and `maxHtml: Infinity` removes it. Sizes such as `\rule` and `\raisebox` are capped at 30em, before a size command such as `\Huge` scales them. Raw HTML in the Markdown is passed through unless you pass `html: false`, which escapes it; page breaks (`<div class="page-break"></div>`) are raw HTML, so they then print as text. `idPrefix` starts the document's ids, as [Embedding in a web page](#embedding-in-a-web-page) describes. `highlightBudget` is how many milliseconds each render may spend highlighting code, after which the rest of the code shows without colour: 100 with `html: false`, unlimited otherwise. Under a budget, a block over 4 KB is highlighted in pieces split at line breaks where it can, so a comment or string that spans a split can be coloured wrongly.
|
|
131
131
|
|
|
132
132
|
### Variables
|
|
133
133
|
|
|
@@ -185,8 +185,9 @@ With a bundler such as Vite:
|
|
|
185
185
|
import hljs from 'highlight.js/lib/common';
|
|
186
186
|
import { createRenderer } from '@threepenny/md2pdf/render';
|
|
187
187
|
|
|
188
|
-
// html: false escapes raw HTML,
|
|
189
|
-
|
|
188
|
+
// For Markdown you didn't write yourself: html: false escapes raw HTML, and idPrefix keeps the
|
|
189
|
+
// document's ids apart from the page's.
|
|
190
|
+
const md = createRenderer({ hljs, html: false, idPrefix: 'notes-' });
|
|
190
191
|
const markdown = '# Notes\n\n> [!tip] Rendered by md2pdf\n> With **callouts**, `code` and [[wikilinks]].\n\n<b>Escaped</b>';
|
|
191
192
|
document.getElementById('rendered-notes').innerHTML = md.render(markdown);
|
|
192
193
|
</script>
|
|
@@ -198,14 +199,13 @@ A style that bundles fonts loads them from `fonts/` beside its stylesheet, so se
|
|
|
198
199
|
|
|
199
200
|
Set the [variables](#variables) on the `.markdown-body` element itself, with any selector or inline (`<article class="markdown-body" style="--md2pdf-font-size: 10pt">`). The style declares its defaults with no specificity, so your rule wins wherever it appears. A value set on `:root` or another element around the document doesn't reach it. One page can hold several documents in the same style, each with its own overrides, but not two different styles.
|
|
200
201
|
|
|
201
|
-
The document paints its own background, so on a page that isn't white, give it some padding. Your page's own CSS still applies inside the document, for whatever the style doesn't set: a global `strong { color: #c00 }` reddens bold text in the document too. A highlight.js theme on your page is the exception: the styles keep it out of the document's code blocks. Headings get ids from their text (`# Notes` becomes `id="notes"`) so `[[#Notes]]` links work,
|
|
202
|
+
The document paints its own background, so on a page that isn't white, give it some padding. Your page's own CSS still applies inside the document, for whatever the style doesn't set: a global `strong { color: #c00 }` reddens bold text in the document too. A highlight.js theme on your page is the exception: the styles keep it out of the document's code blocks. Headings get ids from their text (`# Notes` becomes `id="notes"`) so `[[#Notes]]` links work. Pass `idPrefix`, letters, digits, `_` and `-` starting with a letter and ending in `-`, to start every heading and footnote id with it, and every link to a `#` in the document: with `idPrefix: 'notes-'`, `# Notes` becomes `id="notes-notes"` and `[see](#notes)` links to it. Then no heading takes an id your page uses, as long as none of your page's ids start with the prefix, and two documents on one page don't share ids, as long as neither's prefix starts the other's (`a-` and `a-b-` would). Without it, give your own elements ids that a heading won't produce. Links in raw HTML, which only `html: true` lets through, aren't rewritten.
|
|
202
203
|
|
|
203
|
-
For Markdown you didn't write, render with `html: false` and
|
|
204
|
+
For Markdown you didn't write, render with `html: false` and an `idPrefix`, as in the example above. `html: false` escapes raw HTML, so the output has no scripts, event handlers, forms or style elements of the author's, and markdown-it refuses `javascript:`, `vbscript:`, `file:` and non-image `data:` URLs in links and images. The prefix keeps the document's ids from shadowing your page's globals (`# config` would otherwise give `id="config"`, which a browser exposes as `window.config`) or its own ids. Documents built to be slow to parse, such as thousands of identical headings, unclosed `[[` or unclosed formulas, render in about the time markdown-it itself takes. Code built to be slow to highlight is cut off by `highlightBudget`, which `html: false` sets to 100 ms: a render spends about that long highlighting, plus the 4 KB piece in progress, and shows the rest of the code without colour. A sanitizer such as DOMPurify is still worth running as a second line of defence. What's left to your page:
|
|
204
205
|
|
|
205
|
-
-
|
|
206
|
-
- Headings become element ids (`# config` gives `id="config"`), which can shadow globals or ids your own scripts rely on.
|
|
206
|
+
- Limit the size of documents you accept. Without math the HTML can be about 23 times the size of the Markdown, for a document of nothing but callouts (only a document's first 200 callouts draw an icon, and only its first 1,000 inline footnotes `^[…]` become footnotes; the rest print as text). With math, the formulas' HTML stops at 10,000,000 characters (`maxHtml`), and the formulas after that show as their source.
|
|
207
207
|
- Images load from any URL the author chooses. A Content Security Policy's `img-src` limits that.
|
|
208
|
-
- With math
|
|
208
|
+
- With math, a formula can still draw outside the document: sizes are capped, but a negative space such as `\kern{-300em}` isn't. Clip the element you render into with `contain: paint`, which also clips absolutely positioned content that `overflow: hidden` can let through.
|
|
209
209
|
|
|
210
210
|
# Development
|
|
211
211
|
|
package/lib/callouts.js
CHANGED
|
@@ -26,24 +26,42 @@ const ICONS = {
|
|
|
26
26
|
quote: 'M1.75 2.5h10.5a.75.75 0 0 1 0 1.5H1.75a.75.75 0 0 1 0-1.5Zm4 5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5Zm0 5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5ZM2.5 7.75v6a.75.75 0 0 1-1.5 0v-6a.75.75 0 0 1 1.5 0Z',
|
|
27
27
|
};
|
|
28
28
|
|
|
29
|
-
// `[!type]`, an optional fold marker, then an optional title, on the blockquote's first line.
|
|
30
|
-
|
|
29
|
+
// `[!type]`, an optional fold marker, then an optional title, on the blockquote's first line. [^] rather
|
|
30
|
+
// than ., so a line separator in the title can't make the [ \t]+ before it backtrack; a first line with
|
|
31
|
+
// one isn't a marker, as before.
|
|
32
|
+
const MARKER = /^\[!([\w-]+)\][+-]?(?:[ \t]+([^]*))?$/;
|
|
33
|
+
const LINE_SEPARATOR = /\p{Zl}|\p{Zp}/u;
|
|
34
|
+
|
|
35
|
+
// Each icon is about 1 KB, so only the first callouts of a document draw one: after that the title keeps
|
|
36
|
+
// an empty svg, and its place, but no icon. Otherwise a few characters per callout become a kilobyte.
|
|
37
|
+
const MAX_ICONS = 200;
|
|
31
38
|
|
|
32
39
|
export default function callouts(md) {
|
|
33
40
|
// Runs before inline parsing, so the title can be given its own inline token and still get Markdown.
|
|
34
41
|
md.core.ruler.before('inline', 'callouts', (state) => {
|
|
35
42
|
const tokens = state.tokens;
|
|
43
|
+
// Each blockquote's close, found in one pass rather than by searching ahead from every callout.
|
|
44
|
+
const closeOf = new Map();
|
|
45
|
+
const opens = [];
|
|
46
|
+
for (const t of tokens) {
|
|
47
|
+
if (t.type === 'blockquote_open') opens.push(t);
|
|
48
|
+
else if (t.type === 'blockquote_close') closeOf.set(opens.pop(), t);
|
|
49
|
+
}
|
|
50
|
+
// A new list, since splicing titles into this one would copy it once per callout.
|
|
51
|
+
const out = [];
|
|
36
52
|
for (let i = 0; i < tokens.length; i++) {
|
|
37
53
|
const open = tokens[i];
|
|
54
|
+
out.push(open);
|
|
38
55
|
if (open.type !== 'blockquote_open' || tokens[i + 1]?.type !== 'paragraph_open') continue;
|
|
39
56
|
const inline = tokens[i + 2];
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
|
|
57
|
+
const lineEnd = inline.content.indexOf('\n');
|
|
58
|
+
const firstLine = lineEnd < 0 ? inline.content : inline.content.slice(0, lineEnd);
|
|
59
|
+
const marker = firstLine.match(MARKER);
|
|
60
|
+
if (!marker || LINE_SEPARATOR.test(firstLine)) continue;
|
|
43
61
|
|
|
44
62
|
const type = marker[1].toLowerCase();
|
|
45
|
-
const family = FAMILY_OF[type]
|
|
46
|
-
const close =
|
|
63
|
+
const family = Object.hasOwn(FAMILY_OF, type) ? FAMILY_OF[type] : 'note';
|
|
64
|
+
const close = closeOf.get(open);
|
|
47
65
|
open.tag = close.tag = 'div';
|
|
48
66
|
open.attrSet('class', `markdown-alert markdown-alert-${family}`);
|
|
49
67
|
open.attrSet('data-callout', type);
|
|
@@ -59,15 +77,25 @@ export default function callouts(md) {
|
|
|
59
77
|
t.level = open.level + (t.type === 'inline' ? 2 : 1);
|
|
60
78
|
t.map = inline.map && [inline.map[0], inline.map[0] + 1];
|
|
61
79
|
}
|
|
80
|
+
out.push(titleOpen, title, titleClose);
|
|
62
81
|
|
|
63
82
|
// The rest of the first paragraph is the body; a callout with only a title has none.
|
|
64
|
-
inline.content =
|
|
83
|
+
inline.content = lineEnd < 0 ? '' : inline.content.slice(lineEnd + 1);
|
|
65
84
|
if (inline.map) tokens[i + 1].map = inline.map = [inline.map[0] + 1, inline.map[1]];
|
|
66
|
-
|
|
85
|
+
if (!inline.content) i += 3;
|
|
67
86
|
}
|
|
87
|
+
state.tokens = out;
|
|
68
88
|
});
|
|
69
89
|
|
|
70
|
-
|
|
71
|
-
|
|
90
|
+
let icons;
|
|
91
|
+
const render = md.renderer.render;
|
|
92
|
+
md.renderer.render = function (...args) {
|
|
93
|
+
icons = 0;
|
|
94
|
+
return render.apply(this, args);
|
|
95
|
+
};
|
|
96
|
+
md.renderer.rules.callout_title_open = (tokens, idx) => {
|
|
97
|
+
const path = icons++ < MAX_ICONS ? `<path d="${ICONS[tokens[idx].meta.family]}"></path>` : '';
|
|
98
|
+
return `<p class="markdown-alert-title"><svg class="octicon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true">${path}</svg>`;
|
|
99
|
+
};
|
|
72
100
|
md.renderer.rules.callout_title_close = () => '</p>\n';
|
|
73
101
|
}
|
package/lib/footnotes.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Changes to markdown-it-footnote 4. Two of its rules take quadratic time, and these are the same rules
|
|
2
|
+
// made linear: footnote_tail, which moves footnotes to the end of the document, copied the whole token
|
|
3
|
+
// list once per footnote, and footnote_ref searched for the end of a [^label] from every [^ in a run of
|
|
4
|
+
// them. With an id prefix, footnote ids start with it, and a colon after `fn` keeps them apart from
|
|
5
|
+
// heading ids, which have none: `# fn1` would otherwise share the first footnote's id.
|
|
6
|
+
|
|
7
|
+
import { first } from './scan.js';
|
|
8
|
+
|
|
9
|
+
// Each inline note ^[…] becomes a reference, a list item and a back-link, about 70 times the three
|
|
10
|
+
// characters of an empty one, so a document gets this many; the rest stay text.
|
|
11
|
+
const MAX_INLINE = 1000;
|
|
12
|
+
|
|
13
|
+
export default function footnotes(md, { idPrefix = '' }) {
|
|
14
|
+
const inline = md.inline.ruler.__rules__.find((r) => r.name === 'footnote_inline')?.fn;
|
|
15
|
+
if (!inline) throw new Error('markdown-it-footnote has no footnote_inline rule to limit');
|
|
16
|
+
md.inline.ruler.at('footnote_inline', (state, silent) => {
|
|
17
|
+
if (state.env.md2pdfInlineNotes >= MAX_INLINE) return false;
|
|
18
|
+
if (!inline(state, silent)) return false;
|
|
19
|
+
if (!silent) state.env.md2pdfInlineNotes = (state.env.md2pdfInlineNotes ?? 0) + 1;
|
|
20
|
+
return true;
|
|
21
|
+
});
|
|
22
|
+
md.core.ruler.at('footnote_tail', footnoteTail);
|
|
23
|
+
md.inline.ruler.at('footnote_ref', footnoteRef);
|
|
24
|
+
if (!idPrefix) return;
|
|
25
|
+
|
|
26
|
+
const { rules } = md.renderer;
|
|
27
|
+
const name = (tokens, idx, options, env, slf) => {
|
|
28
|
+
const id = slf.rules.footnote_anchor_name(tokens, idx, options, env, slf);
|
|
29
|
+
return tokens[idx].meta.subId > 0 ? [id, `${id}:${tokens[idx].meta.subId}`] : [id, id];
|
|
30
|
+
};
|
|
31
|
+
rules.footnote_ref = (tokens, idx, options, env, slf) => {
|
|
32
|
+
const [id, refId] = name(tokens, idx, options, env, slf);
|
|
33
|
+
const caption = slf.rules.footnote_caption(tokens, idx, options, env, slf);
|
|
34
|
+
return `<sup class="footnote-ref"><a href="#${idPrefix}fn:${id}" id="${idPrefix}fnref:${refId}">${caption}</a></sup>`;
|
|
35
|
+
};
|
|
36
|
+
rules.footnote_open = (tokens, idx, options, env, slf) =>
|
|
37
|
+
`<li id="${idPrefix}fn:${name(tokens, idx, options, env, slf)[1]}" class="footnote-item">`;
|
|
38
|
+
rules.footnote_anchor = (tokens, idx, options, env, slf) =>
|
|
39
|
+
` <a href="#${idPrefix}fnref:${name(tokens, idx, options, env, slf)[1]}" class="footnote-backref">↩︎</a>`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function footnoteTail(state) {
|
|
43
|
+
if (!state.env.footnotes) return;
|
|
44
|
+
const refTokens = {};
|
|
45
|
+
let current;
|
|
46
|
+
let label;
|
|
47
|
+
let insideRef = false;
|
|
48
|
+
state.tokens = state.tokens.filter((tok) => {
|
|
49
|
+
if (tok.type === 'footnote_reference_open') {
|
|
50
|
+
insideRef = true;
|
|
51
|
+
current = [];
|
|
52
|
+
label = tok.meta.label;
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
if (tok.type === 'footnote_reference_close') {
|
|
56
|
+
insideRef = false;
|
|
57
|
+
// ':' keeps labels apart from Object.prototype's members.
|
|
58
|
+
refTokens[`:${label}`] = current;
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
if (insideRef) current.push(tok);
|
|
62
|
+
return !insideRef;
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const list = state.env.footnotes.list;
|
|
66
|
+
if (!list) return;
|
|
67
|
+
const out = state.tokens;
|
|
68
|
+
out.push(new state.Token('footnote_block_open', '', 1));
|
|
69
|
+
let tokens;
|
|
70
|
+
for (let i = 0; i < list.length; i++) {
|
|
71
|
+
const open = new state.Token('footnote_open', '', 1);
|
|
72
|
+
open.meta = { id: i, label: list[i].label };
|
|
73
|
+
out.push(open);
|
|
74
|
+
|
|
75
|
+
if (list[i].tokens) {
|
|
76
|
+
const paragraphOpen = new state.Token('paragraph_open', 'p', 1);
|
|
77
|
+
paragraphOpen.block = true;
|
|
78
|
+
const inline = new state.Token('inline', '', 0);
|
|
79
|
+
inline.children = list[i].tokens;
|
|
80
|
+
inline.content = list[i].content;
|
|
81
|
+
const paragraphClose = new state.Token('paragraph_close', 'p', -1);
|
|
82
|
+
paragraphClose.block = true;
|
|
83
|
+
tokens = [paragraphOpen, inline, paragraphClose];
|
|
84
|
+
} else if (list[i].label) {
|
|
85
|
+
tokens = refTokens[`:${list[i].label}`];
|
|
86
|
+
}
|
|
87
|
+
// As in the original, a footnote that has neither repeats the previous one's tokens.
|
|
88
|
+
if (tokens) for (const t of tokens) out.push(t);
|
|
89
|
+
|
|
90
|
+
const lastParagraph = out[out.length - 1].type === 'paragraph_close' ? out.pop() : null;
|
|
91
|
+
const count = list[i].count > 0 ? list[i].count : 1;
|
|
92
|
+
for (let j = 0; j < count; j++) {
|
|
93
|
+
const anchor = new state.Token('footnote_anchor', '', 0);
|
|
94
|
+
anchor.meta = { id: i, subId: j, label: list[i].label };
|
|
95
|
+
out.push(anchor);
|
|
96
|
+
}
|
|
97
|
+
if (lastParagraph) out.push(lastParagraph);
|
|
98
|
+
out.push(new state.Token('footnote_close', '', -1));
|
|
99
|
+
}
|
|
100
|
+
out.push(new state.Token('footnote_block_close', '', -1));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// A label ends at the first ], and can't hold a space or a line break.
|
|
104
|
+
const labelStop = (s, i) => s[i] === ']' || s[i] === ' ' || s[i] === '\n';
|
|
105
|
+
|
|
106
|
+
function footnoteRef(state, silent) {
|
|
107
|
+
const { src, posMax: max, pos: start } = state;
|
|
108
|
+
if (start + 3 > max) return false;
|
|
109
|
+
const footnotes = state.env.footnotes;
|
|
110
|
+
if (!footnotes?.refs || src.charCodeAt(start) !== 0x5b /* [ */ || src.charCodeAt(start + 1) !== 0x5e /* ^ */) return false;
|
|
111
|
+
const end = first(state, labelStop, start + 2);
|
|
112
|
+
if (end < 0 || end >= max || src[end] !== ']' || end === start + 2) return false;
|
|
113
|
+
|
|
114
|
+
const label = src.slice(start + 2, end);
|
|
115
|
+
if (typeof footnotes.refs[`:${label}`] === 'undefined') return false;
|
|
116
|
+
if (!silent) {
|
|
117
|
+
footnotes.list ??= [];
|
|
118
|
+
let id = footnotes.refs[`:${label}`];
|
|
119
|
+
if (id < 0) {
|
|
120
|
+
id = footnotes.list.length;
|
|
121
|
+
footnotes.list[id] = { label, count: 0 };
|
|
122
|
+
footnotes.refs[`:${label}`] = id;
|
|
123
|
+
}
|
|
124
|
+
const subId = footnotes.list[id].count++;
|
|
125
|
+
const token = state.push('footnote_ref', '', 0);
|
|
126
|
+
token.meta = { id, subId, label };
|
|
127
|
+
}
|
|
128
|
+
state.pos = end + 1;
|
|
129
|
+
state.posMax = max;
|
|
130
|
+
return true;
|
|
131
|
+
}
|
package/lib/ids.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Heading ids, as markdown-it-anchor 10 gives them with tabindex="-1": the heading's text slugged, and a
|
|
2
|
+
// repeated slug numbered -1, -2 and so on. markdown-it-anchor counts up from 1 for every repeat, which
|
|
3
|
+
// takes quadratic time on a document of identical headings; this remembers where each count got to.
|
|
4
|
+
//
|
|
5
|
+
// With an id prefix, heading and footnote ids start with it, and so does every link to a #fragment in the
|
|
6
|
+
// document, so links still find their targets and two documents on one page don't share ids.
|
|
7
|
+
|
|
8
|
+
export const ID_PREFIX = /^[A-Za-z][\w-]*-$/;
|
|
9
|
+
|
|
10
|
+
export default function ids(md, { slugify, idPrefix = '' }) {
|
|
11
|
+
md.core.ruler.push('heading_ids', (state) => {
|
|
12
|
+
const env = (state.env.md2pdfIds ??= { used: new Set(), next: new Map() });
|
|
13
|
+
for (let i = 0; i < state.tokens.length; i++) {
|
|
14
|
+
const token = state.tokens[i];
|
|
15
|
+
if (token.type !== 'heading_open') continue;
|
|
16
|
+
const text = state.tokens[i + 1].children
|
|
17
|
+
.filter((t) => t.type === 'text' || t.type === 'code_inline')
|
|
18
|
+
.map((t) => t.content)
|
|
19
|
+
.join('');
|
|
20
|
+
const slug = slugify(text);
|
|
21
|
+
let id = slug;
|
|
22
|
+
if (env.used.has(id)) {
|
|
23
|
+
let n = env.next.get(slug) ?? 1;
|
|
24
|
+
while (env.used.has(`${slug}-${n}`)) n++;
|
|
25
|
+
id = `${slug}-${n}`;
|
|
26
|
+
env.next.set(slug, n + 1);
|
|
27
|
+
}
|
|
28
|
+
env.used.add(id);
|
|
29
|
+
token.attrSet('id', idPrefix + id);
|
|
30
|
+
token.attrSet('tabindex', '-1');
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
if (!idPrefix) return;
|
|
35
|
+
// Pushed after footnote_tail has moved footnotes to the end, so links inside them are rewritten too.
|
|
36
|
+
md.core.ruler.push('id_prefix_links', (state) => {
|
|
37
|
+
for (const token of state.tokens) {
|
|
38
|
+
for (const child of token.children ?? []) {
|
|
39
|
+
if (child.type !== 'link_open') continue;
|
|
40
|
+
const href = child.attrGet('href');
|
|
41
|
+
if (href?.startsWith('#') && href.length > 1) child.attrSet('href', `#${idPrefix}${href.slice(1)}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
package/lib/math.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
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
|
|
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.
|
|
8
|
+
|
|
9
|
+
import { first, nextWhere } from './scan.js';
|
|
10
|
+
|
|
11
|
+
const MAX_LENGTH = 8000;
|
|
12
|
+
// How deep braces may nest. KaTeX recurses once per level and overflows its stack at a few hundred, which
|
|
13
|
+
// takes it milliseconds per formula; a document of formulas that all do so takes seconds.
|
|
14
|
+
const MAX_DEPTH = 100;
|
|
15
|
+
// Macro definitions are refused: a few hundred bytes of nested definitions expand to minutes of work. So is
|
|
16
|
+
// a line break before the word (\\def), since counting backslashes can't tell where KaTeX's tokens end:
|
|
17
|
+
// \verb\a\ ends at its second backslash.
|
|
18
|
+
const DEFINITION = /\\(?:[egx]?def|let|futurelet|global|long|(?:re|provide)?newcommand)(?![a-zA-Z])/;
|
|
19
|
+
// Caps how far a formula can reach (\rule, \raisebox, \hspace). Negative sizes aren't capped.
|
|
20
|
+
const MAX_SIZE = 30;
|
|
21
|
+
// 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
|
+
const MAX_HTML = 10_000_000;
|
|
25
|
+
|
|
26
|
+
// How deeply {…} nest in `tex`, not counting a brace after a backslash.
|
|
27
|
+
function braceDepth(tex) {
|
|
28
|
+
let depth = 0;
|
|
29
|
+
let max = 0;
|
|
30
|
+
for (let i = 0; i < tex.length; i++) {
|
|
31
|
+
const c = tex[i];
|
|
32
|
+
if (c === '\\') i++;
|
|
33
|
+
else if (c === '{') max = Math.max(max, ++depth);
|
|
34
|
+
else if (c === '}' && depth > 0) depth--;
|
|
35
|
+
}
|
|
36
|
+
return max;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const SPACE = /\s/;
|
|
40
|
+
const isBreak = (c) => c === '\n' || c === '\r' || c === '\u2028' || c === '\u2029';
|
|
41
|
+
|
|
42
|
+
const escapeHtml = (s) =>
|
|
43
|
+
s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
44
|
+
|
|
45
|
+
const closeParen = (s, i) => s.startsWith('\\)', i);
|
|
46
|
+
const openBracket = (s, i) => s.startsWith('\\[', i);
|
|
47
|
+
const closeBracket = (s, i) => s.startsWith('\\]', i);
|
|
48
|
+
const dollar = (s, i) => s[i] === '$';
|
|
49
|
+
// A $ that can close an inline formula: not after a space or a backslash.
|
|
50
|
+
const dollarCloser = (s, i) => s[i] === '$' && i > 0 && !SPACE.test(s[i - 1]) && s[i - 1] !== '\\';
|
|
51
|
+
const lineBreak = (s, i) => isBreak(s[i]);
|
|
52
|
+
const nonSpace = (s, i) => !SPACE.test(s[i]);
|
|
53
|
+
const bracketNumberStop = (s, i) => ')$\r\n'.includes(s[i]);
|
|
54
|
+
const dollarNumberStop = (s, i) => s[i] === ')' || SPACE.test(s[i]);
|
|
55
|
+
|
|
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
|
+
// texmath's own test for $$ inside a paragraph, which outerSpace doesn't reach: no backslash or digit
|
|
61
|
+
// before the opening $$, and no digit after the closing one.
|
|
62
|
+
const isDigit = (c) => c >= '0' && c <= '9';
|
|
63
|
+
const doublePre = (src, at) => at === 0 || (src[at - 1] !== '\\' && !isDigit(src[at - 1]));
|
|
64
|
+
const doublePost = (src, at) => !isDigit(src[at + 1] ?? '');
|
|
65
|
+
|
|
66
|
+
// The ways $$…$$ can close after the $$ at `at`, in texmath's order: \$\$([^$]*?[^\\])\$\$.
|
|
67
|
+
function* doubleDollar(state, at) {
|
|
68
|
+
const { src } = state;
|
|
69
|
+
const d = first(state, dollar, at + 2);
|
|
70
|
+
if (d < 0) return;
|
|
71
|
+
if (d - 1 >= at + 2 && src[d - 1] !== '\\' && src[d + 1] === '$') yield { content: src.slice(at + 2, d), end: d + 2 };
|
|
72
|
+
if (src[d + 1] === '$' && src[d + 2] === '$') yield { content: src.slice(at + 2, d + 1), end: d + 3 };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// $…$ from `at`, as texmath's \$((?:[^\s\\])|(?:\S.*?[^\s\\]))\$ matches it, or null.
|
|
76
|
+
function singleDollar(state, at) {
|
|
77
|
+
const { src } = state;
|
|
78
|
+
const c = src[at + 1];
|
|
79
|
+
if (c === undefined || SPACE.test(c)) return null;
|
|
80
|
+
if (c !== '\\' && src[at + 2] === '$') return { content: c, end: at + 3 };
|
|
81
|
+
const close = first(state, dollarCloser, at + 2);
|
|
82
|
+
if (close < 0) return null;
|
|
83
|
+
const br = first(state, lineBreak, at + 2);
|
|
84
|
+
if (br >= 0 && br < close) return null;
|
|
85
|
+
return { content: src.slice(at + 1, close), end: close + 1 };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// \(…\) from `at`, as \\\((.+?)\\\) matches it, or null.
|
|
89
|
+
function parens(state, at) {
|
|
90
|
+
const close = first(state, closeParen, at + 3);
|
|
91
|
+
if (close < 0) return null;
|
|
92
|
+
const br = first(state, lineBreak, at + 2);
|
|
93
|
+
if (br >= 0 && br < close) return null;
|
|
94
|
+
return { content: state.src.slice(at + 2, close), end: close + 2 };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function inline(state, silent) {
|
|
98
|
+
const { src, pos } = state;
|
|
99
|
+
let type;
|
|
100
|
+
let match;
|
|
101
|
+
if (src.startsWith('\\(', pos)) {
|
|
102
|
+
type = 'math_inline';
|
|
103
|
+
match = parens(state, pos);
|
|
104
|
+
} else if (src[pos] === '$') {
|
|
105
|
+
// texmath's order: $$ then $ with md2pdf's outer tests, then $$ with texmath's own.
|
|
106
|
+
const double = src[pos + 1] === '$' ? doubleDollar(state, pos).next().value : null;
|
|
107
|
+
const outer = dollarPre(src, pos);
|
|
108
|
+
if (outer && double && dollarPost(src, double.end - 1)) {
|
|
109
|
+
[type, match] = ['math_inline_double', double];
|
|
110
|
+
} else if (outer && (match = singleDollar(state, pos)) && dollarPost(src, match.end - 1)) {
|
|
111
|
+
type = 'math_inline';
|
|
112
|
+
} else if (double && doublePre(src, pos) && doublePost(src, double.end - 1)) {
|
|
113
|
+
[type, match] = ['math_inline_double', double];
|
|
114
|
+
} else {
|
|
115
|
+
match = null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (!match) return false;
|
|
119
|
+
if (!silent) {
|
|
120
|
+
const token = state.push(type, 'math', 0);
|
|
121
|
+
token.content = match.content;
|
|
122
|
+
token.markup = type === 'math_inline_double' ? '$$' : src.slice(pos, pos + (src[pos] === '$' ? 1 : 2));
|
|
123
|
+
}
|
|
124
|
+
state.pos = match.end;
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// An equation number after a displayed formula that ends at `from`: whitespace, then (number).
|
|
129
|
+
function equationNumber(state, from, stop) {
|
|
130
|
+
const open = first(state, nonSpace, from);
|
|
131
|
+
if (open < 0 || state.src[open] !== '(') return null;
|
|
132
|
+
const close = first(state, stop, open + 1);
|
|
133
|
+
if (close <= open + 1 || state.src[close] !== ')') return null;
|
|
134
|
+
return { info: state.src.slice(open + 1, close), end: close + 1 };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The first `\end{name}` at or after `from`, or -1.
|
|
138
|
+
function environmentEnd(state, name, from) {
|
|
139
|
+
if (!state.md2pdfEnds) {
|
|
140
|
+
state.md2pdfEnds = new Map();
|
|
141
|
+
for (const m of state.src.matchAll(/\\end\{([a-z]+)\}/g)) {
|
|
142
|
+
if (!state.md2pdfEnds.has(m[1])) state.md2pdfEnds.set(m[1], []);
|
|
143
|
+
state.md2pdfEnds.get(m[1]).push(m.index);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const ends = state.md2pdfEnds.get(name) ?? [];
|
|
147
|
+
let lo = 0;
|
|
148
|
+
let hi = ends.length;
|
|
149
|
+
while (lo < hi) {
|
|
150
|
+
const mid = (lo + hi) >> 1;
|
|
151
|
+
if (ends[mid] < from) lo = mid + 1;
|
|
152
|
+
else hi = mid;
|
|
153
|
+
}
|
|
154
|
+
return lo < ends.length ? ends[lo] : -1;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const BEGIN = /\\begin\{([a-z]+)\}/y;
|
|
158
|
+
|
|
159
|
+
// The displayed formula starting at `at`, trying texmath's block rules in their order, or null.
|
|
160
|
+
function displayed(state, at) {
|
|
161
|
+
const { src } = state;
|
|
162
|
+
if (src.startsWith('\\[', at)) {
|
|
163
|
+
const close = first(state, closeBracket, at + 2);
|
|
164
|
+
const open = first(state, openBracket, at + 2);
|
|
165
|
+
if (close > at + 2 && (open < 0 || open > close)) {
|
|
166
|
+
const number = equationNumber(state, close + 2, bracketNumberStop);
|
|
167
|
+
if (number) return { type: 'math_block_eqno', tag: '\\[', content: src.slice(at + 2, close), ...number };
|
|
168
|
+
}
|
|
169
|
+
const end = first(state, closeBracket, at + 3);
|
|
170
|
+
if (end >= 0) return { type: 'math_block', tag: '\\[', content: src.slice(at + 2, end), end: end + 2 };
|
|
171
|
+
}
|
|
172
|
+
if (src.startsWith('$$', at)) {
|
|
173
|
+
for (const { content, end } of doubleDollar(state, at)) {
|
|
174
|
+
const number = equationNumber(state, end, dollarNumberStop);
|
|
175
|
+
if (number) return { type: 'math_block_eqno', tag: '$$', content, ...number };
|
|
176
|
+
}
|
|
177
|
+
const match = doubleDollar(state, at).next().value;
|
|
178
|
+
if (match) return { type: 'math_block', tag: '$$', ...match };
|
|
179
|
+
}
|
|
180
|
+
if (src[at] === '\\') {
|
|
181
|
+
BEGIN.lastIndex = at;
|
|
182
|
+
const begin = BEGIN.exec(src);
|
|
183
|
+
const close = begin && environmentEnd(state, begin[1], at + begin[0].length + 1);
|
|
184
|
+
if (begin && close >= 0) {
|
|
185
|
+
const end = close + `\\end{${begin[1]}}`.length;
|
|
186
|
+
return { type: 'math_block', tag: '\\', content: src.slice(at, end), info: begin[1], end };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// texmath's content.replace(/(\n*?^(?:\s*>)+)/gm, ''), which takes the > markers off the lines of a
|
|
193
|
+
// formula in a blockquote, in one pass.
|
|
194
|
+
function unquote(s) {
|
|
195
|
+
const next = nextWhere(s, nonSpace);
|
|
196
|
+
let out = '';
|
|
197
|
+
let kept = 0;
|
|
198
|
+
for (let p = 0; p < s.length; ) {
|
|
199
|
+
let w = p === 0 || isBreak(s[p - 1]) || s[p] === '\n' ? next[p] : -1;
|
|
200
|
+
if (w < 0 || s[w] !== '>') {
|
|
201
|
+
p++;
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
while (next[w + 1] >= 0 && s[next[w + 1]] === '>') w = next[w + 1];
|
|
205
|
+
out += s.slice(kept, p);
|
|
206
|
+
kept = p = w + 1;
|
|
207
|
+
}
|
|
208
|
+
return out + s.slice(kept);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function block(state, startLine, endLine, silent) {
|
|
212
|
+
const match = displayed(state, state.bMarks[startLine] + state.tShift[startLine]);
|
|
213
|
+
const last = match ? match.end - 1 : -1;
|
|
214
|
+
// Inside a blockquote, endLine is the quote's end, for the lists and other blocks inside it too.
|
|
215
|
+
if (!match || last > state.eMarks[endLine - 1]) return false;
|
|
216
|
+
let line = startLine;
|
|
217
|
+
while (line < endLine && !(last >= state.bMarks[line] + state.tShift[line] && last <= state.eMarks[line])) line++;
|
|
218
|
+
// Text after the closing delimiter on its line was dropped with the rest of the line, by texmath too. On
|
|
219
|
+
// the formula's first line, declining leaves it to the inline rules, which keep the text beside the
|
|
220
|
+
// formula. A formula over several lines stays a block, and the text follows it as a paragraph, since the
|
|
221
|
+
// paragraph and list rules would otherwise get its lines.
|
|
222
|
+
const rest = line < endLine ? state.src.slice(match.end, state.eMarks[line]).trim() : '';
|
|
223
|
+
if (rest && line === startLine) return false;
|
|
224
|
+
if (silent) return true;
|
|
225
|
+
const token = state.push(match.type, 'math', 0);
|
|
226
|
+
token.block = true;
|
|
227
|
+
token.tag = match.tag;
|
|
228
|
+
token.markup = '';
|
|
229
|
+
token.content = state.parentType === 'blockquote' ? unquote(match.content) : match.content;
|
|
230
|
+
// texmath's info is the equation number, the environment's name, or else the formula.
|
|
231
|
+
token.info = match.info ?? token.content;
|
|
232
|
+
token.map = [startLine, line + 1];
|
|
233
|
+
state.line = line + 1;
|
|
234
|
+
if (rest) {
|
|
235
|
+
const open = state.push('paragraph_open', 'p', 1);
|
|
236
|
+
const inline = state.push('inline', '', 0);
|
|
237
|
+
inline.content = rest;
|
|
238
|
+
inline.children = [];
|
|
239
|
+
const close = state.push('paragraph_close', 'p', -1);
|
|
240
|
+
open.map = inline.map = [line, line + 1];
|
|
241
|
+
open.block = close.block = true;
|
|
242
|
+
}
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export default function math(md, { katex, maxHtml = MAX_HTML }) {
|
|
247
|
+
if (!(typeof maxHtml === 'number' && maxHtml >= 0)) {
|
|
248
|
+
throw new TypeError(`math.maxHtml must be a number of characters, 0 or more: ${String(maxHtml)}`);
|
|
249
|
+
}
|
|
250
|
+
const error = (tex, reason) =>
|
|
251
|
+
`<span class="katex-error" title="${escapeHtml(reason)}" style="color:#cc0000">${escapeHtml(tex)}</span>`;
|
|
252
|
+
const render = (tex, displayMode) => {
|
|
253
|
+
if (tex.length > MAX_LENGTH) return error(tex, `Formulas over ${MAX_LENGTH} characters aren't rendered`);
|
|
254
|
+
if (braceDepth(tex) > MAX_DEPTH) return error(tex, `Formulas nested over ${MAX_DEPTH} levels deep aren't rendered`);
|
|
255
|
+
if (DEFINITION.test(tex)) return error(tex, 'Macro definitions aren\'t supported');
|
|
256
|
+
try {
|
|
257
|
+
return katex.renderToString(tex, {
|
|
258
|
+
displayMode,
|
|
259
|
+
output: 'html',
|
|
260
|
+
throwOnError: false,
|
|
261
|
+
trust: false,
|
|
262
|
+
maxSize: MAX_SIZE,
|
|
263
|
+
maxExpand: 1000,
|
|
264
|
+
// KaTeX warns on the console about TeX that LaTeX wouldn't take, once per occurrence.
|
|
265
|
+
strict: 'ignore',
|
|
266
|
+
});
|
|
267
|
+
} catch (err) {
|
|
268
|
+
// KaTeX reports bad TeX as an error box itself; this is for its own limits, like nesting too deep.
|
|
269
|
+
return escapeHtml(`${tex}:${err.message}`);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
// The budget is spent in document order and starts again with each render. Only the first formula past it
|
|
274
|
+
// says why: the reason on each of a run of short formulas would make the HTML 40 times the Markdown.
|
|
275
|
+
let budget;
|
|
276
|
+
const budgeted = (tex, displayMode) => {
|
|
277
|
+
if (budget.used <= maxHtml) {
|
|
278
|
+
const html = render(tex, displayMode);
|
|
279
|
+
budget.used += html.length;
|
|
280
|
+
if (budget.used <= maxHtml) return html;
|
|
281
|
+
return error(tex, `The document's formulas reached their limit of ${maxHtml.toLocaleString('en-US')} characters of HTML`);
|
|
282
|
+
}
|
|
283
|
+
return `<span class="katex-error" style="color:#cc0000">${escapeHtml(tex)}</span>`;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
// Before escape, so \( isn't taken as an escaped (.
|
|
287
|
+
md.inline.ruler.before('escape', 'math_inline', inline);
|
|
288
|
+
md.block.ruler.before('fence', 'math_block', block);
|
|
289
|
+
// A render a rule starts inside another, such as a plugin's md.renderInline, spends the outer one's budget.
|
|
290
|
+
let depth = 0;
|
|
291
|
+
const withBudget = (renderTokens) =>
|
|
292
|
+
function (...args) {
|
|
293
|
+
if (depth++ === 0) budget = { used: 0 };
|
|
294
|
+
try {
|
|
295
|
+
return renderTokens.apply(this, args);
|
|
296
|
+
} finally {
|
|
297
|
+
depth--;
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
md.renderer.render = withBudget(md.renderer.render);
|
|
301
|
+
md.renderer.renderInline = withBudget(md.renderer.renderInline);
|
|
302
|
+
md.renderer.rules.math_inline = (tokens, idx) => `<eq>${budgeted(tokens[idx].content, false)}</eq>`;
|
|
303
|
+
md.renderer.rules.math_inline_double = md.renderer.rules.math_block = (tokens, idx) =>
|
|
304
|
+
`<section><eqn>${budgeted(tokens[idx].content, true)}</eqn></section>`;
|
|
305
|
+
md.renderer.rules.math_block_eqno = (tokens, idx) =>
|
|
306
|
+
`<section class="eqno"><eqn>${budgeted(tokens[idx].content, true)}</eqn><span>(${escapeHtml(tokens[idx].info)})</span></section>`;
|
|
307
|
+
}
|
package/lib/render.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// Markdown → HTML rendering shared by the CLI and the md2pdf.me website.
|
|
2
2
|
|
|
3
3
|
import MarkdownIt from 'markdown-it';
|
|
4
|
-
import anchor from 'markdown-it-anchor';
|
|
5
4
|
import footnote from 'markdown-it-footnote';
|
|
6
|
-
import taskLists from 'markdown-it-task-lists';
|
|
7
5
|
import { full as emoji } from 'markdown-it-emoji';
|
|
8
6
|
import callouts from './callouts.js';
|
|
7
|
+
import footnotes from './footnotes.js';
|
|
8
|
+
import ids, { ID_PREFIX } from './ids.js';
|
|
9
|
+
import mathRules from './math.js';
|
|
10
|
+
import taskLists from './tasklists.js';
|
|
9
11
|
import wikilinks from './wikilinks.js';
|
|
10
12
|
|
|
11
13
|
// YAML front matter: a `---` line at the very start of the document, closed by another `---` line.
|
|
@@ -45,57 +47,92 @@ const slugify = (s) => s.trim().toLowerCase().replace(/[^\w\- ]+/g, '').replace(
|
|
|
45
47
|
export const escapeHtml = (s) =>
|
|
46
48
|
s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
47
49
|
|
|
50
|
+
// highlight.js takes time that grows with the square of the length on some code, so under a budget a
|
|
51
|
+
// longer block is highlighted in pieces of this many characters.
|
|
52
|
+
const PIECE = 4096;
|
|
53
|
+
|
|
54
|
+
// `code` in pieces of at most PIECE characters, each ending at a line break where there is one, and
|
|
55
|
+
// never between the halves of a surrogate pair.
|
|
56
|
+
function pieces(code) {
|
|
57
|
+
const out = [];
|
|
58
|
+
for (let start = 0; start < code.length; ) {
|
|
59
|
+
let end = Math.min(start + PIECE, code.length);
|
|
60
|
+
if (end < code.length) {
|
|
61
|
+
const lineEnd = code.lastIndexOf('\n', end - 1);
|
|
62
|
+
if (lineEnd >= start) end = lineEnd + 1;
|
|
63
|
+
else if (/[\uD800-\uDBFF]/.test(code[end - 1])) end--;
|
|
64
|
+
}
|
|
65
|
+
out.push(code.slice(start, end));
|
|
66
|
+
start = end;
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
48
71
|
// `hljs` is passed in so the CLI can use every language while the website
|
|
49
|
-
// ships the smaller common-languages bundle. `math` ({
|
|
72
|
+
// ships the smaller common-languages bundle. `math` ({ katex, maxHtml? }) is optional:
|
|
50
73
|
// the website loads it on demand when a document contains formulas. `html: false` escapes raw HTML in
|
|
51
|
-
// the Markdown instead of passing it through
|
|
52
|
-
|
|
74
|
+
// the Markdown instead of passing it through, and `idPrefix` (letters, digits, _ and -, starting with a
|
|
75
|
+
// letter and ending in -) starts every id the document gives an element, and every link to one; use both for Markdown you didn't
|
|
76
|
+
// write. `highlightBudget` is the milliseconds each render may spend highlighting code, after which code
|
|
77
|
+
// is escaped without colour: 100 with `html: false`, otherwise unlimited.
|
|
78
|
+
export function createRenderer({ hljs, math, html = true, idPrefix = '', highlightBudget = html ? Infinity : 100 }) {
|
|
79
|
+
if (idPrefix !== '' && !(typeof idPrefix === 'string' && ID_PREFIX.test(idPrefix))) {
|
|
80
|
+
throw new TypeError(`idPrefix must be letters, digits, _ and -, starting with a letter and ending in -: ${JSON.stringify(idPrefix)}`);
|
|
81
|
+
}
|
|
82
|
+
if (!(typeof highlightBudget === 'number' && highlightBudget >= 0)) {
|
|
83
|
+
throw new TypeError(`highlightBudget must be a number of milliseconds, 0 or more: ${String(highlightBudget)}`);
|
|
84
|
+
}
|
|
85
|
+
let spent = 0;
|
|
86
|
+
const highlight = (code, language) => {
|
|
87
|
+
if (spent >= highlightBudget) return escapeHtml(code);
|
|
88
|
+
const start = performance.now();
|
|
89
|
+
const { value } = hljs.highlight(code, { language, ignoreIllegals: true });
|
|
90
|
+
spent += performance.now() - start;
|
|
91
|
+
return value;
|
|
92
|
+
};
|
|
53
93
|
const md = new MarkdownIt({
|
|
54
94
|
html,
|
|
55
95
|
linkify: true,
|
|
56
96
|
typographer: true,
|
|
57
97
|
highlight(code, lang) {
|
|
58
98
|
code = code.replace(/\n$/, '');
|
|
59
|
-
const body =
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
99
|
+
const body = !(lang && hljs.getLanguage(lang))
|
|
100
|
+
? escapeHtml(code)
|
|
101
|
+
: highlightBudget === Infinity
|
|
102
|
+
? highlight(code, lang)
|
|
103
|
+
: pieces(code).map((piece) => highlight(piece, lang)).join('');
|
|
63
104
|
return `<pre><code class="hljs${lang ? ` language-${escapeHtml(lang)}` : ''}">${body}</code></pre>`;
|
|
64
105
|
},
|
|
65
106
|
});
|
|
66
|
-
|
|
107
|
+
// The budget is for each render.
|
|
108
|
+
const render = md.renderer.render;
|
|
109
|
+
md.renderer.render = function (...args) {
|
|
110
|
+
spent = 0;
|
|
111
|
+
return render.apply(this, args);
|
|
112
|
+
};
|
|
113
|
+
md.use(ids, { slugify, idPrefix })
|
|
67
114
|
.use(footnote)
|
|
68
|
-
.use(
|
|
115
|
+
.use(footnotes, { idPrefix })
|
|
116
|
+
.use(taskLists)
|
|
69
117
|
.use(emoji)
|
|
70
118
|
.use(callouts)
|
|
71
119
|
.use(wikilinks, { slugify })
|
|
72
120
|
.use(frontMatter);
|
|
73
|
-
if (math) {
|
|
74
|
-
md.use(math.texmath, {
|
|
75
|
-
engine: math.katex,
|
|
76
|
-
// LaTeX writes \( \) and \[ \]; AI assistants and most Markdown editors use $ and $$.
|
|
77
|
-
delimiters: ['brackets', 'dollars', 'beg_end'],
|
|
78
|
-
// Require a space before an opening $ so prices like "$5 and $10" stay text.
|
|
79
|
-
outerSpace: true,
|
|
80
|
-
katexOptions: { throwOnError: false, output: 'html' },
|
|
81
|
-
});
|
|
82
|
-
// texmath's outerSpace takes only a space beside a $, so a formula at the start or end of a
|
|
83
|
-
// hard-wrapped line stays text. These run first and also take a line break.
|
|
84
|
-
for (const rule of math.texmath.rules.dollars.inline) {
|
|
85
|
-
md.inline.ruler.before('math_inline_double', `${rule.name}_wrapped`,
|
|
86
|
-
math.texmath.inline({ ...rule, rex: new RegExp(rule.rex), pre: dollarPre, post: dollarPost }));
|
|
87
|
-
}
|
|
88
|
-
}
|
|
121
|
+
if (math) md.use(mathRules, { katex: math.katex, maxHtml: math.maxHtml });
|
|
89
122
|
return md;
|
|
90
123
|
}
|
|
91
124
|
|
|
92
|
-
// Whether the $ at `at` opens or closes a formula: whitespace or the paragraph's edge is outside it,
|
|
93
|
-
// or after a closing $, punctuation that ends a clause.
|
|
94
|
-
const dollarPre = (src, _outerSpace, at) => at === 0 || /\s/.test(src[at - 1]);
|
|
95
|
-
const dollarPost = (src, _outerSpace, at) => at + 1 >= src.length || /[\s.,;]/.test(src[at + 1]);
|
|
96
|
-
|
|
97
125
|
let titleParser;
|
|
98
126
|
|
|
127
|
+
// `s` without the spaces and tabs at either end. A regex would take quadratic time on a long run of them.
|
|
128
|
+
function trimSpaceTab(s) {
|
|
129
|
+
let start = 0;
|
|
130
|
+
let end = s.length;
|
|
131
|
+
while (start < end && (s[start] === ' ' || s[start] === '\t')) start++;
|
|
132
|
+
while (end > start && (s[end - 1] === ' ' || s[end - 1] === '\t')) end--;
|
|
133
|
+
return s.slice(start, end);
|
|
134
|
+
}
|
|
135
|
+
|
|
99
136
|
// The document title: the text of the first level-one heading as it renders, else the front matter's
|
|
100
137
|
// `title:`, else the fallback.
|
|
101
138
|
export function titleOf(markdown, fallback) {
|
|
@@ -105,7 +142,7 @@ export function titleOf(markdown, fallback) {
|
|
|
105
142
|
const at = tokens.findIndex((t) => t.type === 'heading_open' && t.tag === 'h1');
|
|
106
143
|
const heading = at < 0 ? '' : headingText(titleParser.renderer.render(tokens.slice(at, at + 3), titleParser.options, env));
|
|
107
144
|
const yaml = frontMatterOf(markdown)?.yaml ?? '';
|
|
108
|
-
const title = yaml.match(/^title:
|
|
145
|
+
const title = trimSpaceTab(yaml.match(/^title:(.+)$/m)?.[1] ?? '').replace(/^(["'])(.*)\1$/, '$2').trim();
|
|
109
146
|
return heading || title || fallback;
|
|
110
147
|
}
|
|
111
148
|
|
package/lib/scan.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Searches that a rule repeats from every opening marker, answered from a table built in one pass, so a
|
|
2
|
+
// document of thousands of unclosed markers doesn't search to its end from each one.
|
|
3
|
+
|
|
4
|
+
// For each index of `s`, the first index at or after it where test(s, i) holds, or -1.
|
|
5
|
+
export function nextWhere(s, test) {
|
|
6
|
+
const next = new Int32Array(s.length + 1);
|
|
7
|
+
next[s.length] = -1;
|
|
8
|
+
for (let i = s.length - 1; i >= 0; i--) next[i] = test(s, i) ? i : next[i + 1];
|
|
9
|
+
return next;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// The first index at or after `from` in a parser state's source where `test` holds, or -1. Each test's
|
|
13
|
+
// table is built the first time a rule needs it and kept with the state.
|
|
14
|
+
export function first(state, test, from) {
|
|
15
|
+
const tables = (state.md2pdfScan ??= new Map());
|
|
16
|
+
let next = tables.get(test);
|
|
17
|
+
if (!next) tables.set(test, (next = nextWhere(state.src, test)));
|
|
18
|
+
return from < next.length ? next[from] : -1;
|
|
19
|
+
}
|
package/lib/tasklists.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// GitHub task lists: a list item starting `[ ] ` or `[x] ` gets a checkbox that can't be ticked, inside a
|
|
2
|
+
// label with the item's text. The markup is that of markdown-it-task-lists 2.1.1 with { label: true }.
|
|
3
|
+
// That plugin keeps its options in module variables, so another markdown-it on the page that uses it with
|
|
4
|
+
// other options changes md2pdf's task lists too, and its labelAfter option writes the item's text out as
|
|
5
|
+
// raw HTML.
|
|
6
|
+
|
|
7
|
+
const TASK = /^\[[ xX]\] /;
|
|
8
|
+
|
|
9
|
+
export default function taskLists(md) {
|
|
10
|
+
md.core.ruler.after('inline', 'task_lists', (state) => {
|
|
11
|
+
const tokens = state.tokens;
|
|
12
|
+
// The open token at each nesting level, to find a list item's list without searching back.
|
|
13
|
+
const open = [];
|
|
14
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
15
|
+
const token = tokens[i];
|
|
16
|
+
if (token.nesting === 1) open[token.level] = token;
|
|
17
|
+
if (
|
|
18
|
+
i < 2 ||
|
|
19
|
+
token.type !== 'inline' ||
|
|
20
|
+
tokens[i - 1].type !== 'paragraph_open' ||
|
|
21
|
+
tokens[i - 2].type !== 'list_item_open' ||
|
|
22
|
+
!TASK.test(token.content)
|
|
23
|
+
) continue;
|
|
24
|
+
|
|
25
|
+
const checkbox = new state.Token('task_checkbox', '', 0);
|
|
26
|
+
checkbox.meta = { checked: token.content[1] !== ' ' };
|
|
27
|
+
token.children.unshift(checkbox);
|
|
28
|
+
// As in markdown-it-task-lists, which takes the marker off the first child whatever it is: an item
|
|
29
|
+
// whose [x] is a link reference keeps the link.
|
|
30
|
+
token.children[1].content = token.children[1].content.slice(3);
|
|
31
|
+
token.content = token.content.slice(3);
|
|
32
|
+
token.children.unshift(new state.Token('task_label_open', 'label', 1));
|
|
33
|
+
token.children.push(new state.Token('task_label_close', 'label', -1));
|
|
34
|
+
|
|
35
|
+
tokens[i - 2].attrSet('class', 'task-list-item');
|
|
36
|
+
open[tokens[i - 2].level - 1]?.attrSet('class', 'contains-task-list');
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
md.renderer.rules.task_checkbox = (tokens, idx) =>
|
|
41
|
+
`<input class="task-list-item-checkbox"${tokens[idx].meta.checked ? ' checked=""' : ''} disabled="" type="checkbox">`;
|
|
42
|
+
md.renderer.rules.task_label_open = () => '<label>';
|
|
43
|
+
md.renderer.rules.task_label_close = () => '</label>';
|
|
44
|
+
}
|
package/lib/wikilinks.js
CHANGED
|
@@ -17,15 +17,20 @@ export default function wikilinks(md, { slugify }) {
|
|
|
17
17
|
const embed = src.charCodeAt(pos) === 0x21 /* ! */;
|
|
18
18
|
const start = pos + (embed ? 1 : 0);
|
|
19
19
|
if (!src.startsWith('[[', start)) return false;
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
// The inside runs to the first bracket or line break, which must start the closing ]]. Stopping at the
|
|
21
|
+
// next [ keeps a run of unclosed [[ from each searching to the end of the paragraph.
|
|
22
|
+
let end = start + 2;
|
|
23
|
+
while (end < src.length && !'[]\n'.includes(src[end])) end++;
|
|
24
|
+
if (!src.startsWith(']]', end)) return false;
|
|
22
25
|
const inner = src.slice(start + 2, end);
|
|
23
|
-
if (!inner.trim()
|
|
26
|
+
if (!inner.trim()) return false;
|
|
24
27
|
// [[1]](url) is an ordinary link whose text is [1]; AI assistants write citations that way.
|
|
25
28
|
if (src.charCodeAt(end + 2) === 0x28 /* ( */) return false;
|
|
26
29
|
|
|
27
30
|
// In tables the pipe is escaped, [[Note\|alias]]; markdown-it unescapes it only inside table cells.
|
|
28
|
-
const
|
|
31
|
+
const bar = inner.indexOf('|');
|
|
32
|
+
const target = bar < 0 ? inner : inner.slice(0, inner[bar - 1] === '\\' ? bar - 1 : bar);
|
|
33
|
+
const alias = bar < 0 ? '' : inner.slice(bar + 1);
|
|
29
34
|
const [page, ...rest] = target.split('#').map((s) => s.trim());
|
|
30
35
|
// Block references (#^id) name no heading to show.
|
|
31
36
|
const headings = rest.filter((h) => h && !h.startsWith('^'));
|
|
@@ -48,8 +53,8 @@ export default function wikilinks(md, { slugify }) {
|
|
|
48
53
|
return true;
|
|
49
54
|
});
|
|
50
55
|
|
|
51
|
-
//
|
|
52
|
-
// `A -- B` has the id a--b. Slug the same text
|
|
56
|
+
// Heading ids are slugged from a heading's text after the typographer and emoji rules have run, so
|
|
57
|
+
// `A -- B` has the id a--b. Slug the same text.
|
|
53
58
|
const headingId = (md, heading) =>
|
|
54
59
|
slugify(md.parseInline(heading, {})[0].children
|
|
55
60
|
.filter((t) => t.type === 'text' || t.type === 'code_inline')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threepenny/md2pdf",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.3",
|
|
4
4
|
"description": "Markdown to beautifully styled PDF: the renderer and macOS CLI behind md2pdf.me",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -36,13 +36,12 @@
|
|
|
36
36
|
"github-markdown-css": "5.9.0",
|
|
37
37
|
"highlight.js": "^11.12.0",
|
|
38
38
|
"markdown-it": "^15.0.2",
|
|
39
|
-
"markdown-it-anchor": "^10.0.0",
|
|
40
39
|
"markdown-it-emoji": "^3.1.0",
|
|
41
|
-
"markdown-it-footnote": "^4.0.0"
|
|
42
|
-
"markdown-it-task-lists": "^2.1.1"
|
|
40
|
+
"markdown-it-footnote": "^4.0.0"
|
|
43
41
|
},
|
|
44
42
|
"devDependencies": {
|
|
45
43
|
"katex": "^0.19.1",
|
|
44
|
+
"markdown-it-task-lists": "^2.1.1",
|
|
46
45
|
"markdown-it-texmath": "^1.0.0"
|
|
47
46
|
}
|
|
48
47
|
}
|