diff options
author | Runxi Yu <me@runxiyu.org> | 2025-04-05 12:34:14 +0800 |
---|---|---|
committer | Runxi Yu <me@runxiyu.org> | 2025-04-05 12:36:54 +0800 |
commit | d15089b985122d0841afdd1379791fa9deefa374 (patch) | |
tree | 633d3c95347dfdab65daefc4d4557a0e7fe08bbb /chroma.go | |
parent | git2d: Add a basic command for tree (diff) | |
download | forge-d15089b985122d0841afdd1379791fa9deefa374.tar.gz forge-d15089b985122d0841afdd1379791fa9deefa374.tar.zst forge-d15089b985122d0841afdd1379791fa9deefa374.zip |
HTTP: Make the tree and raw endpoints use git2d
Diffstat (limited to 'chroma.go')
-rw-r--r-- | chroma.go | 35 |
1 files changed, 35 insertions, 0 deletions
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("<pre>Error tokenizing file: " + err.Error() + "</pre>") + } + + 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("<pre>Error formatting file: " + err.Error() + "</pre>") + } + + return template.HTML(buf.Bytes()) //#nosec G203 +} |