-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown.go
98 lines (87 loc) · 1.51 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
package web
import (
"io"
"strings"
"github.com/gregoryv/nexus"
)
func NewMarkdownWriter(w io.Writer) *MarkdownWriter {
p, err := nexus.NewPrinter(w)
return &MarkdownWriter{
Printer: p,
err: err,
}
}
type MarkdownWriter struct {
*nexus.Printer
err *error
indent string // ie. for pre tags
}
func (p *MarkdownWriter) WriteMarkdown(e *Element) {
p.writeElement(e)
}
func (p *MarkdownWriter) writeElement(t interface{}) {
switch t := t.(type) {
case *Element:
p.open(t)
for _, a := range t.Attributes {
p.writeAttr(a)
}
for _, child := range t.Children {
p.writeElement(child)
}
p.close(t)
case string:
if strings.Index(t, "\n") == -1 {
p.Print(p.indent, t)
return
}
lines := strings.Split(t, "\n")
for _, line := range lines {
p.Print(p.indent, line, "\n")
}
}
}
var markdown = map[string]string{
"h1": "# ",
"h2": "## ",
"h3": "### ",
"h4": "#### ",
"h5": "##### ",
"h6": "###### ",
"ul": "",
"p": "",
"li": "- ",
"hr": "----",
"br": "\n",
}
func (p *MarkdownWriter) writeAttr(a *Attribute) {
if a.Name == "src" {
p.Printf("(%s)", a.Val)
}
if a.Name == "alt" {
p.Printf("[%s]", a.Val)
}
}
func (p *MarkdownWriter) open(t *Element) {
switch t.Name {
case "img":
p.Print("!")
if !t.hasAttr("alt") {
p.Print("[]")
}
case "pre":
p.indent = " "
default:
p.Print(markdown[t.Name])
}
}
func (p *MarkdownWriter) close(t *Element) {
p.Println()
switch t.Name {
case "li", "span":
case "pre":
p.indent = ""
default:
p.Println()
}
}