-
Notifications
You must be signed in to change notification settings - Fork 1
/
mdrender.go
71 lines (61 loc) · 1.49 KB
/
mdrender.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
package markdown
import (
"bytes"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/util"
highlighting "github.com/yuin/goldmark-highlighting"
"github.com/alecthomas/chroma/formatters/html"
)
// Render renders markdown to html
type Converter struct {
markdown goldmark.Markdown
}
type Document struct {
Title string
Preview string
Body string
}
// NewRender create new renderer
func NewConverter() *Converter {
md := goldmark.New(
goldmark.WithExtensions(
extension.GFM,
extension.Footnote,
extension.Typographer,
highlighting.NewHighlighting(
highlighting.WithStyle("monokai"),
highlighting.WithFormatOptions(
html.WithLineNumbers(true),
),
),
TableOfContentsShortcode,
),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
parser.WithASTTransformers(
util.Prioritized(&titleExtractorTransformer{}, 500),
),
),
goldmark.WithRendererOptions(),
)
return &Converter{md}
}
// Converter markdown to html
func (r *Converter) Convert(data []byte) (*Document, error) {
var ctx = parser.NewContext()
var htmlBuf bytes.Buffer
if err := r.markdown.Convert(data, &htmlBuf, parser.WithContext(ctx)); err != nil {
return nil, err
}
doc := &Document{
Body: htmlBuf.String(),
}
previewText, ok := ctx.Get(titleParserCtxKey).(*PagePreviewText)
if ok && previewText != nil {
doc.Title = previewText.Title
doc.Preview = previewText.Preview
}
return doc, nil
}