-
Notifications
You must be signed in to change notification settings - Fork 7
/
markdownfmt.go
55 lines (47 loc) · 1.34 KB
/
markdownfmt.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
package markdownfmt
import (
"bytes"
"os"
"github.com/Kunde21/markdownfmt/v3/markdown"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
)
// NewGoldmark builds a new [goldmark.Markdown] object
// capable of reformatting GitHub Formatted Markdown.
func NewGoldmark(opts ...markdown.Option) goldmark.Markdown {
mr := markdown.NewRenderer()
mr.AddMarkdownOptions(opts...)
extensions := []goldmark.Extender{
extension.GFM,
}
parserOptions := []parser.Option{
parser.WithAttribute(), // We need this to enable # headers {#custom-ids}.
}
gm := goldmark.New(
goldmark.WithExtensions(extensions...),
goldmark.WithParserOptions(parserOptions...),
goldmark.WithRenderer(mr),
)
return gm
}
// Process formats given Markdown.
func Process(filename string, src []byte, opts ...markdown.Option) ([]byte, error) {
text, err := readSource(filename, src)
if err != nil {
return nil, err
}
output := bytes.NewBuffer(nil)
if err := NewGoldmark(opts...).Convert(text, output); err != nil {
return nil, err
}
return output.Bytes(), nil
}
// If src != nil, readSource returns src.
// If src == nil, readSource returns the result of reading the file specified by filename.
func readSource(filename string, src []byte) ([]byte, error) {
if src != nil {
return src, nil
}
return os.ReadFile(filename)
}