-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkdown.go
80 lines (65 loc) · 1.57 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
package rescript
import (
"fmt"
"io"
)
// NewMarkdownComposer creates a new composer which generates output in markdown format.
func NewMarkdownComposer() ComposeFunc {
return composeMarkdown
}
type stringWriter struct {
io.Writer
}
func (sw stringWriter) WriteString(s string) (int, error) {
return sw.Write([]byte(s))
}
func composeMarkdown(w io.Writer, m Metadata, r map[string]*Node) error {
var err error
sw := stringWriter{w}
// TODO: we might write a yaml frontmatter here
sw.WriteString(fmt.Sprintf("# %v\n\n", m.Title))
for i, pageID := range m.PageIDs {
// thematic break after each page but the last
if i != 0 {
_, err = sw.WriteString("\n\n---\n\n")
if err != nil {
return err
}
}
tail, ok := r[pageID]
if ok {
err = markdownPage(sw, i, tail)
if err != nil {
return err
}
}
// TODO what should we do with pages w/o results?
}
// end the document with a newline
_, err = sw.WriteString("\n")
if err != nil {
return err
}
return nil
}
// "Improve" the result
// recognize lists:
// lines starting with "-" or "*"
// in some cases, add missing space
// add a newline before the *first* and after the *last* line
// of consecutive list entries
func markdownPage(sw io.StringWriter, idx int, n *Node) error {
var err error
_, err = sw.WriteString(fmt.Sprintf("**Page %d**\n\n", idx+1))
if err != nil {
return err
}
for node := n; node != nil; node = node.Next() {
// TODO: we might attempt to "guess" markdown here,
_, err = sw.WriteString(node.Token().String())
if err != nil {
return err
}
}
return nil
}