-
Notifications
You must be signed in to change notification settings - Fork 0
/
highlight.go
48 lines (40 loc) · 977 Bytes
/
highlight.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
package server
import (
"bytes"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
)
type highlighter struct {
style *chroma.Style
formatter *html.Formatter
css []byte
}
func newHighlighter(style string) *highlighter {
return &highlighter{
style: styles.Get(style),
formatter: html.New(html.WithClasses(true), html.ClassPrefix("-devcard-hl-")),
}
}
func (h *highlighter) CSS() []byte {
out := new(bytes.Buffer)
err := h.formatter.WriteCSS(out, h.style)
if err != nil {
return nil
}
return out.Bytes()
}
func (h *highlighter) Highlight(src, lang string) (string, error) {
lexer := lexers.Get(lang)
iterator, err := lexer.Tokenise(nil, src)
if err != nil {
return "", err
}
out := new(bytes.Buffer)
err = h.formatter.Format(out, h.style, iterator)
if err != nil {
return "", err
}
return out.String(), nil
}