package rendering import ( "bytes" "html/template" chromalib "github.com/alecthomas/chroma/v2" chromahtml "github.com/alecthomas/chroma/v2/formatters/html" "github.com/alecthomas/chroma/v2/lexers" "github.com/alecthomas/chroma/v2/styles" ) func HighlightCode(content, filename string) (string, string) { lexer := lexers.Match(filename) if lexer == nil { lexer = lexers.Analyse(content) } if lexer == nil { lexer = lexers.Fallback } lexer = chromalib.Coalesce(lexer) style := styles.Get("onedark") if style == nil { style = styles.Fallback } formatter := chromahtml.New( chromahtml.WithClasses(true), chromahtml.TabWidth(4), chromahtml.WithLineNumbers(true), chromahtml.LineNumbersInTable(true), ) var cssBuf bytes.Buffer if err := formatter.WriteCSS(&cssBuf, style); err != nil { return plainFallback(content), "" } chromaCSS := cssBuf.String() iterator, err := lexer.Tokenise(nil, content) if err != nil { return plainFallback(content), chromaCSS } var hlBuf bytes.Buffer if err := formatter.Format(&hlBuf, style, iterator); err != nil { return plainFallback(content), chromaCSS } return hlBuf.String(), chromaCSS } func plainFallback(content string) string { return `
` +
template.HTMLEscapeString(content) + ``
}