-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (48 loc) · 1.46 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
import katex from 'katex'
const defaultOptions = {
delimiters: [
{ left: '\\[', right: '\\]' },
{ left: '\\(', right: '\\)' }
]
}
function escapedBracketRule(options) {
return (state, silent) => {
const max = state.posMax
const start = state.pos
for (const { left, right } of options.delimiters) {
// 检查是否以左标记开始
if (!state.src.slice(start).startsWith(left)) continue
// 跳过左标记的长度
let pos = start + left.length
// 寻找匹配的右标记
while (pos < max) {
if (state.src.slice(pos).startsWith(right)) {
break
}
pos++
}
// 没找到匹配的右标记,跳过,进入下个匹配
if (pos >= max) continue
// 如果不是静默模式,将 LaTeX 公式转换为 MathML
if (!silent) {
const content = state.src.slice(start + left.length, pos)
try {
const renderedContent = katex.renderToString(content, {
throwOnError: false,
output: 'mathml'
})
const token = state.push('html_inline', '', 0)
token.content = renderedContent
} catch (e) {
console.error(e)
}
}
// 更新位置,跳过右标记的长度
state.pos = pos + right.length
return true
}
}
}
export default function (md, options = defaultOptions) {
md.inline.ruler.after('text', 'escaped_bracket', escapedBracketRule(options))
}