forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformula.ts
More file actions
78 lines (68 loc) · 1.86 KB
/
Copy pathformula.ts
File metadata and controls
78 lines (68 loc) · 1.86 KB
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
export interface FormulaInput {
latex: string
displayMode: boolean
sourceRaw: string | null
}
export function escapeHtml(text: string): string {
return text
.replace(/&/g, `&`)
.replace(/</g, `<`)
.replace(/>/g, `>`)
.replace(/"/g, `"`)
.replace(/'/g, `'`)
}
export function unwrapFormula(text: string): FormulaInput {
let current = text.trim()
let displayMode = false
let clean = true
while (clean) {
clean = false
current = current.trim()
if (current.startsWith(`$$`) && current.endsWith(`$$`) && current.length > 4) {
current = current.slice(2, -2)
displayMode = true
clean = true
}
else if (current.startsWith(`\\[`) && current.endsWith(`\\]`)) {
current = current.slice(2, -2)
displayMode = true
clean = true
}
else if (current.startsWith(`\\(`) && current.endsWith(`\\)`)) {
current = current.slice(2, -2)
displayMode = false
clean = true
}
else if (current.startsWith(`$`) && current.endsWith(`$`) && current.length > 2) {
current = current.slice(1, -1)
displayMode = false
clean = true
}
}
return {
latex: current.trim(),
displayMode,
sourceRaw: text.trim(),
}
}
export function normalizeFormulaInput(text: string): FormulaInput {
const trimmed = text.trim()
if (!trimmed) {
return { latex: ``, displayMode: false, sourceRaw: null }
}
const unwrapped = unwrapFormula(trimmed)
const isWrapped = unwrapped.latex !== trimmed
return {
latex: unwrapped.latex,
displayMode: unwrapped.displayMode || trimmed.includes(`\n`),
sourceRaw: isWrapped ? trimmed : null,
}
}
export function wrapFormula(latex: string, displayMode: boolean): string {
const content = latex.trim()
if (!content)
return ``
return displayMode
? `$$\n${content}\n$$`
: `$${content}$`
}