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
|
package html
import (
"bytes"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
"go.abhg.dev/goldmark/toc"
"github.com/alecthomas/chroma/v2"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
chromastyles "github.com/alecthomas/chroma/v2/styles"
highlighting "github.com/yuin/goldmark-highlighting/v2"
)
func MDToHTML(md []byte, hasToc bool) []byte {
style := chromastyles.Get("autumn")
style, err := style.Builder().Add(chroma.Background, "bg:#f0f0f0").Build()
if err != nil {
return nil
}
extensions := []goldmark.Extender{
extension.GFM,
extension.Footnote,
highlighting.NewHighlighting(
highlighting.WithCustomStyle(style),
highlighting.WithFormatOptions(
chromahtml.WrapLongLines(true),
chromahtml.InlineCode(true),
chromahtml.TabWidth(4),
chromahtml.PreventSurroundingPre(false),
),
),
}
if hasToc {
extensions = append(extensions, &toc.Extender{
Compact: true,
})
}
converter := goldmark.New(
goldmark.WithExtensions(extensions...),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
html.WithHardWraps(),
html.WithXHTML(),
),
)
var buf bytes.Buffer
err = converter.Convert(md, &buf)
if err != nil {
return nil
}
return buf.Bytes()
}
|