package main
import (
"bytes"
"html/template"
"path/filepath"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
)
var formatter = html.New(
html.WithClasses(true),
html.WithLineNumbers(true),
html.LineNumbersInTable(true),
html.WithLinkableLineNumbers(true, "L"),
html.TabWidth(4),
)
var highlightStyle = styles.Get("pygments")
func highlight(name string, content []byte) (template.HTML, bool) {
if len(content) > 256<<10 {
return "", false
}
lexer := lexers.Match(filepath.Base(name))
if lexer == nil {
lexer = lexers.Analyse(string(content))
}
if lexer == nil {
return "", false
}
lexer = chroma.Coalesce(lexer)
iterator, err := lexer.Tokenise(nil, string(content))
if err != nil {
return "", false
}
var buf bytes.Buffer
if err := formatter.Format(&buf, highlightStyle, iterator); err != nil {
return "", false
}
return template.HTML(buf.String()), true
}
func highlightCSS() []byte {
var buf bytes.Buffer
formatter.WriteCSS(&buf, highlightStyle)
return buf.Bytes()
}