forked from b3log/lute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinline_math.go
88 lines (78 loc) · 2.47 KB
/
inline_math.go
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
// Lute - A structured markdown engine.
// Copyright (c) 2019-present, b3log.org
//
// Lute is licensed under the Mulan PSL v1.
// You can use this software according to the terms and conditions of the Mulan PSL v1.
// You may obtain a copy of Mulan PSL v1 at:
// http://license.coscl.org.cn/MulanPSL
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
// PURPOSE.
// See the Mulan PSL v1 for more details.
package lute
var dollar = strToBytes("$")
func (t *Tree) parseInlineMath(ctx *InlineContext) (ret *Node) {
if 2 > ctx.tokensLen {
ctx.pos++
return &Node{typ: NodeText, tokens: dollar}
}
startPos := ctx.pos
blockStartPos := startPos
dollars := 0
for ; blockStartPos < ctx.tokensLen && itemDollar == ctx.tokens[blockStartPos]; blockStartPos++ {
dollars++
}
if 2 <= dollars {
// 块节点
matchBlock := false
blockEndPos := blockStartPos + dollars
var token byte
for ; blockEndPos < ctx.tokensLen; blockEndPos++ {
token = ctx.tokens[blockEndPos]
if itemDollar == token && blockEndPos < ctx.tokensLen-1 && itemDollar == ctx.tokens[blockEndPos+1] {
matchBlock = true
break
}
}
if matchBlock {
ret = &Node{typ: NodeMathBlock}
ret.AppendChild(&Node{typ: NodeMathBlockOpenMarker})
ret.AppendChild(&Node{typ: NodeMathBlockContent, tokens: ctx.tokens[blockStartPos:blockEndPos]})
ret.AppendChild(&Node{typ: NodeMathBlockCloseMarker})
ctx.pos = blockEndPos + 2
return
}
}
if !t.context.option.InlineMathAllowDigitAfterOpenMarker && isDigit(ctx.tokens[startPos+1]) { // $ 后面不能紧跟数字
ctx.pos += 3
return &Node{typ: NodeText, tokens: ctx.tokens[startPos : startPos+3]}
}
endPos := t.matchInlineMathEnd(ctx.tokens[startPos+1:])
if 1 > endPos {
ctx.pos++
ret = &Node{typ: NodeText, tokens: dollar}
return
}
endPos = startPos + endPos + 2
ret = &Node{typ: NodeInlineMath}
ret.AppendChild(&Node{typ: NodeInlineMathOpenMarker})
ret.AppendChild(&Node{typ: NodeInlineMathContent, tokens: ctx.tokens[startPos+1 : endPos-1]})
ret.AppendChild(&Node{typ: NodeInlineMathCloseMarker})
ctx.pos = endPos
return
}
func (t *Tree) matchInlineMathEnd(tokens []byte) (pos int) {
length := len(tokens)
for ; pos < length; pos++ {
if itemDollar == tokens[pos] {
if pos < length-1 {
if !isDigit(tokens[pos+1]) {
return pos
}
} else {
return pos
}
}
}
return -1
}