-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathindex.js
359 lines (289 loc) · 10.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
* @typedef {import("mathup").Options} MathupOptions
* @typedef {import("markdown-it").default} MarkdownIt
* @typedef {import("markdown-it/lib/parser_block.mjs").RuleBlock} RuleBlock
* @typedef {import("markdown-it/lib/parser_inline.mjs").RuleInline} RuleInline
* @typedef {import("markdown-it/lib/rules_block/state_block.mjs").default} StateBlock
* @typedef {import("markdown-it/lib/rules_inline/state_inline.mjs").default} StateInline
* @typedef {import("markdown-it/lib/token.mjs").default} Token
* @typedef {string | [string, string]} Delimiter
*/
/** @type {import("mathup").default | undefined} */
let mathup;
try {
mathup = (await import("mathup")).default;
} catch {
// pass
}
/**
* @param {string | Delimiter[]} delimiters
* @returns {Array<[string, string]> | null}
*/
function fromDelimiterOption(delimiters) {
if (typeof delimiters === "string") {
if (delimiters.length === 0) {
return null;
}
return [[delimiters, delimiters]];
}
/** @type {Array<[string, string]>} */
const pairs = [];
for (const pair of delimiters) {
if (typeof pair === "string") {
if (pair.length === 0) {
continue;
}
pairs.push([pair, pair]);
} else {
if (pair[0].length === 0 || pair[1].length === 0) {
continue;
}
pairs.push(pair);
}
}
if (pairs.length === 0) {
return null;
}
// Make sure we match longer variants first.
return pairs.sort(([a], [b]) => b.length - a.length);
}
/**
* @param {object} options
* @param {Array<[string, string]>} options.delimiters
* @param {boolean} options.allowWhiteSpacePadding
* @returns {RuleInline}
*/
function createInlineMathRule({ delimiters, allowWhiteSpacePadding }) {
return (state, silent) => {
const start = state.pos;
const markers = delimiters.filter(
([open]) => open === state.src.slice(start, start + open.length),
);
if (markers.length === 0) {
return false;
}
// Scan until the end of the line (or until close marker is found).
for (const [open, close] of markers) {
const pos = start + open.length;
if (
state.md.utils.isWhiteSpace(state.src.charCodeAt(pos)) &&
!allowWhiteSpacePadding
) {
// Don’t allow whitespace immediately after open delimiter
continue;
}
const matchStart = state.src.indexOf(close, pos);
if (matchStart === -1 || pos === matchStart) {
// Don’t allow empty expressions.
continue;
}
if (
state.md.utils.isWhiteSpace(state.src.charCodeAt(matchStart - 1)) &&
!allowWhiteSpacePadding
) {
// Don’t allow whitespace immediately before close delimiter
continue;
}
let content = state.src.slice(pos, matchStart).replaceAll("\n", " ");
if (allowWhiteSpacePadding) {
content = content.replace(/^ (.+) $/, "$1");
}
if (!silent) {
const token = state.push("math_inline", "math", 0);
token.markup = open;
token.content = content;
}
state.pos = matchStart + close.length;
return true;
}
return false;
};
}
/**
* @param {Array<[string, string]>} delimiters
* @returns {RuleBlock}
*/
function createBlockMathRule(delimiters) {
return function math_block(state, startLine, endLine, silent) {
const start = state.bMarks[startLine] + state.tShift[startLine];
for (const [open, close] of delimiters) {
let pos = start;
let max = state.eMarks[startLine];
if (pos + open.length > max) {
continue;
}
const openDelim = state.src.slice(pos, pos + open.length);
if (openDelim !== open) {
continue;
}
pos += open.length;
let firstLine = state.src.slice(pos, max);
// Since start is found, we can report success here in validation mode
if (silent) {
return true;
}
let haveEndMarker = false;
if (firstLine.trim().slice(-close.length) === close) {
// Single line expression
firstLine = firstLine.trim().slice(0, -close.length);
haveEndMarker = true;
}
// search end of block
let nextLine = startLine;
/** @type {string | undefined} */
let lastLine;
for (;;) {
if (haveEndMarker) {
break;
}
nextLine += 1;
if (nextLine >= endLine) {
// unclosed block should be autoclosed by end of document.
// also block seems to be autoclosed by end of parent
break;
}
pos = state.bMarks[nextLine] + state.tShift[nextLine];
max = state.eMarks[nextLine];
if (state.src.slice(pos, max).trim().slice(-close.length) !== close) {
continue;
}
if (state.tShift[nextLine] - state.blkIndent >= 4) {
// closing block math should be indented less then 4 spaces
continue;
}
const lastLinePos = state.src.slice(0, max).lastIndexOf(close);
lastLine = state.src.slice(pos, lastLinePos);
pos += lastLine.length + close.length;
// make sure tail has spaces only
pos = state.skipSpaces(pos);
if (pos < max) {
continue;
}
// found!
haveEndMarker = true;
}
// If math block has heading spaces, they should be removed from its inner block
const len = state.tShift[startLine];
state.line = nextLine + (haveEndMarker ? 1 : 0);
const token = state.push("math_block", "math", 0);
token.block = true;
const firstLineContent = firstLine && firstLine.trim() ? firstLine : "";
const contentLines = state.getLines(startLine + 1, nextLine, len, false);
const lastLineContent = lastLine && lastLine.trim() ? lastLine : "";
token.content = `${firstLineContent}${firstLineContent && (contentLines || lastLineContent) ? "\n" : ""}${contentLines}${contentLines && lastLineContent ? "\n" : ""}${lastLineContent}`;
token.map = [startLine, state.line];
token.markup = open;
return true;
}
return false;
};
}
/**
* @typedef {string | [tag: string, attrs?: Record<string, string>]} CustomElementOption
* @param {CustomElementOption} customElementOption
* @param {MarkdownIt} md
* @returns {(src: string) => string}
*/
function createCustomElementRenderer(customElementOption, md) {
const { escapeHtml } = md.utils;
/** @type {string} */
let tag;
let attrs = "";
if (typeof customElementOption === "string") {
tag = customElementOption;
} else {
const [tagName, attrsObj = {}] = customElementOption;
tag = tagName;
for (const [key, value] of Object.entries(attrsObj)) {
attrs += ` ${key}="${escapeHtml(value)}"`;
}
}
return (src) => `<${tag}${attrs}>${escapeHtml(src)}</${tag}>`;
}
/**
* @param {MathupOptions} options
* @param {MarkdownIt} md
* @returns {(src: string) => string}
*/
function defaultInlineRenderer(options, md) {
if (!mathup) {
return createCustomElementRenderer(["span", { class: "math inline" }], md);
}
return (src) => mathup(src, options).toString();
}
/**
* @param {MathupOptions} options
* @param {MarkdownIt} md
* @returns {(src: string) => string}
*/
function defaultBlockRenderer(options, md) {
if (!mathup) {
return createCustomElementRenderer(["div", { class: "math block" }], md);
}
return (src) => mathup(src, { ...options, display: "block" }).toString();
}
/**
* @callback Renderer
* @param {string} src - The source content
* @param {Token} token - The parsed markdown-it token
* @param {MarkdownIt} md - The markdown-it instance
* @typedef {object} PluginOptions
* @property {string | Delimiter[]} [inlineDelimiters] - Inline math delimiters.
* @property {string} [inlineOpen] - Deprecated: Use inlineDelimiters
* @property {string} [inlineClose] - Deprecated: Use inlineDelimiters
* @property {CustomElementOption} [inlineCustomElement] - If you want to render to a custom element.
* @property {Renderer} [inlineRenderer] - Custom renderer for inline math. Default mathup.
* @property {boolean} [inlineAllowWhiteSpacePadding] - If you want allow inline math to start or end with whitespace.
* @property {string | Delimiter[]} [blockDelimiters] - Block math delimters.
* @property {string} [blockOpen] - Deprecated: Use blockDelimiters
* @property {string} [blockClose] - Deprecated: Use blockDelimiters
* @property {CustomElementOption} [blockCustomElement] - If you want to render to a custom element.
* @property {Renderer} [blockRenderer] - Custom renderer for block math. Default mathup with display = "block".
* @property {MathupOptions} [defaultRendererOptions] - The options passed into the default renderer.
*/
/** @type {import("markdown-it").PluginWithOptions<PluginOptions>} */
export default function markdownItMath(
md,
{
defaultRendererOptions = {},
inlineAllowWhiteSpacePadding = false,
inlineOpen,
inlineClose,
inlineDelimiters = inlineOpen && inlineClose
? /** @type {Delimiter[]} */ ([[inlineOpen, inlineClose]])
: /** @type {Delimiter[]} */ (["$", ["$`", "`$"]]),
blockOpen,
blockClose,
blockDelimiters = blockOpen && blockClose
? /** @type {Delimiter[]} */ ([[blockOpen, blockClose]])
: "$$",
inlineCustomElement,
inlineRenderer = inlineCustomElement
? createCustomElementRenderer(inlineCustomElement, md)
: defaultInlineRenderer(defaultRendererOptions, md),
blockCustomElement,
blockRenderer = blockCustomElement
? createCustomElementRenderer(blockCustomElement, md)
: defaultBlockRenderer(defaultRendererOptions, md),
} = {},
) {
const inlineDelimitersArray = fromDelimiterOption(inlineDelimiters);
if (inlineDelimitersArray) {
const inlineMathRule = createInlineMathRule({
delimiters: inlineDelimitersArray,
allowWhiteSpacePadding: inlineAllowWhiteSpacePadding,
});
md.inline.ruler.before("escape", "math_inline", inlineMathRule);
md.renderer.rules.math_inline = (tokens, idx) =>
inlineRenderer(tokens[idx].content, tokens[idx], md);
}
const blockDelitiersArray = fromDelimiterOption(blockDelimiters);
if (blockDelitiersArray) {
const blockMathRule = createBlockMathRule(blockDelitiersArray);
md.block.ruler.after("blockquote", "math_block", blockMathRule, {
alt: ["paragraph", "reference", "blockquote", "list"],
});
md.renderer.rules.math_block = (tokens, idx) =>
`${blockRenderer(tokens[idx].content, tokens[idx], md)}\n`;
}
}