Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

335 lines · 7.5 KiB · Go

Last changed by

Allow ^EqualMatch$Junegunn Choibefore adoption0be4cea

History of this file

Take it

1package fzf23import (4	"regexp"5	"sort"6	"strings"78	"github.com/junegunn/fzf/src/algo"9)1011// fuzzy12// 'exact13// ^exact-prefix14// exact-suffix$15// !not-fuzzy16// !'not-exact17// !^not-exact-prefix18// !not-exact-suffix$1920type termType int2122const (23	termFuzzy termType = iota24	termExact25	termPrefix26	termSuffix27	termEqual28)2930type term struct {31	typ           termType32	inv           bool33	text          []rune34	caseSensitive bool35	origText      []rune36}3738// Pattern represents search pattern39type Pattern struct {40	mode          Mode41	caseSensitive bool42	text          []rune43	terms         []term44	hasInvTerm    bool45	delimiter     *regexp.Regexp46	nth           []Range47	procFun       map[termType]func(bool, *[]rune, []rune) (int, int)48}4950var (51	_patternCache map[string]*Pattern52	_splitRegex   *regexp.Regexp53	_cache        ChunkCache54)5556func init() {57	_splitRegex = regexp.MustCompile("\\s+")58	clearPatternCache()59	clearChunkCache()60}6162func clearPatternCache() {63	// We can uniquely identify the pattern for a given string since64	// mode and caseMode do not change while the program is running65	_patternCache = make(map[string]*Pattern)66}6768func clearChunkCache() {69	_cache = NewChunkCache()70}7172// BuildPattern builds Pattern object from the given arguments73func BuildPattern(mode Mode, caseMode Case,74	nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {7576	var asString string77	switch mode {78	case ModeExtended, ModeExtendedExact:79		asString = strings.Trim(string(runes), " ")80	default:81		asString = string(runes)82	}8384	cached, found := _patternCache[asString]85	if found {86		return cached87	}8889	caseSensitive, hasInvTerm := true, false90	terms := []term{}9192	switch mode {93	case ModeExtended, ModeExtendedExact:94		terms = parseTerms(mode, caseMode, asString)95		for _, term := range terms {96			if term.inv {97				hasInvTerm = true98			}99		}100	default:101		lowerString := strings.ToLower(asString)102		caseSensitive = caseMode == CaseRespect ||103			caseMode == CaseSmart && lowerString != asString104		if !caseSensitive {105			asString = lowerString106		}107	}108109	ptr := &Pattern{110		mode:          mode,111		caseSensitive: caseSensitive,112		text:          []rune(asString),113		terms:         terms,114		hasInvTerm:    hasInvTerm,115		nth:           nth,116		delimiter:     delimiter,117		procFun:       make(map[termType]func(bool, *[]rune, []rune) (int, int))}118119	ptr.procFun[termFuzzy] = algo.FuzzyMatch120	ptr.procFun[termEqual] = algo.EqualMatch121	ptr.procFun[termExact] = algo.ExactMatchNaive122	ptr.procFun[termPrefix] = algo.PrefixMatch123	ptr.procFun[termSuffix] = algo.SuffixMatch124125	_patternCache[asString] = ptr126	return ptr127}128129func parseTerms(mode Mode, caseMode Case, str string) []term {130	tokens := _splitRegex.Split(str, -1)131	terms := []term{}132	for _, token := range tokens {133		typ, inv, text := termFuzzy, false, token134		lowerText := strings.ToLower(text)135		caseSensitive := caseMode == CaseRespect ||136			caseMode == CaseSmart && text != lowerText137		if !caseSensitive {138			text = lowerText139		}140		origText := []rune(text)141		if mode == ModeExtendedExact {142			typ = termExact143		}144145		if strings.HasPrefix(text, "!") {146			inv = true147			text = text[1:]148		}149150		if strings.HasPrefix(text, "'") {151			if mode == ModeExtended {152				typ = termExact153				text = text[1:]154			}155		} else if strings.HasPrefix(text, "^") {156			if strings.HasSuffix(text, "$") {157				typ = termEqual158				text = text[1 : len(text)-1]159			} else {160				typ = termPrefix161				text = text[1:]162			}163		} else if strings.HasSuffix(text, "$") {164			typ = termSuffix165			text = text[:len(text)-1]166		}167168		if len(text) > 0 {169			terms = append(terms, term{170				typ:           typ,171				inv:           inv,172				text:          []rune(text),173				caseSensitive: caseSensitive,174				origText:      origText})175		}176	}177	return terms178}179180// IsEmpty returns true if the pattern is effectively empty181func (p *Pattern) IsEmpty() bool {182	if p.mode == ModeFuzzy {183		return len(p.text) == 0184	}185	return len(p.terms) == 0186}187188// AsString returns the search query in string type189func (p *Pattern) AsString() string {190	return string(p.text)191}192193// CacheKey is used to build string to be used as the key of result cache194func (p *Pattern) CacheKey() string {195	if p.mode == ModeFuzzy {196		return p.AsString()197	}198	cacheableTerms := []string{}199	for _, term := range p.terms {200		if term.inv {201			continue202		}203		cacheableTerms = append(cacheableTerms, string(term.origText))204	}205	return strings.Join(cacheableTerms, " ")206}207208// Match returns the list of matches Items in the given Chunk209func (p *Pattern) Match(chunk *Chunk) []*Item {210	space := chunk211212	// ChunkCache: Exact match213	cacheKey := p.CacheKey()214	if !p.hasInvTerm { // Because we're excluding Inv-term from cache key215		if cached, found := _cache.Find(chunk, cacheKey); found {216			return cached217		}218	}219220	// ChunkCache: Prefix/suffix match221Loop:222	for idx := 1; idx < len(cacheKey); idx++ {223		// [---------| ] | [ |---------]224		// [--------|  ] | [  |--------]225		// [-------|   ] | [   |-------]226		prefix := cacheKey[:len(cacheKey)-idx]227		suffix := cacheKey[idx:]228		for _, substr := range [2]*string{&prefix, &suffix} {229			if cached, found := _cache.Find(chunk, *substr); found {230				cachedChunk := Chunk(cached)231				space = &cachedChunk232				break Loop233			}234		}235	}236237	matches := p.matchChunk(space)238239	if !p.hasInvTerm {240		_cache.Add(chunk, cacheKey, matches)241	}242	return matches243}244245func (p *Pattern) matchChunk(chunk *Chunk) []*Item {246	matches := []*Item{}247	if p.mode == ModeFuzzy {248		for _, item := range *chunk {249			if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {250				matches = append(matches,251					dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))252			}253		}254	} else {255		for _, item := range *chunk {256			if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {257				matches = append(matches, dupItem(item, offsets))258			}259		}260	}261	return matches262}263264// MatchItem returns true if the Item is a match265func (p *Pattern) MatchItem(item *Item) bool {266	if p.mode == ModeFuzzy {267		sidx, _ := p.fuzzyMatch(item)268		return sidx >= 0269	}270	offsets := p.extendedMatch(item)271	return len(offsets) == len(p.terms)272}273274func dupItem(item *Item, offsets []Offset) *Item {275	sort.Sort(ByOrder(offsets))276	return &Item{277		text:        item.text,278		origText:    item.origText,279		transformed: item.transformed,280		index:       item.index,281		offsets:     offsets,282		colors:      item.colors,283		rank:        Rank{0, 0, item.index}}284}285286func (p *Pattern) fuzzyMatch(item *Item) (int, int) {287	input := p.prepareInput(item)288	return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)289}290291func (p *Pattern) extendedMatch(item *Item) []Offset {292	input := p.prepareInput(item)293	offsets := []Offset{}294	for _, term := range p.terms {295		pfun := p.procFun[term.typ]296		if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {297			if term.inv {298				break299			}300			offsets = append(offsets, Offset{int32(sidx), int32(eidx)})301		} else if term.inv {302			offsets = append(offsets, Offset{0, 0})303		}304	}305	return offsets306}307308func (p *Pattern) prepareInput(item *Item) *[]Token {309	if item.transformed != nil {310		return item.transformed311	}312313	var ret *[]Token314	if len(p.nth) > 0 {315		tokens := Tokenize(item.text, p.delimiter)316		ret = Transform(tokens, p.nth)317	} else {318		runes := []rune(*item.text)319		trans := []Token{Token{text: &runes, prefixLength: 0}}320		ret = &trans321	}322	item.transformed = ret323	return ret324}325326func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),327	tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {328	for _, part := range *tokens {329		prefixLength := part.prefixLength330		if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {331			return sidx + prefixLength, eidx + prefixLength332		}333	}334	return -1, -1335}