Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

343 lines · 7.8 KiB · Go

Last changed by

Make --extended defaultJunegunn Choibefore adoption81a8869

History of this file

Take it

1package fzf23import (4	"regexp"5	"sort"6	"strings"78	"github.com/junegunn/fzf/src/algo"9	"github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact14// ^exact-prefix15// exact-suffix$16// !not-fuzzy17// !'not-exact18// !^not-exact-prefix19// !not-exact-suffix$2021type termType int2223const (24	termFuzzy termType = iota25	termExact26	termPrefix27	termSuffix28	termEqual29)3031type term struct {32	typ           termType33	inv           bool34	text          []rune35	caseSensitive bool36	origText      []rune37}3839// Pattern represents search pattern40type Pattern struct {41	fuzzy         bool42	extended      bool43	caseSensitive bool44	forward       bool45	text          []rune46	terms         []term47	hasInvTerm    bool48	delimiter     Delimiter49	nth           []Range50	procFun       map[termType]func(bool, bool, []rune, []rune) (int, int)51}5253var (54	_patternCache map[string]*Pattern55	_splitRegex   *regexp.Regexp56	_cache        ChunkCache57)5859func init() {60	_splitRegex = regexp.MustCompile("\\s+")61	clearPatternCache()62	clearChunkCache()63}6465func clearPatternCache() {66	// We can uniquely identify the pattern for a given string since67	// search mode and caseMode do not change while the program is running68	_patternCache = make(map[string]*Pattern)69}7071func clearChunkCache() {72	_cache = NewChunkCache()73}7475// BuildPattern builds Pattern object from the given arguments76func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,77	nth []Range, delimiter Delimiter, runes []rune) *Pattern {7879	var asString string80	if extended {81		asString = strings.Trim(string(runes), " ")82	} else {83		asString = string(runes)84	}8586	cached, found := _patternCache[asString]87	if found {88		return cached89	}9091	caseSensitive, hasInvTerm := true, false92	terms := []term{}9394	if extended {95		terms = parseTerms(fuzzy, caseMode, asString)96		for _, term := range terms {97			if term.inv {98				hasInvTerm = true99			}100		}101	} else {102		lowerString := strings.ToLower(asString)103		caseSensitive = caseMode == CaseRespect ||104			caseMode == CaseSmart && lowerString != asString105		if !caseSensitive {106			asString = lowerString107		}108	}109110	ptr := &Pattern{111		fuzzy:         fuzzy,112		extended:      extended,113		caseSensitive: caseSensitive,114		forward:       forward,115		text:          []rune(asString),116		terms:         terms,117		hasInvTerm:    hasInvTerm,118		nth:           nth,119		delimiter:     delimiter,120		procFun:       make(map[termType]func(bool, bool, []rune, []rune) (int, int))}121122	ptr.procFun[termFuzzy] = algo.FuzzyMatch123	ptr.procFun[termEqual] = algo.EqualMatch124	ptr.procFun[termExact] = algo.ExactMatchNaive125	ptr.procFun[termPrefix] = algo.PrefixMatch126	ptr.procFun[termSuffix] = algo.SuffixMatch127128	_patternCache[asString] = ptr129	return ptr130}131132func parseTerms(fuzzy bool, caseMode Case, str string) []term {133	tokens := _splitRegex.Split(str, -1)134	terms := []term{}135	for _, token := range tokens {136		typ, inv, text := termFuzzy, false, token137		lowerText := strings.ToLower(text)138		caseSensitive := caseMode == CaseRespect ||139			caseMode == CaseSmart && text != lowerText140		if !caseSensitive {141			text = lowerText142		}143		origText := []rune(text)144		if !fuzzy {145			typ = termExact146		}147148		if strings.HasPrefix(text, "!") {149			inv = true150			text = text[1:]151		}152153		if strings.HasPrefix(text, "'") {154			// Flip exactness155			if fuzzy {156				typ = termExact157				text = text[1:]158			} else {159				typ = termFuzzy160				text = text[1:]161			}162		} else if strings.HasPrefix(text, "^") {163			if strings.HasSuffix(text, "$") {164				typ = termEqual165				text = text[1 : len(text)-1]166			} else {167				typ = termPrefix168				text = text[1:]169			}170		} else if strings.HasSuffix(text, "$") {171			typ = termSuffix172			text = text[:len(text)-1]173		}174175		if len(text) > 0 {176			terms = append(terms, term{177				typ:           typ,178				inv:           inv,179				text:          []rune(text),180				caseSensitive: caseSensitive,181				origText:      origText})182		}183	}184	return terms185}186187// IsEmpty returns true if the pattern is effectively empty188func (p *Pattern) IsEmpty() bool {189	if !p.extended {190		return len(p.text) == 0191	}192	return len(p.terms) == 0193}194195// AsString returns the search query in string type196func (p *Pattern) AsString() string {197	return string(p.text)198}199200// CacheKey is used to build string to be used as the key of result cache201func (p *Pattern) CacheKey() string {202	if !p.extended {203		return p.AsString()204	}205	cacheableTerms := []string{}206	for _, term := range p.terms {207		if term.inv {208			continue209		}210		cacheableTerms = append(cacheableTerms, string(term.origText))211	}212	return strings.Join(cacheableTerms, " ")213}214215// Match returns the list of matches Items in the given Chunk216func (p *Pattern) Match(chunk *Chunk) []*Item {217	space := chunk218219	// ChunkCache: Exact match220	cacheKey := p.CacheKey()221	if !p.hasInvTerm { // Because we're excluding Inv-term from cache key222		if cached, found := _cache.Find(chunk, cacheKey); found {223			return cached224		}225	}226227	// ChunkCache: Prefix/suffix match228Loop:229	for idx := 1; idx < len(cacheKey); idx++ {230		// [---------| ] | [ |---------]231		// [--------|  ] | [  |--------]232		// [-------|   ] | [   |-------]233		prefix := cacheKey[:len(cacheKey)-idx]234		suffix := cacheKey[idx:]235		for _, substr := range [2]*string{&prefix, &suffix} {236			if cached, found := _cache.Find(chunk, *substr); found {237				cachedChunk := Chunk(cached)238				space = &cachedChunk239				break Loop240			}241		}242	}243244	matches := p.matchChunk(space)245246	if !p.hasInvTerm {247		_cache.Add(chunk, cacheKey, matches)248	}249	return matches250}251252func (p *Pattern) matchChunk(chunk *Chunk) []*Item {253	matches := []*Item{}254	if !p.extended {255		for _, item := range *chunk {256			if sidx, eidx, tlen := p.basicMatch(item); sidx >= 0 {257				matches = append(matches,258					dupItem(item, []Offset{Offset{int32(sidx), int32(eidx), int32(tlen)}}))259			}260		}261	} else {262		for _, item := range *chunk {263			if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {264				matches = append(matches, dupItem(item, offsets))265			}266		}267	}268	return matches269}270271// MatchItem returns true if the Item is a match272func (p *Pattern) MatchItem(item *Item) bool {273	if !p.extended {274		sidx, _, _ := p.basicMatch(item)275		return sidx >= 0276	}277	offsets := p.extendedMatch(item)278	return len(offsets) == len(p.terms)279}280281func dupItem(item *Item, offsets []Offset) *Item {282	sort.Sort(ByOrder(offsets))283	return &Item{284		text:        item.text,285		origText:    item.origText,286		transformed: item.transformed,287		index:       item.index,288		offsets:     offsets,289		colors:      item.colors,290		rank:        Rank{0, 0, item.index}}291}292293func (p *Pattern) basicMatch(item *Item) (int, int, int) {294	input := p.prepareInput(item)295	if p.fuzzy {296		return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)297	}298	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)299}300301func (p *Pattern) extendedMatch(item *Item) []Offset {302	input := p.prepareInput(item)303	offsets := []Offset{}304	for _, term := range p.terms {305		pfun := p.procFun[term.typ]306		if sidx, eidx, tlen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text); sidx >= 0 {307			if term.inv {308				break309			}310			offsets = append(offsets, Offset{int32(sidx), int32(eidx), int32(tlen)})311		} else if term.inv {312			offsets = append(offsets, Offset{0, 0, 0})313		}314	}315	return offsets316}317318func (p *Pattern) prepareInput(item *Item) []Token {319	if item.transformed != nil {320		return item.transformed321	}322323	var ret []Token324	if len(p.nth) > 0 {325		tokens := Tokenize(item.text, p.delimiter)326		ret = Transform(tokens, p.nth)327	} else {328		ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: util.TrimLen(item.text)}}329	}330	item.transformed = ret331	return ret332}333334func (p *Pattern) iter(pfun func(bool, bool, []rune, []rune) (int, int),335	tokens []Token, caseSensitive bool, forward bool, pattern []rune) (int, int, int) {336	for _, part := range tokens {337		prefixLength := part.prefixLength338		if sidx, eidx := pfun(caseSensitive, forward, part.text, pattern); sidx >= 0 {339			return sidx + prefixLength, eidx + prefixLength, part.trimLength340		}341	}342	return -1, -1, -1 // math.MaxUint16343}