From d15089b985122d0841afdd1379791fa9deefa374 Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sat, 5 Apr 2025 12:34:14 +0800 Subject: HTTP: Make the tree and raw endpoints use git2d --- chroma.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 chroma.go (limited to 'chroma.go') diff --git a/chroma.go b/chroma.go new file mode 100644 index 0000000..5a9f99f --- /dev/null +++ b/chroma.go @@ -0,0 +1,35 @@ +package main + +import ( + "bytes" + "html/template" + + chromaHTML "github.com/alecthomas/chroma/v2/formatters/html" + chromaLexers "github.com/alecthomas/chroma/v2/lexers" + chromaStyles "github.com/alecthomas/chroma/v2/styles" +) + +func renderHighlightedFile(filename, content string) template.HTML { + lexer := chromaLexers.Match(filename) + if lexer == nil { + lexer = chromaLexers.Fallback + } + + iterator, err := lexer.Tokenise(nil, content) + if err != nil { + return template.HTML("
Error tokenizing file: " + err.Error() + "
") + } + + var buf bytes.Buffer + style := chromaStyles.Get("autumn") + formatter := chromaHTML.New( + chromaHTML.WithClasses(true), + chromaHTML.TabWidth(8), + ) + + if err := formatter.Format(&buf, style, iterator); err != nil { + return template.HTML("
Error formatting file: " + err.Error() + "
") + } + + return template.HTML(buf.Bytes()) //#nosec G203 +} -- cgit v1.2.3