Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

419 lines · 10.0 KiB · Go

Last changed by

Inverse-only matches should not reorder the remaining resultsJunegunn Choibefore adoption5624a89

History of this file

Take it

1package fzf23import (4	"fmt"5	"regexp"6	"strings"78	"github.com/junegunn/fzf/src/algo"9	"github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact14// ^prefix-exact15// suffix-exact$16// !inverse-exact17// !'inverse-fuzzy18// !^inverse-prefix-exact19// !inverse-suffix-exact$2021type termType int2223const (24	termFuzzy termType = iota25	termExact26	termPrefix27	termSuffix28	termEqual29)3031type term struct {32	typ           termType33	inv           bool34	text          []rune35	caseSensitive bool36}3738// String returns the string representation of a term.39func (t term) String() string {40	return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)41}4243type termSet []term4445// Pattern represents search pattern46type Pattern struct {47	fuzzy         bool48	fuzzyAlgo     algo.Algo49	extended      bool50	caseSensitive bool51	normalize     bool52	forward       bool53	text          []rune54	termSets      []termSet55	sortable      bool56	cacheable     bool57	cacheKey      string58	delimiter     Delimiter59	nth           []Range60	procFun       map[termType]algo.Algo61}6263var (64	_patternCache map[string]*Pattern65	_splitRegex   *regexp.Regexp66	_cache        ChunkCache67)6869func init() {70	_splitRegex = regexp.MustCompile(" +")71	clearPatternCache()72	clearChunkCache()73}7475func clearPatternCache() {76	// We can uniquely identify the pattern for a given string since77	// search mode and caseMode do not change while the program is running78	_patternCache = make(map[string]*Pattern)79}8081func clearChunkCache() {82	_cache = NewChunkCache()83}8485// BuildPattern builds Pattern object from the given arguments86func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,87	cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8889	var asString string90	if extended {91		asString = strings.TrimLeft(string(runes), " ")92		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {93			asString = asString[:len(asString)-1]94		}95	} else {96		asString = string(runes)97	}9899	cached, found := _patternCache[asString]100	if found {101		return cached102	}103104	caseSensitive := true105	sortable := true106	termSets := []termSet{}107108	if extended {109		termSets = parseTerms(fuzzy, caseMode, normalize, asString)110		// We should not sort the result if there are only inverse search terms111		sortable = false112	Loop:113		for _, termSet := range termSets {114			for idx, term := range termSet {115				if !term.inv {116					sortable = true117				}118				// If the query contains inverse search terms or OR operators,119				// we cannot cache the search scope120				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {121					cacheable = false122					if sortable {123						// Can't break until we see at least one non-inverse term124						break Loop125					}126				}127			}128		}129	} else {130		lowerString := strings.ToLower(asString)131		caseSensitive = caseMode == CaseRespect ||132			caseMode == CaseSmart && lowerString != asString133		if !caseSensitive {134			asString = lowerString135		}136	}137138	ptr := &Pattern{139		fuzzy:         fuzzy,140		fuzzyAlgo:     fuzzyAlgo,141		extended:      extended,142		caseSensitive: caseSensitive,143		normalize:     normalize,144		forward:       forward,145		text:          []rune(asString),146		termSets:      termSets,147		sortable:      sortable,148		cacheable:     cacheable,149		nth:           nth,150		delimiter:     delimiter,151		procFun:       make(map[termType]algo.Algo)}152153	ptr.cacheKey = ptr.buildCacheKey()154	ptr.procFun[termFuzzy] = fuzzyAlgo155	ptr.procFun[termEqual] = algo.EqualMatch156	ptr.procFun[termExact] = algo.ExactMatchNaive157	ptr.procFun[termPrefix] = algo.PrefixMatch158	ptr.procFun[termSuffix] = algo.SuffixMatch159160	_patternCache[asString] = ptr161	return ptr162}163164func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {165	str = strings.Replace(str, "\\ ", "\t", -1)166	tokens := _splitRegex.Split(str, -1)167	sets := []termSet{}168	set := termSet{}169	switchSet := false170	afterBar := false171	for _, token := range tokens {172		typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)173		lowerText := strings.ToLower(text)174		caseSensitive := caseMode == CaseRespect ||175			caseMode == CaseSmart && text != lowerText176		if !caseSensitive {177			text = lowerText178		}179		if !fuzzy {180			typ = termExact181		}182183		if len(set) > 0 && !afterBar && text == "|" {184			switchSet = false185			afterBar = true186			continue187		}188		afterBar = false189190		if strings.HasPrefix(text, "!") {191			inv = true192			typ = termExact193			text = text[1:]194		}195196		if text != "$" && strings.HasSuffix(text, "$") {197			typ = termSuffix198			text = text[:len(text)-1]199		}200201		if strings.HasPrefix(text, "'") {202			// Flip exactness203			if fuzzy && !inv {204				typ = termExact205				text = text[1:]206			} else {207				typ = termFuzzy208				text = text[1:]209			}210		} else if strings.HasPrefix(text, "^") {211			if typ == termSuffix {212				typ = termEqual213			} else {214				typ = termPrefix215			}216			text = text[1:]217		}218219		if len(text) > 0 {220			if switchSet {221				sets = append(sets, set)222				set = termSet{}223			}224			textRunes := []rune(text)225			if normalize {226				textRunes = algo.NormalizeRunes(textRunes)227			}228			set = append(set, term{229				typ:           typ,230				inv:           inv,231				text:          textRunes,232				caseSensitive: caseSensitive})233			switchSet = true234		}235	}236	if len(set) > 0 {237		sets = append(sets, set)238	}239	return sets240}241242// IsEmpty returns true if the pattern is effectively empty243func (p *Pattern) IsEmpty() bool {244	if !p.extended {245		return len(p.text) == 0246	}247	return len(p.termSets) == 0248}249250// AsString returns the search query in string type251func (p *Pattern) AsString() string {252	return string(p.text)253}254255func (p *Pattern) buildCacheKey() string {256	if !p.extended {257		return p.AsString()258	}259	cacheableTerms := []string{}260	for _, termSet := range p.termSets {261		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {262			cacheableTerms = append(cacheableTerms, string(termSet[0].text))263		}264	}265	return strings.Join(cacheableTerms, "\t")266}267268// CacheKey is used to build string to be used as the key of result cache269func (p *Pattern) CacheKey() string {270	return p.cacheKey271}272273// Match returns the list of matches Items in the given Chunk274func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {275	// ChunkCache: Exact match276	cacheKey := p.CacheKey()277	if p.cacheable {278		if cached := _cache.Lookup(chunk, cacheKey); cached != nil {279			return cached280		}281	}282283	// Prefix/suffix cache284	space := _cache.Search(chunk, cacheKey)285286	matches := p.matchChunk(chunk, space, slab)287288	if p.cacheable {289		_cache.Add(chunk, cacheKey, matches)290	}291	return matches292}293294func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {295	matches := []Result{}296297	if space == nil {298		for idx := 0; idx < chunk.count; idx++ {299			if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {300				matches = append(matches, *match)301			}302		}303	} else {304		for _, result := range space {305			if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {306				matches = append(matches, *match)307			}308		}309	}310	return matches311}312313// MatchItem returns true if the Item is a match314func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {315	if p.extended {316		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {317			result := buildResult(item, offsets, bonus)318			return &result, offsets, pos319		}320		return nil, nil, nil321	}322	offset, bonus, pos := p.basicMatch(item, withPos, slab)323	if sidx := offset[0]; sidx >= 0 {324		offsets := []Offset{offset}325		result := buildResult(item, offsets, bonus)326		return &result, offsets, pos327	}328	return nil, nil, nil329}330331func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {332	var input []Token333	if len(p.nth) == 0 {334		input = []Token{Token{text: &item.text, prefixLength: 0}}335	} else {336		input = p.transformInput(item)337	}338	if p.fuzzy {339		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)340	}341	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)342}343344func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {345	var input []Token346	if len(p.nth) == 0 {347		input = []Token{Token{text: &item.text, prefixLength: 0}}348	} else {349		input = p.transformInput(item)350	}351	offsets := []Offset{}352	var totalScore int353	var allPos *[]int354	if withPos {355		allPos = &[]int{}356	}357	for _, termSet := range p.termSets {358		var offset Offset359		var currentScore int360		matched := false361		for _, term := range termSet {362			pfun := p.procFun[term.typ]363			off, score, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)364			if sidx := off[0]; sidx >= 0 {365				if term.inv {366					continue367				}368				offset, currentScore = off, score369				matched = true370				if withPos {371					if pos != nil {372						*allPos = append(*allPos, *pos...)373					} else {374						for idx := off[0]; idx < off[1]; idx++ {375							*allPos = append(*allPos, int(idx))376						}377					}378				}379				break380			} else if term.inv {381				offset, currentScore = Offset{0, 0}, 0382				matched = true383				continue384			}385		}386		if matched {387			offsets = append(offsets, offset)388			totalScore += currentScore389		}390	}391	return offsets, totalScore, allPos392}393394func (p *Pattern) transformInput(item *Item) []Token {395	if item.transformed != nil {396		return *item.transformed397	}398399	tokens := Tokenize(item.text.ToString(), p.delimiter)400	ret := Transform(tokens, p.nth)401	item.transformed = &ret402	return ret403}404405func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {406	for _, part := range tokens {407		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {408			sidx := int32(res.Start) + part.prefixLength409			eidx := int32(res.End) + part.prefixLength410			if pos != nil {411				for idx := range *pos {412					(*pos)[idx] += int(part.prefixLength)413				}414			}415			return Offset{sidx, eidx}, res.Score, pos416		}417	}418	return Offset{-1, -1}, 0, nil419}