aboutsummaryrefslogtreecommitdiff
path: root/internal/render/chroma.go
diff options
context:
space:
mode:
authorRunxi Yu <me@runxiyu.org>2025-04-05 21:27:17 +0800
committerRunxi Yu <me@runxiyu.org>2025-04-05 21:27:17 +0800
commite0635b47c2f30719e1ea026812af85c988632c0e (patch)
treef112904c018dc294cf6f902423745f1f1932449c /internal/render/chroma.go
parentExport symbols from database.go (diff)
downloadforge-e0635b47c2f30719e1ea026812af85c988632c0e.tar.gz
forge-e0635b47c2f30719e1ea026812af85c988632c0e.tar.zst
forge-e0635b47c2f30719e1ea026812af85c988632c0e.zip
Move things to internal/v0.1.23
Diffstat (limited to 'internal/render/chroma.go')
-rw-r--r--internal/render/chroma.go35
1 files changed, 35 insertions, 0 deletions
diff --git a/internal/render/chroma.go b/internal/render/chroma.go
new file mode 100644
index 0000000..c7d64ec
--- /dev/null
+++ b/internal/render/chroma.go
@@ -0,0 +1,35 @@
+package render
+
+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 Highlight(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>") //#nosec G203`
+ }
+
+ 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>") //#nosec G203
+ }
+
+ return template.HTML(buf.Bytes()) //#nosec G203
+}