-
Notifications
You must be signed in to change notification settings - Fork 4
/
markdowm.go
90 lines (81 loc) · 1.98 KB
/
markdowm.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
package xmind
import (
"io"
"strconv"
"strings"
"text/template"
)
const (
DefaultMarkdownName = "default"
DefaultMarkdownFormat = "{{Repeat \"#\" ." + MarkdownKeyDeep +
"}} {{." + CustomKeyTitle + "}}\n\n{{range $i,$v := ." + CustomKeyLabels +
"}}> {{$v}}\n\n{{end}}{{range $i,$v := (SplitLines ." + CustomKeyNotes +
" \"\\n\\r\")}}> {{$v}}\n\n{{end}}"
MarkdownKeyDeep = "Deep" // 所在层级,>=1
)
func (wk *WorkBook) SaveToMarkdown(w io.Writer, format map[string]string) error {
defText, ok := format[DefaultMarkdownName]
if !ok {
defText = DefaultMarkdownFormat
}
tpl, err := template.New(DefaultMarkdownName).Funcs(template.FuncMap{
"Repeat": strings.Repeat, // 注册用到的方法
"SplitLines": func(s any, sep string) []string {
switch ss := s.(type) {
case string:
return strings.FieldsFunc(ss, func(r rune) bool {
for _, sv := range sep {
if r == sv {
return true // 匹配到分隔符
}
}
return false
})
default:
return nil
}
},
}).Parse(defText)
if err != nil {
return err
}
for k, v := range format {
// 对每个层级创建自定义渲染模板
if _, err = tpl.New(k).Parse(v); err != nil {
return err
}
}
for _, tp := range wk.Topics {
cent := tp.On()
if !cent.IsCent() {
return RootIsNull
}
err = cent.Range(func(deep int, current *Topic) error {
data := map[string]any{
MarkdownKeyDeep: deep,
CustomKeyTitle: current.Title,
}
if len(current.Labels) > 0 {
data[CustomKeyLabels] = current.Labels
}
if current.Notes != nil && current.Notes.Plain.Content != "" {
data[CustomKeyNotes] = current.Notes.Plain.Content
}
if current.Branch != "" {
data[CustomKeyBranch] = current.Branch
}
if current.Href != "" {
data[CustomKeyHref] = current.Href
}
tw := tpl.Lookup(strconv.Itoa(deep))
if tw == nil {
tw = tpl.Lookup(DefaultMarkdownName)
}
return tw.Execute(w, data)
})
if err != nil {
return err
}
}
return nil
}