-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodifyast.go
99 lines (87 loc) · 2.34 KB
/
modifyast.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
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"bytes"
"github.com/gomarkdown/markdown/ast"
)
func modifyAst(doc ast.Node) ast.Node {
doclinkPrefixBytes := []byte("[[")
doclinkSuffixBytes := []byte("]]")
doclinkPrefixBytesLen := len(doclinkPrefixBytes)
ast.WalkFunc(doc, func(node ast.Node, entering bool) ast.WalkStatus {
if entering {
leaf := node.AsLeaf()
if leaf != nil {
for {
doclinkPrefixIndex := bytes.Index(leaf.Literal, doclinkPrefixBytes)
if doclinkPrefixIndex == -1 {
return ast.GoToNext
}
doclinkSuffixIndex := bytes.Index(leaf.Literal[doclinkPrefixIndex:], doclinkSuffixBytes)
if doclinkSuffixIndex == -1 {
return ast.GoToNext
}
if doclinkPrefixIndex > doclinkSuffixIndex {
return ast.GoToNext
}
if doclinkPrefixIndex != 0 {
newnode := &ast.Text{}
newnode.Literal = leaf.Literal[:doclinkPrefixIndex]
leaf.Literal = leaf.Literal[doclinkPrefixIndex:]
index := 0
parent := node.GetParent().AsContainer()
for i, v := range parent.Children {
if v == node {
index = i
break
}
}
insertNewNode(newnode, parent, index)
// debug
// fmt.Println("--")
// for _, v := range parent.Children {
// vv := v.AsLeaf()
// if vv != nil {
// fmt.Println(string(vv.Literal))
// }
// }
continue
}
insideDoclink := leaf.Literal[doclinkPrefixIndex+doclinkPrefixBytesLen : doclinkSuffixIndex]
leaf.Literal = leaf.Literal[doclinkSuffixIndex+doclinkPrefixBytesLen:]
parent := node.GetParent().AsContainer()
index := 0
for i, v := range parent.Children {
if v == node {
index = i
break
}
}
newnode := &DocLink{
URL: string(insideDoclink),
Inline: true,
}
insertNewNode(newnode, parent, index)
// debug
// fmt.Println("--")
// for _, v := range parent.Children {
// vv := v.AsLeaf()
// if vv != nil {
// fmt.Println(string(vv.Literal))
// }
// }
}
}
}
return ast.GoToNext
})
return doc
}
func insertNewNode(newnode ast.Node, parentn ast.Node, at int) {
newnode.SetParent(parentn)
parent := parentn.AsContainer()
pc := parent.Children
tmp := append([]ast.Node{}, pc[at:]...)
pc = append(pc[0:at], newnode)
pc = append(pc, tmp...)
parent.SetChildren(pc)
}