...
1
16
17 package templates
18
19 import (
20 "fmt"
21 "io"
22 "strings"
23
24 "github.com/russross/blackfriday/v2"
25 )
26
27 const linebreak = "\n"
28
29
30 var _ blackfriday.Renderer = &ASCIIRenderer{}
31
32
33
34 type ASCIIRenderer struct {
35 Indentation string
36
37 listItemCount uint
38 listLevel uint
39 }
40
41
42 func (r *ASCIIRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
43 switch node.Type {
44 case blackfriday.Text:
45 raw := string(node.Literal)
46 lines := strings.Split(raw, linebreak)
47 for _, line := range lines {
48 trimmed := strings.Trim(line, " \n\t")
49 if len(trimmed) > 0 && trimmed[0] != '_' {
50 w.Write([]byte(" "))
51 }
52 w.Write([]byte(trimmed))
53 }
54 case blackfriday.HorizontalRule, blackfriday.Hardbreak:
55 w.Write([]byte(linebreak + "----------" + linebreak))
56 case blackfriday.Code, blackfriday.CodeBlock:
57 w.Write([]byte(linebreak))
58 lines := []string{}
59 for _, line := range strings.Split(string(node.Literal), linebreak) {
60 trimmed := strings.Trim(line, " \t")
61
62
63 indented := strings.Repeat(r.Indentation, 4) + trimmed
64 lines = append(lines, indented)
65 }
66 w.Write([]byte(strings.Join(lines, linebreak)))
67 case blackfriday.Image:
68 w.Write(node.LinkData.Destination)
69 case blackfriday.Link:
70 w.Write([]byte(" "))
71 w.Write(node.LinkData.Destination)
72 case blackfriday.Paragraph:
73 if r.listLevel == 0 {
74 w.Write([]byte(linebreak))
75 }
76 case blackfriday.List:
77 if entering {
78 w.Write([]byte(linebreak))
79 r.listLevel++
80 } else {
81 r.listLevel--
82 r.listItemCount = 0
83 }
84 case blackfriday.Item:
85 if entering {
86 r.listItemCount++
87 for i := 0; uint(i) < r.listLevel; i++ {
88 w.Write([]byte(r.Indentation))
89 }
90 if node.ListFlags&blackfriday.ListTypeOrdered != 0 {
91 w.Write([]byte(fmt.Sprintf("%d. ", r.listItemCount)))
92 } else {
93 w.Write([]byte("* "))
94 }
95 } else {
96 w.Write([]byte(linebreak))
97 }
98 default:
99 normalText(w, node.Literal)
100 }
101 return blackfriday.GoToNext
102 }
103
104 func normalText(w io.Writer, text []byte) {
105 w.Write([]byte(strings.Trim(string(text), " \n\t")))
106 }
107
108
109 func (r *ASCIIRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {
110
111 }
112
113
114 func (r *ASCIIRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {
115 io.WriteString(w, "\n")
116 }
117
View as plain text