You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fzf/src/pattern.go

334 lines
7.5 KiB
Go

10 years ago
package fzf
import (
"regexp"
"sort"
10 years ago
"strings"
"github.com/junegunn/fzf/src/algo"
10 years ago
)
// fuzzy
// 'exact
// ^exact-prefix
// exact-suffix$
// !not-fuzzy
// !'not-exact
// !^not-exact-prefix
// !not-exact-suffix$
10 years ago
type termType int
10 years ago
const (
10 years ago
termFuzzy termType = iota
termExact
termPrefix
termSuffix
termEqual
10 years ago
)
10 years ago
type term struct {
typ termType
inv bool
text []rune
caseSensitive bool
origText []rune
10 years ago
}
10 years ago
// Pattern represents search pattern
10 years ago
type Pattern struct {
mode Mode
caseSensitive bool
text []rune
10 years ago
terms []term
10 years ago
hasInvTerm bool
delimiter Delimiter
10 years ago
nth []Range
procFun map[termType]func(bool, []rune, []rune) (int, int)
10 years ago
}
var (
_patternCache map[string]*Pattern
_splitRegex *regexp.Regexp
_cache ChunkCache
)
func init() {
_splitRegex = regexp.MustCompile("\\s+")
clearPatternCache()
clearChunkCache()
10 years ago
}
func clearPatternCache() {
// We can uniquely identify the pattern for a given string since
// mode and caseMode do not change while the program is running
10 years ago
_patternCache = make(map[string]*Pattern)
}
func clearChunkCache() {
_cache = NewChunkCache()
}
10 years ago
// BuildPattern builds Pattern object from the given arguments
10 years ago
func BuildPattern(mode Mode, caseMode Case,
nth []Range, delimiter Delimiter, runes []rune) *Pattern {
10 years ago
var asString string
switch mode {
10 years ago
case ModeExtended, ModeExtendedExact:
10 years ago
asString = strings.Trim(string(runes), " ")
default:
asString = string(runes)
}
cached, found := _patternCache[asString]
if found {
return cached
}
caseSensitive, hasInvTerm := true, false
10 years ago
terms := []term{}
10 years ago
switch mode {
10 years ago
case ModeExtended, ModeExtendedExact:
terms = parseTerms(mode, caseMode, asString)
10 years ago
for _, term := range terms {
if term.inv {
hasInvTerm = true
}
}
default:
lowerString := strings.ToLower(asString)
caseSensitive = caseMode == CaseRespect ||
caseMode == CaseSmart && lowerString != asString
if !caseSensitive {
asString = lowerString
}
10 years ago
}
ptr := &Pattern{
mode: mode,
caseSensitive: caseSensitive,
text: []rune(asString),
10 years ago
terms: terms,
hasInvTerm: hasInvTerm,
nth: nth,
delimiter: delimiter,
procFun: make(map[termType]func(bool, []rune, []rune) (int, int))}
10 years ago
ptr.procFun[termFuzzy] = algo.FuzzyMatch
ptr.procFun[termEqual] = algo.EqualMatch
ptr.procFun[termExact] = algo.ExactMatchNaive
ptr.procFun[termPrefix] = algo.PrefixMatch
ptr.procFun[termSuffix] = algo.SuffixMatch
10 years ago
_patternCache[asString] = ptr
return ptr
}
func parseTerms(mode Mode, caseMode Case, str string) []term {
10 years ago
tokens := _splitRegex.Split(str, -1)
10 years ago
terms := []term{}
10 years ago
for _, token := range tokens {
10 years ago
typ, inv, text := termFuzzy, false, token
lowerText := strings.ToLower(text)
caseSensitive := caseMode == CaseRespect ||
caseMode == CaseSmart && text != lowerText
if !caseSensitive {
text = lowerText
}
10 years ago
origText := []rune(text)
10 years ago
if mode == ModeExtendedExact {
typ = termExact
10 years ago
}
if strings.HasPrefix(text, "!") {
inv = true
text = text[1:]
}
if strings.HasPrefix(text, "'") {
10 years ago
if mode == ModeExtended {
typ = termExact
10 years ago
text = text[1:]
}
} else if strings.HasPrefix(text, "^") {
if strings.HasSuffix(text, "$") {
typ = termEqual
text = text[1 : len(text)-1]
} else {
typ = termPrefix
text = text[1:]
}
10 years ago
} else if strings.HasSuffix(text, "$") {
10 years ago
typ = termSuffix
10 years ago
text = text[:len(text)-1]
}
if len(text) > 0 {
10 years ago
terms = append(terms, term{
typ: typ,
inv: inv,
text: []rune(text),
caseSensitive: caseSensitive,
origText: origText})
10 years ago
}
}
return terms
}
10 years ago
// IsEmpty returns true if the pattern is effectively empty
10 years ago
func (p *Pattern) IsEmpty() bool {
10 years ago
if p.mode == ModeFuzzy {
10 years ago
return len(p.text) == 0
}
10 years ago
return len(p.terms) == 0
10 years ago
}
10 years ago
// AsString returns the search query in string type
10 years ago
func (p *Pattern) AsString() string {
return string(p.text)
}
10 years ago
// CacheKey is used to build string to be used as the key of result cache
10 years ago
func (p *Pattern) CacheKey() string {
10 years ago
if p.mode == ModeFuzzy {
10 years ago
return p.AsString()
}
cacheableTerms := []string{}
for _, term := range p.terms {
if term.inv {
continue
}
cacheableTerms = append(cacheableTerms, string(term.origText))
}
return strings.Join(cacheableTerms, " ")
}
10 years ago
// Match returns the list of matches Items in the given Chunk
10 years ago
func (p *Pattern) Match(chunk *Chunk) []*Item {
space := chunk
// ChunkCache: Exact match
cacheKey := p.CacheKey()
if !p.hasInvTerm { // Because we're excluding Inv-term from cache key
if cached, found := _cache.Find(chunk, cacheKey); found {
return cached
}
}
// ChunkCache: Prefix/suffix match
Loop:
for idx := 1; idx < len(cacheKey); idx++ {
// [---------| ] | [ |---------]
// [--------| ] | [ |--------]
// [-------| ] | [ |-------]
prefix := cacheKey[:len(cacheKey)-idx]
suffix := cacheKey[idx:]
for _, substr := range [2]*string{&prefix, &suffix} {
if cached, found := _cache.Find(chunk, *substr); found {
10 years ago
cachedChunk := Chunk(cached)
space = &cachedChunk
break Loop
10 years ago
}
}
}
matches := p.matchChunk(space)
10 years ago
if !p.hasInvTerm {
_cache.Add(chunk, cacheKey, matches)
}
return matches
}
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
matches := []*Item{}
if p.mode == ModeFuzzy {
for _, item := range *chunk {
if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {
matches = append(matches,
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))
}
}
} else {
for _, item := range *chunk {
if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {
matches = append(matches, dupItem(item, offsets))
}
}
}
return matches
}
// MatchItem returns true if the Item is a match
func (p *Pattern) MatchItem(item *Item) bool {
if p.mode == ModeFuzzy {
sidx, _ := p.fuzzyMatch(item)
return sidx >= 0
}
offsets := p.extendedMatch(item)
return len(offsets) == len(p.terms)
}
func dupItem(item *Item, offsets []Offset) *Item {
sort.Sort(ByOrder(offsets))
return &Item{
text: item.text,
origText: item.origText,
transformed: item.transformed,
index: item.index,
offsets: offsets,
colors: item.colors,
rank: Rank{0, 0, item.index}}
}
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
input := p.prepareInput(item)
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)
10 years ago
}
func (p *Pattern) extendedMatch(item *Item) []Offset {
input := p.prepareInput(item)
offsets := []Offset{}
for _, term := range p.terms {
pfun := p.procFun[term.typ]
if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {
if term.inv {
break
10 years ago
}
offsets = append(offsets, Offset{int32(sidx), int32(eidx)})
} else if term.inv {
offsets = append(offsets, Offset{0, 0})
10 years ago
}
}
return offsets
10 years ago
}
func (p *Pattern) prepareInput(item *Item) []Token {
10 years ago
if item.transformed != nil {
return item.transformed
}
var ret []Token
10 years ago
if len(p.nth) > 0 {
tokens := Tokenize(item.text, p.delimiter)
ret = Transform(tokens, p.nth)
} else {
ret = []Token{Token{text: item.text, prefixLength: 0}}
10 years ago
}
item.transformed = ret
return ret
}
func (p *Pattern) iter(pfun func(bool, []rune, []rune) (int, int),
tokens []Token, caseSensitive bool, pattern []rune) (int, int) {
for _, part := range tokens {
10 years ago
prefixLength := part.prefixLength
if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {
10 years ago
return sidx + prefixLength, eidx + prefixLength
}
}
return -1, -1
}