-
Notifications
You must be signed in to change notification settings - Fork 38
/
node.go
130 lines (116 loc) · 2.16 KB
/
node.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
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
package document
import (
"bytes"
)
type Node struct {
children []*Node
parent *Node
item Block
}
func (n *Node) Children() []*Node {
return n.children
}
func (n *Node) Index() int {
if n.parent == nil {
return -1
}
i := 0
for ; i < len(n.parent.children); i++ {
if n.parent.children[i] == n {
break
}
}
return i
}
func (n *Node) InsertAt(idx int, item Block) *Node {
node := &Node{
item: item,
parent: n,
}
if idx == len(n.children) {
n.children = append(n.children, node)
} else {
n.children = append(n.children[:idx+1], n.children[idx:]...)
n.children[idx] = node
}
return node
}
func (n *Node) Item() Block {
return n.item
}
func (n *Node) Parent() *Node {
return n.parent
}
func (n *Node) Remove(nodeToRemove *Node) bool {
if len(n.children) == 0 {
return false
}
idx := -1
for i := 0; i < len(n.children); i++ {
if n.children[i] == nodeToRemove {
idx = i
break
}
}
if idx == -1 {
return false
}
if idx == 0 {
n.children = n.children[1:]
} else if idx == len(n.children)-1 {
n.children = n.children[:len(n.children)-1]
} else {
n.children = append(n.children[0:idx], n.children[idx+1:]...)
}
return true
}
func (n *Node) Bytes() []byte {
var b bytes.Buffer
for idx, child := range n.children {
_, _ = b.Write(child.Item().Value())
if idx != len(n.children)-1 {
_ = b.WriteByte('\n')
}
}
return b.Bytes()
}
func (n *Node) String() string {
return string(n.Bytes())
}
func (n *Node) add(item Block) *Node {
node := &Node{
item: item,
parent: n,
}
n.children = append(n.children, node)
return node
}
func CollectCodeBlocks(node *Node) (result CodeBlocks) {
collectCodeBlocks(node, &result)
return
}
func collectCodeBlocks(node *Node, result *CodeBlocks) {
if node == nil {
return
}
for _, child := range node.children {
if item, ok := child.Item().(*CodeBlock); ok {
*result = append(*result, item)
}
collectCodeBlocks(child, result)
}
}
func FindNode(node *Node, fn func(*Node) bool) *Node {
if node == nil {
return nil
}
for _, child := range node.children {
if n := FindNode(child, fn); n != nil {
return n
}
}
if fn(node) {
return node
}
return nil
}