-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown.go
130 lines (119 loc) · 2.22 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
130
package web
import (
"io"
"strings"
"github.com/gregoryv/nexus"
)
func NewMarkdownEncoder(w io.Writer) *MarkdownEncoder {
p, err := nexus.NewPrinter(w)
return &MarkdownEncoder{
Printer: p,
err: err,
trim: true,
}
}
type MarkdownEncoder struct {
*nexus.Printer
err *error
indent string // ie. for pre tags
trim bool // pre tags should keep original whitespaces
oneliner bool
}
func (p *MarkdownEncoder) Encode(t interface{}) error {
p.writeElement(t)
return *p.err
}
func (p *MarkdownEncoder) writeElement(t interface{}) {
switch t := t.(type) {
case *Element:
switch t.Name {
case "img":
p.Print("![", t.AttrVal("alt"), "](", t.AttrVal("src"), ")")
if p.oneliner {
return
}
p.Print("\n")
case "a":
p.Print("[")
for _, child := range t.Children {
p.oneliner = true
p.writeElement(child)
p.oneliner = false
}
p.Print("]")
href := t.Attr("href")
if href == nil {
return
}
p.Print("(", href.Val, ")")
if t.hasChild("img") { // special case to put linked images on separate lines
p.Print("\n")
}
default:
if t.Name != "wrapper" {
p.open(t)
}
for _, child := range t.Children {
p.writeElement(child)
}
if t.Name != "wrapper" {
p.close(t)
}
}
case ElementBuilder:
p.writeElement(t.BuildElement())
case string:
if p.oneliner {
p.Print(t)
return
}
if strings.Index(t, "\n") == -1 {
p.Print(p.indent, t)
return
}
lines := strings.Split(t, "\n")
for _, line := range lines {
if p.trim {
line = strings.TrimSpace(line)
}
p.Print(p.indent, line, "\n")
}
}
}
func (p *MarkdownEncoder) open(t *Element) {
switch t.Name {
case "pre":
p.indent = " "
p.trim = false
default:
// todo: default to writing html
p.Print(markdown[t.Name])
}
}
func (p *MarkdownEncoder) close(t *Element) {
switch t.Name {
case "span", "body", "html":
case "pre":
p.Println()
p.indent = ""
p.trim = true
case "h1", "h2", "h3", "h4", "h5", "h6":
p.Println()
p.Println()
default:
p.Println()
}
}
var markdown = map[string]string{
"h1": "# ",
"h2": "## ",
"h3": "### ",
"h4": "#### ",
"h5": "##### ",
"h6": "###### ",
"ul": "",
"p": "",
"li": "- ",
"hr": "----",
"br": "\n",
}