Skip to content

Commit

Permalink
Allow custom highlight mapping beyond file extensions (go-gitea#15808)
Browse files Browse the repository at this point in the history
Co-authored-by: Lauris BH <lauris@nix.lv>
  • Loading branch information
2 people authored and AbdulrhmnGhanem committed Aug 10, 2021
1 parent ca0971d commit 843fae9
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions modules/highlight/highlight.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
Expand Down Expand Up @@ -66,14 +67,17 @@ func Code(fileName, code string) string {
htmlbuf := bytes.Buffer{}
htmlw := bufio.NewWriter(&htmlbuf)

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

lexer := lexers.Match(fileName)
if lexer == nil {
lexer = lexers.Fallback
lexer = lexers.Match(fileName)
if lexer == nil {
lexer = lexers.Fallback
}
}

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

var lexer chroma.Lexer
if val, ok := highlightMapping[filepath.Ext(fileName)]; ok {
fileName = "test." + val
lexer = lexers.Get(val)
}

language := analyze.GetCodeLanguage(fileName, code)

lexer := lexers.Get(language)
if lexer == nil {
lexer = lexers.Match(fileName)
language := analyze.GetCodeLanguage(fileName, code)

lexer = lexers.Get(language)
if lexer == nil {
lexer = lexers.Fallback
lexer = lexers.Match(fileName)
if lexer == nil {
lexer = lexers.Fallback
}
}
}

Expand Down

0 comments on commit 843fae9

Please sign in to comment.