Allow custom highlight mapping beyond file extensions (#15808)

Co-authored-by: Lauris BH <lauris@nix.lv>
release/v1.15
mlpo 2021-05-13 11:31:23 +02:00 committed by GitHub
parent 27b29ffb22
commit 52f8dcda43
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 10 deletions

View File

@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/analyze" "code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html" "github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers" "github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles" "github.com/alecthomas/chroma/styles"
@ -66,15 +67,18 @@ func Code(fileName, code string) string {
htmlbuf := bytes.Buffer{} htmlbuf := bytes.Buffer{}
htmlw := bufio.NewWriter(&htmlbuf) htmlw := bufio.NewWriter(&htmlbuf)
var lexer chroma.Lexer
if val, ok := highlightMapping[filepath.Ext(fileName)]; ok { if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
//change file name to one with mapped extension so we look that up instead //use mapped value to find lexer
fileName = "mapped." + val lexer = lexers.Get(val)
} }
lexer := lexers.Match(fileName) if lexer == nil {
lexer = lexers.Match(fileName)
if lexer == nil { if lexer == nil {
lexer = lexers.Fallback lexer = lexers.Fallback
} }
}
iterator, err := lexer.Tokenise(nil, string(code)) iterator, err := lexer.Tokenise(nil, string(code))
if err != nil { if err != nil {
@ -114,19 +118,22 @@ func File(numLines int, fileName string, code []byte) map[int]string {
htmlbuf := bytes.Buffer{} htmlbuf := bytes.Buffer{}
htmlw := bufio.NewWriter(&htmlbuf) htmlw := bufio.NewWriter(&htmlbuf)
var lexer chroma.Lexer
if val, ok := highlightMapping[filepath.Ext(fileName)]; ok { if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
fileName = "test." + val lexer = lexers.Get(val)
} }
if lexer == nil {
language := analyze.GetCodeLanguage(fileName, code) language := analyze.GetCodeLanguage(fileName, code)
lexer := lexers.Get(language) lexer = lexers.Get(language)
if lexer == nil { if lexer == nil {
lexer = lexers.Match(fileName) lexer = lexers.Match(fileName)
if lexer == nil { if lexer == nil {
lexer = lexers.Fallback lexer = lexers.Fallback
} }
} }
}
iterator, err := lexer.Tokenise(nil, string(code)) iterator, err := lexer.Tokenise(nil, string(code))
if err != nil { if err != nil {