-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
html.go
37 lines (30 loc) · 916 Bytes
/
html.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
package renderer
import (
"bytes"
"fmt"
"html/template"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/styles"
)
// ToSyntaxHighlightedHTML returns HTML of the syntax highlighted code via Chroma
func ToSyntaxHighlightedHTML(fileType string, fileContent []byte) (template.HTML, error) {
lexer := GetLexer(fileType)
it, err := lexer.Tokenise(nil, string(fileContent))
if err != nil {
return "", err
}
formatter := html.New(
html.WithClasses(true),
html.WithAllClasses(true),
html.WithLineNumbers(true),
html.WithLinkableLineNumbers(true, "L"),
)
chromaHTML := bytes.NewBuffer(nil)
// using fallback style because we'll use custom prebaked CSS
err = formatter.Format(chromaHTML, styles.Fallback, it)
if err != nil {
return "", err
}
wrapped := fmt.Sprintf("<div class=\"code\">%s</div>", chromaHTML.String())
return template.HTML(wrapped), nil
}