-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown.go
102 lines (87 loc) · 2.47 KB
/
markdown.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
package markdown
import (
"os"
"regexp"
"strings"
)
type LineType string
func getLineType(line string) LineType {
trimmedLine := strings.TrimSpace(line)
re := regexp.MustCompile(`^- \[.\] `)
if re.MatchString(trimmedLine) {
return Task
}
if strings.HasPrefix(trimmedLine, string(Code)) {
return Code
} else if strings.HasPrefix(trimmedLine, string(Image)) {
return Image
} else if strings.HasPrefix(trimmedLine, string(List)) {
return List
} else if strings.HasPrefix(trimmedLine, string(Quote)) {
return Quote
} else if strings.HasPrefix(trimmedLine, string(Table)) {
return Table
}
re = regexp.MustCompile(`^\d+\.`)
if re.MatchString(trimmedLine) {
return NumberedList
}
return Normal
}
var (
Normal LineType = ""
Code LineType = "```"
Image LineType = "!["
List LineType = "- "
Quote LineType = "> "
Table LineType = "| "
Task LineType = "- [%] "
NumberedList LineType = "%. "
)
type Line struct {
Text string // The original text, with prefix
LineType LineType
originalText string
}
// Sections
type SectionType string
var (
H1 SectionType = "#"
H2 SectionType = "##"
H3 SectionType = "###"
H4 SectionType = "####"
H5 SectionType = "#####"
H6 SectionType = "######"
NullSection SectionType = ""
)
func getSectionType(line string) SectionType {
trimmedLine := strings.TrimSpace(line)
if strings.HasPrefix(trimmedLine, "#") {
sectionType := SectionType(trimmedLine[:strings.Index(trimmedLine, " ")])
return sectionType
} else {
return NullSection
}
}
// A "section" is a part of the markdown file that starts with any of the H1-H6 headers
// A NullSection is a section that has no "section" (It's the first part of the file if no title at the beginning)
type Section struct {
SectionType SectionType
Text string // The text after the first space (Without the "#..")
Lines []Line
originalText string
}
type MarkdownFile struct {
Path string
Title string // First "H1" section
FrontMatter map[interface{}]interface{}
Sections []Section
}
// New creates a new MarkdownFile object
func New(path string) MarkdownFile {
path = strings.Replace(path, "$HOME", os.Getenv("HOME"), 1)
path = strings.Replace(path, "${HOME}", os.Getenv("HOME"), 1)
path = strings.Replace(path, "$USER", os.Getenv("HOME"), 1)
path = strings.Replace(path, "${USER}", os.Getenv("USER"), 1)
return MarkdownFile{Path: path}
}