forked from niklasfasching/go-org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
84 lines (73 loc) · 2.38 KB
/
block.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
package org
import (
"regexp"
"strings"
"unicode"
)
type Block struct {
Name string
Parameters []string
Children []Node
}
type Example struct {
Children []Node
}
var exampleLineRegexp = regexp.MustCompile(`^(\s*):(\s(.*)|\s*$)`)
var beginBlockRegexp = regexp.MustCompile(`(?i)^(\s*)#\+BEGIN_(\w+)(.*)`)
var endBlockRegexp = regexp.MustCompile(`(?i)^(\s*)#\+END_(\w+)`)
func lexBlock(line string) (token, bool) {
if m := beginBlockRegexp.FindStringSubmatch(line); m != nil {
return token{"beginBlock", len(m[1]), strings.ToUpper(m[2]), m}, true
} else if m := endBlockRegexp.FindStringSubmatch(line); m != nil {
return token{"endBlock", len(m[1]), strings.ToUpper(m[2]), m}, true
}
return nilToken, false
}
func lexExample(line string) (token, bool) {
if m := exampleLineRegexp.FindStringSubmatch(line); m != nil {
return token{"example", len(m[1]), m[3], m}, true
}
return nilToken, false
}
func isRawTextBlock(name string) bool { return name == "SRC" || name == "EXAMPLE" || name == "EXPORT" }
func (d *Document) parseBlock(i int, parentStop stopFn) (int, Node) {
t, start := d.tokens[i], i
name, parameters := t.content, strings.Fields(t.matches[3])
trim := trimIndentUpTo(d.tokens[i].lvl)
stop := func(d *Document, i int) bool {
return i >= len(d.tokens) || (d.tokens[i].kind == "endBlock" && d.tokens[i].content == name)
}
block, i := Block{name, parameters, nil}, i+1
if isRawTextBlock(name) {
rawText := ""
for ; !stop(d, i); i++ {
rawText += trim(d.tokens[i].matches[0]) + "\n"
}
block.Children = d.parseRawInline(rawText)
} else {
consumed, nodes := d.parseMany(i, stop)
block.Children = nodes
i += consumed
}
if i < len(d.tokens) && d.tokens[i].kind == "endBlock" && d.tokens[i].content == name {
return i + 1 - start, block
}
return 0, nil
}
func (d *Document) parseExample(i int, parentStop stopFn) (int, Node) {
example, start := Example{}, i
for ; !parentStop(d, i) && d.tokens[i].kind == "example"; i++ {
example.Children = append(example.Children, Text{d.tokens[i].content, true})
}
return i - start, example
}
func trimIndentUpTo(max int) func(string) string {
return func(line string) string {
i := 0
for ; i < len(line) && i < max && unicode.IsSpace(rune(line[i])); i++ {
}
return line[i:]
}
}
func (n Example) String() string { return orgWriter.nodesAsString(n) }
func (n Block) String() string { return orgWriter.nodesAsString(n) }