blog/markdown/markdown.go

59 lines
1.4 KiB
Go

package markdown
import (
"bytes"
"fmt"
"io"
chromahtml "github.com/alecthomas/chroma/formatters/html"
"github.com/yuin/goldmark"
emoji "github.com/yuin/goldmark-emoji"
highlighting "github.com/yuin/goldmark-highlighting"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
_ "go.jolheiser.com/chroma-catppuccin/chroma1"
)
var gm = func() goldmark.Markdown {
var codeblockIdx int
return goldmark.New(
goldmark.WithExtensions(
extension.GFM,
highlighting.NewHighlighting(
highlighting.WithStyle("catppuccin"),
highlighting.WithFormatOptions(
chromahtml.WithLineNumbers(true),
chromahtml.LineNumbersInTable(true),
),
highlighting.WithCodeBlockOptions(func(ctx highlighting.CodeBlockContext) []chromahtml.Option {
codeblockIdx++
return []chromahtml.Option{
chromahtml.LinkableLineNumbers(true, fmt.Sprintf("code%d-", codeblockIdx)),
}
}),
),
emoji.Emoji,
),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
html.WithHardWraps(),
),
)
}
// Convert transforms a markdown document into HTML
func Convert(r io.Reader) (string, error) {
content, err := io.ReadAll(r)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := gm().Convert(content, &buf); err != nil {
return "", err
}
return buf.String(), nil
}