Skip to content

Commit 692256e

Browse files
authored
Merge pull request #906 from rumpl/lexer-cache
perf: cache lexers per file extension in syntax highlighting
2 parents 7f09e89 + a95e24e commit 692256e

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

pkg/tui/components/tool/editfile/render.go

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import (
44
"encoding/json"
55
"fmt"
66
"os"
7+
"path/filepath"
78
"strings"
9+
"sync"
810

911
"charm.land/lipgloss/v2"
1012
"github.com/alecthomas/chroma/v2"
@@ -25,6 +27,11 @@ const (
2527
minWidth = 80
2628
)
2729

30+
var (
31+
lexerCache = make(map[string]chroma.Lexer)
32+
lexerCacheMu sync.RWMutex
33+
)
34+
2835
type chromaToken struct {
2936
Text string
3037
Style lipgloss.Style
@@ -127,11 +134,25 @@ func normalizeDiff(diff []*udiff.Hunk) []*udiff.Hunk {
127134
}
128135

129136
func syntaxHighlight(code, filePath string) []chromaToken {
130-
lexer := lexers.Match(filePath)
131-
if lexer == nil {
132-
lexer = lexers.Fallback
137+
ext := filepath.Ext(filePath)
138+
139+
// Try to get lexer from cache
140+
lexerCacheMu.RLock()
141+
lexer, ok := lexerCache[ext]
142+
lexerCacheMu.RUnlock()
143+
144+
if !ok {
145+
// Cache miss - compute and store
146+
lexer = lexers.Match(filePath)
147+
if lexer == nil {
148+
lexer = lexers.Fallback
149+
}
150+
lexer = chroma.Coalesce(lexer)
151+
152+
lexerCacheMu.Lock()
153+
lexerCache[ext] = lexer
154+
lexerCacheMu.Unlock()
133155
}
134-
lexer = chroma.Coalesce(lexer)
135156

136157
style := styles.ChromaStyle()
137158
iterator, err := lexer.Tokenise(nil, code)

0 commit comments

Comments
 (0)