1
0
mirror of https://github.com/alecthomas/chroma.git synced 2025-03-29 21:56:56 +02:00

Extend lexers.Get() to support filenames.

Fixes .
This commit is contained in:
Alec Thomas 2017-11-24 13:32:17 +11:00
parent 9c81d25368
commit 2e7e1e1580
2 changed files with 40 additions and 3 deletions

@ -3,6 +3,7 @@ package lexers
import (
"path/filepath"
"sort"
"strings"
"github.com/danwakefield/fnmatch"
@ -33,12 +34,34 @@ func Names(withAliases bool) []string {
return out
}
// Get a Lexer by name.
// Get a Lexer by name, alias or file extension.
func Get(name string) chroma.Lexer {
candidates := chroma.PrioritisedLexers{}
if lexer := Registry.byName[name]; lexer != nil {
return lexer
candidates = append(candidates, lexer)
}
return Registry.byAlias[name]
if lexer := Registry.byAlias[name]; lexer != nil {
candidates = append(candidates, lexer)
}
if lexer := Registry.byName[strings.ToLower(name)]; lexer != nil {
candidates = append(candidates, lexer)
}
if lexer := Registry.byAlias[strings.ToLower(name)]; lexer != nil {
candidates = append(candidates, lexer)
}
// Try file extension.
if lexer := Match("filename." + name); lexer != nil {
candidates = append(candidates, lexer)
}
// Try exact filename.
if lexer := Match(name); lexer != nil {
candidates = append(candidates, lexer)
}
if len(candidates) == 0 {
return nil
}
sort.Sort(candidates)
return candidates[0]
}
// MatchMimeType attempts to find a lexer for the given MIME type.
@ -112,8 +135,10 @@ func Analyse(text string) chroma.Lexer {
func Register(lexer chroma.Lexer) chroma.Lexer {
config := lexer.Config()
Registry.byName[config.Name] = lexer
Registry.byName[strings.ToLower(config.Name)] = lexer
for _, alias := range config.Aliases {
Registry.byAlias[alias] = lexer
Registry.byAlias[strings.ToLower(alias)] = lexer
}
Registry.Lexers = append(Registry.Lexers, lexer)
return lexer

@ -19,3 +19,15 @@ func TestCompileAllRegexes(t *testing.T) {
assert.NoError(t, err, "%s failed", lexer.Config().Name)
}
}
func TestGet(t *testing.T) {
t.Run("ByName", func(t *testing.T) {
assert.Equal(t, lexers.Get("xml"), lexers.XML)
})
t.Run("ByAlias", func(t *testing.T) {
assert.Equal(t, lexers.Get("as"), lexers.Actionscript)
})
t.Run("ViaFilename", func(t *testing.T) {
assert.Equal(t, lexers.Get("svg"), lexers.XML)
})
}