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

383 lines
8.6 KiB
Go

10 years ago
package fzf
import (
"regexp"
"sort"
10 years ago
"strings"
"github.com/junegunn/fzf/src/algo"
"github.com/junegunn/fzf/src/util"
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
}
type termSet []term
10 years ago
// Pattern represents search pattern
10 years ago
type Pattern struct {
fuzzy bool
extended bool
10 years ago
caseSensitive bool
forward bool
10 years ago
text []rune
termSets []termSet
cacheable bool
delimiter Delimiter
10 years ago
nth []Range
procFun map[termType]func(bool, bool, []rune, []rune) algo.Result
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
// search 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
func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,
nth []Range, delimiter Delimiter, runes []rune) *Pattern {
10 years ago
var asString string
if extended {
10 years ago
asString = strings.Trim(string(runes), " ")
} else {
10 years ago
asString = string(runes)
}
cached, found := _patternCache[asString]
if found {
return cached
}
caseSensitive, cacheable := true, true
termSets := []termSet{}
10 years ago
if extended {
termSets = parseTerms(fuzzy, caseMode, asString)
Loop:
for _, termSet := range termSets {
for idx, term := range termSet {
// If the query contains inverse search terms or OR operators,
// we cannot cache the search scope
if idx > 0 || term.inv {
cacheable = false
break Loop
}
10 years ago
}
}
} else {
lowerString := strings.ToLower(asString)
caseSensitive = caseMode == CaseRespect ||
caseMode == CaseSmart && lowerString != asString
if !caseSensitive {
asString = lowerString
}
10 years ago
}
ptr := &Pattern{
fuzzy: fuzzy,
extended: extended,
10 years ago
caseSensitive: caseSensitive,
forward: forward,
text: []rune(asString),
termSets: termSets,
cacheable: cacheable,
10 years ago
nth: nth,
delimiter: delimiter,
procFun: make(map[termType]func(bool, bool, []rune, []rune) algo.Result)}
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(fuzzy bool, caseMode Case, str string) []termSet {
10 years ago
tokens := _splitRegex.Split(str, -1)
sets := []termSet{}
set := termSet{}
switchSet := false
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)
if !fuzzy {
10 years ago
typ = termExact
10 years ago
}
if text == "|" {
switchSet = false
continue
}
10 years ago
if strings.HasPrefix(text, "!") {
inv = true
text = text[1:]
}
if strings.HasPrefix(text, "'") {
// Flip exactness
if fuzzy {
10 years ago
typ = termExact
10 years ago
text = text[1:]
} else {
typ = termFuzzy
text = text[1:]
10 years ago
}
} 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 {
if switchSet {
sets = append(sets, set)
set = termSet{}
}
set = append(set, term{
typ: typ,
inv: inv,
text: []rune(text),
caseSensitive: caseSensitive,
origText: origText})
switchSet = true
10 years ago
}
}
if len(set) > 0 {
sets = append(sets, set)
}
return sets
10 years ago
}
10 years ago
// IsEmpty returns true if the pattern is effectively empty
10 years ago
func (p *Pattern) IsEmpty() bool {
if !p.extended {
10 years ago
return len(p.text) == 0
}
return len(p.termSets) == 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 {
if !p.extended {
10 years ago
return p.AsString()
}
cacheableTerms := []string{}
for _, termSet := range p.termSets {
if len(termSet) == 1 && !termSet[0].inv {
cacheableTerms = append(cacheableTerms, string(termSet[0].origText))
10 years ago
}
}
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.cacheable {
10 years ago
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.cacheable {
10 years ago
_cache.Add(chunk, cacheKey, matches)
}
return matches
}
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
matches := []*Item{}
if !p.extended {
for _, item := range *chunk {
offset, bonus := p.basicMatch(item)
if sidx := offset[0]; sidx >= 0 {
matches = append(matches,
dupItem(item, []Offset{offset}, bonus))
}
}
} else {
for _, item := range *chunk {
if offsets, bonus := p.extendedMatch(item); len(offsets) == len(p.termSets) {
matches = append(matches, dupItem(item, offsets, bonus))
}
}
}
return matches
}
// MatchItem returns true if the Item is a match
func (p *Pattern) MatchItem(item *Item) bool {
if !p.extended {
offset, _ := p.basicMatch(item)
sidx := offset[0]
return sidx >= 0
}
offsets, _ := p.extendedMatch(item)
return len(offsets) == len(p.termSets)
}
func dupItem(item *Item, offsets []Offset, bonus int32) *Item {
sort.Sort(ByOrder(offsets))
return &Item{
text: item.text,
origText: item.origText,
transformed: item.transformed,
offsets: offsets,
bonus: bonus,
colors: item.colors,
rank: buildEmptyRank(item.Index())}
}
func (p *Pattern) basicMatch(item *Item) (Offset, int32) {
input := p.prepareInput(item)
if p.fuzzy {
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)
}
return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)
10 years ago
}
func (p *Pattern) extendedMatch(item *Item) ([]Offset, int32) {
input := p.prepareInput(item)
offsets := []Offset{}
var totalBonus int32
for _, termSet := range p.termSets {
var offset *Offset
var bonus int32
for _, term := range termSet {
pfun := p.procFun[term.typ]
off, pen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)
if sidx := off[0]; sidx >= 0 {
if term.inv {
continue
}
offset, bonus = &off, pen
break
} else if term.inv {
offset, bonus = &Offset{0, 0, 0}, 0
continue
10 years ago
}
}
if offset != nil {
offsets = append(offsets, *offset)
totalBonus += bonus
}
10 years ago
}
return offsets, totalBonus
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, trimLength: util.TrimLen(item.text)}}
10 years ago
}
item.transformed = ret
return ret
}
func (p *Pattern) iter(pfun func(bool, bool, []rune, []rune) algo.Result,
tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int32) {
for _, part := range tokens {
prefixLength := int32(part.prefixLength)
if res := pfun(caseSensitive, forward, part.text, pattern); res.Start >= 0 {
var sidx int32 = res.Start + prefixLength
var eidx int32 = res.End + prefixLength
return Offset{sidx, eidx, int32(part.trimLength)}, res.Bonus
10 years ago
}
}
// TODO: math.MaxUint16
return Offset{-1, -1, -1}, 0.0
10 years ago
}