-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkdown.go
129 lines (110 loc) · 2.2 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
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
package sisyphus
import (
"fmt"
"net/url"
"path/filepath"
"strings"
)
type Markdown struct {
State State
LinkHooks map[string]LinkHook
QuoteHook QuoteHook
OpenHook Hook
CloseHook Hook
}
func (md *Markdown) OnLink(rule string, hook LinkHook) {
if md.LinkHooks == nil {
md.LinkHooks = make(map[string]LinkHook)
}
md.LinkHooks[rule] = hook
}
func (md *Markdown) OnQuote(hook QuoteHook) {
md.QuoteHook = hook
}
func (md *Markdown) OnOpen(hook Hook) {
md.OpenHook = hook
}
func (md *Markdown) OnClose(hook Hook) {
md.CloseHook = hook
}
func (md *Markdown) Wrap(s string) {
if s == "" {
return
}
md.OnOpen(func() string {
return s
})
md.OnClose(func() string {
return s
})
}
func (md *Markdown) Open() string {
if md.OpenHook != nil {
return md.OpenHook()
}
return ""
}
func (md *Markdown) Close() string {
if md.CloseHook != nil {
return md.CloseHook()
}
return ""
}
func (md *Markdown) Header(level int, text string) string {
return fmt.Sprintf("%s %s\n", strings.Repeat("#", level), text)
}
func (md *Markdown) Link(url string, text string) string {
ext := filepath.Ext(url)
hook, ok := md.LinkHooks[ext]
if ok {
return hook(Safe(url), Safe(text), ext)
}
if text == "" {
text = url
}
return fmt.Sprintf("[%s](%s)", text, url)
}
func (md *Markdown) ListItem(text string) string {
return fmt.Sprintf("* %s\n", text)
}
func (md *Markdown) Pre(text string) string {
return text
}
func (md *Markdown) Text(text string) string {
return text
}
func (md *Markdown) Quote(text string) string {
if md.QuoteHook != nil {
return md.QuoteHook(text)
}
return "> " + text
}
func (md *Markdown) GetState() State {
return md.State
}
func (md *Markdown) SetState(state State) string {
if state == md.State {
return ""
}
var closing, opening string
switch md.State {
case Pre:
closing = "```\n"
}
switch state {
case Pre:
opening = "```\n"
}
md.State = state
return closing + opening
}
func (md *Markdown) Aspeq(prefix string, useBase bool) LinkHook {
return func(uri, text, suffix string) string {
parsed, err := url.Parse(uri)
format := "![%s](%s)"
if err == nil && !parsed.IsAbs() && useBase {
uri = filepath.Base(uri)
}
return fmt.Sprintf(format, text, uri)
}
}