-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown_to_html.go
205 lines (192 loc) · 5.02 KB
/
markdown_to_html.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package lib
import (
"errors"
"fmt"
"io"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/ast"
mdhtml "github.com/gomarkdown/markdown/html"
)
const (
DEFAULT_CODE_STYLE = "monokai"
)
type MarkdownToHTMLRenderer struct {
highlightStyle *chroma.Style
htmlFormatter *html.Formatter
mdhtmlRenderer *mdhtml.Renderer
}
func NewMarkdownToHtmlRenderer(highlightStyleString string) (*MarkdownToHTMLRenderer, error) {
var styleName string
if highlightStyleString == "" {
styleName = DEFAULT_CODE_STYLE
} else {
styleName = highlightStyleString
}
highlightStyle := styles.Get(DEFAULT_CODE_STYLE)
if style, ok := styles.Registry[styleName]; ok {
highlightStyle = style
} else {
fmt.Printf("invaid style: %s\n", styleName)
}
htmlFormatter := html.New(html.Standalone(true), html.TabWidth(2))
if htmlFormatter == nil {
return nil, errors.New("couldn't create html formatter")
}
mdhtmlRenderer := mdhtmlRenderer(highlightStyle, htmlFormatter)
return &MarkdownToHTMLRenderer{highlightStyle, htmlFormatter, mdhtmlRenderer}, nil
}
func (m MarkdownToHTMLRenderer) MarkdownBytesToHTML(md []byte) string {
htmlBytes := markdown.ToHTML(md, nil, m.mdhtmlRenderer)
return string(htmlBytes)
}
// based on https://github.com/alecthomas/chroma/blob/master/quick/quick.go
func htmlHighlight(
w io.Writer,
source, lang,
defaultLang string,
highlightStyle *chroma.Style,
htmlFormatter *html.Formatter,
) error {
if lang == "" {
lang = defaultLang
}
l := lexers.Get(lang)
if l == nil {
l = lexers.Analyse(source)
}
if l == nil {
l = lexers.Fallback
}
l = chroma.Coalesce(l)
it, err := l.Tokenise(nil, source)
if err != nil {
return err
}
return htmlFormatter.Format(w, highlightStyle, it)
}
func renderCode(
w io.Writer,
codeBlock *ast.CodeBlock,
highlightStyle *chroma.Style,
htmlFormatter *html.Formatter,
) error {
defaultLang := ""
lang := string(codeBlock.Info)
return htmlHighlight(
w,
string(codeBlock.Literal),
lang,
defaultLang,
highlightStyle,
htmlFormatter,
)
}
func mdhtmlRenderer(highlightStyle *chroma.Style, htmlFormatter *html.Formatter) *mdhtml.Renderer {
opts := mdhtml.RendererOptions{
Flags: mdhtml.CommonFlags | mdhtml.HrefTargetBlank,
RenderNodeHook: func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
if code, ok := node.(*ast.CodeBlock); ok {
w.Write([]byte(`<div class="my-4 rounded-xl shadow-lg [&>pre]:p-4">`))
err := renderCode(w, code, highlightStyle, htmlFormatter)
if err != nil {
fmt.Println("error rendering code")
return ast.Terminate, false
}
w.Write([]byte("</div>"))
return ast.GoToNext, true
}
if link, ok := node.(*ast.Link); ok {
if entering {
w.Write(
[]byte(
`<a class="font-medium text-green-600 dark:text-green-400 hover:underline"`,
),
)
if len(link.Title) > 0 {
w.Write([]byte(fmt.Sprintf(` title="link" href="%s"`, link.Title)))
} else if len(link.Destination) > 0 {
w.Write([]byte(fmt.Sprintf(` href="%s"`, link.Destination)))
}
w.Write([]byte(">"))
} else {
w.Write([]byte("</a>"))
}
return ast.GoToNext, true
}
if heading, ok := node.(*ast.Heading); ok {
headingClass := fmt.Sprintf(
"myh myh-%d",
min(heading.Level, 6), // max supported level is 6
)
if headingClass != "" {
attr := heading.Attribute
if attr == nil {
attr = &ast.Attribute{}
}
attr.Classes = append(
attr.Classes,
[]byte(headingClass),
)
heading.Attribute = attr
}
}
if list, ok := node.(*ast.List); ok {
listClass := "list-disc"
if list.ListFlags&ast.ListTypeOrdered != 0 {
listClass = "list-decimal"
}
if entering {
// Start of the list
fmt.Fprintf(w, `<ul class="%s ml-6">`, listClass)
} else {
// End of the list
fmt.Fprintf(w, "</ul>")
}
return ast.GoToNext, true
}
if li, ok := node.(*ast.ListItem); ok {
attr := li.Attribute
if attr == nil {
attr = &ast.Attribute{}
}
attr.Classes = append(attr.Classes, []byte("text-lg"))
if entering {
w.Write([]byte(`<li class="text-lg">`))
} else {
w.Write([]byte("</li>"))
}
return ast.GoToNext, true
}
if p, ok := node.(*ast.Paragraph); ok {
attr := p.Attribute
if attr == nil {
attr = &ast.Attribute{}
}
attr.Classes = append(attr.Classes, []byte("text-lg"))
p.Attribute = attr
}
// return false to tell html.Renderer to use default render
return ast.GoToNext, false
},
}
return mdhtml.NewRenderer(opts)
}
// assumes lists can be wrapped and we will still find parent lists, for exmaple
// ````
// <div><ul><li>list item</li></ul></div>
// ````
func calculateListDepth(node ast.Node) int {
depth := 0
parent := node.GetParent()
for parent != nil {
if _, ok := parent.(*ast.List); ok {
depth++
}
parent = parent.GetParent()
}
return depth
}