Skip to content

Commit e37ceb4

Browse files
committed
Allow custom highlight mapping beyond file extensions
1 parent 2e0f315 commit e37ceb4

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

modules/highlight/highlight.go

+17-10
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"code.gitea.io/gitea/modules/analyze"
1717
"code.gitea.io/gitea/modules/log"
1818
"code.gitea.io/gitea/modules/setting"
19+
"github.com/alecthomas/chroma"
1920
"github.com/alecthomas/chroma/formatters/html"
2021
"github.com/alecthomas/chroma/lexers"
2122
"github.com/alecthomas/chroma/styles"
@@ -66,14 +67,17 @@ func Code(fileName, code string) string {
6667
htmlbuf := bytes.Buffer{}
6768
htmlw := bufio.NewWriter(&htmlbuf)
6869

70+
var lexer chroma.Lexer
6971
if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
70-
//change file name to one with mapped extension so we look that up instead
71-
fileName = "mapped." + val
72+
//use mapped value to find lexer
73+
lexer = lexers.Get(val)
7274
}
7375

74-
lexer := lexers.Match(fileName)
7576
if lexer == nil {
76-
lexer = lexers.Fallback
77+
lexer = lexers.Match(fileName)
78+
if lexer == nil {
79+
lexer = lexers.Fallback
80+
}
7781
}
7882

7983
iterator, err := lexer.Tokenise(nil, string(code))
@@ -114,17 +118,20 @@ func File(numLines int, fileName string, code []byte) map[int]string {
114118
htmlbuf := bytes.Buffer{}
115119
htmlw := bufio.NewWriter(&htmlbuf)
116120

121+
var lexer chroma.Lexer
117122
if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
118-
fileName = "test." + val
123+
lexer = lexers.Get(val)
119124
}
120125

121-
language := analyze.GetCodeLanguage(fileName, code)
122-
123-
lexer := lexers.Get(language)
124126
if lexer == nil {
125-
lexer = lexers.Match(fileName)
127+
language := analyze.GetCodeLanguage(fileName, code)
128+
129+
lexer = lexers.Get(language)
126130
if lexer == nil {
127-
lexer = lexers.Fallback
131+
lexer = lexers.Match(fileName)
132+
if lexer == nil {
133+
lexer = lexers.Fallback
134+
}
128135
}
129136
}
130137

0 commit comments

Comments
 (0)