Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

419 lines · 10.4 KiB · Go

Last changed by

Require quotes on both sides for boundary matching even in --exact modeJunegunn Choibefore adoptionefbcd5a

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	termExactBoundary27	termPrefix28	termSuffix29	termEqual30)3132type term struct {33	typ           termType34	inv           bool35	text          []rune36	caseSensitive bool37	normalize     bool38}3940// String returns the string representation of a term.41func (t term) String() string {42	return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)43}4445type termSet []term4647// Pattern represents search pattern48type Pattern struct {49	fuzzy         bool50	fuzzyAlgo     algo.Algo51	extended      bool52	caseSensitive bool53	normalize     bool54	forward       bool55	withPos       bool56	text          []rune57	termSets      []termSet58	sortable      bool59	cacheable     bool60	cacheKey      string61	delimiter     Delimiter62	nth           []Range63	procFun       map[termType]algo.Algo64	cache         *ChunkCache65}6667var _splitRegex *regexp.Regexp6869func init() {70	_splitRegex = regexp.MustCompile(" +")71}7273// BuildPattern builds Pattern object from the given arguments74func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,75	withPos bool, cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {7677	var asString string78	if extended {79		asString = strings.TrimLeft(string(runes), " ")80		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {81			asString = asString[:len(asString)-1]82		}83	} else {84		asString = string(runes)85	}8687	// We can uniquely identify the pattern for a given string since88	// search mode and caseMode do not change while the program is running89	cached, found := patternCache[asString]90	if found {91		return cached92	}9394	caseSensitive := true95	sortable := true96	termSets := []termSet{}9798	if extended {99		termSets = parseTerms(fuzzy, caseMode, normalize, asString)100		// We should not sort the result if there are only inverse search terms101		sortable = false102	Loop:103		for _, termSet := range termSets {104			for idx, term := range termSet {105				if !term.inv {106					sortable = true107				}108				// If the query contains inverse search terms or OR operators,109				// we cannot cache the search scope110				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {111					cacheable = false112					if sortable {113						// Can't break until we see at least one non-inverse term114						break Loop115					}116				}117			}118		}119	} else {120		lowerString := strings.ToLower(asString)121		normalize = normalize &&122			lowerString == string(algo.NormalizeRunes([]rune(lowerString)))123		caseSensitive = caseMode == CaseRespect ||124			caseMode == CaseSmart && lowerString != asString125		if !caseSensitive {126			asString = lowerString127		}128	}129130	ptr := &Pattern{131		fuzzy:         fuzzy,132		fuzzyAlgo:     fuzzyAlgo,133		extended:      extended,134		caseSensitive: caseSensitive,135		normalize:     normalize,136		forward:       forward,137		withPos:       withPos,138		text:          []rune(asString),139		termSets:      termSets,140		sortable:      sortable,141		cacheable:     cacheable,142		nth:           nth,143		delimiter:     delimiter,144		cache:         cache,145		procFun:       make(map[termType]algo.Algo)}146147	ptr.cacheKey = ptr.buildCacheKey()148	ptr.procFun[termFuzzy] = fuzzyAlgo149	ptr.procFun[termEqual] = algo.EqualMatch150	ptr.procFun[termExact] = algo.ExactMatchNaive151	ptr.procFun[termExactBoundary] = algo.ExactMatchBoundary152	ptr.procFun[termPrefix] = algo.PrefixMatch153	ptr.procFun[termSuffix] = algo.SuffixMatch154155	patternCache[asString] = ptr156	return ptr157}158159func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {160	str = strings.ReplaceAll(str, "\\ ", "\t")161	tokens := _splitRegex.Split(str, -1)162	sets := []termSet{}163	set := termSet{}164	switchSet := false165	afterBar := false166	for _, token := range tokens {167		typ, inv, text := termFuzzy, false, strings.ReplaceAll(token, "\t", " ")168		lowerText := strings.ToLower(text)169		caseSensitive := caseMode == CaseRespect ||170			caseMode == CaseSmart && text != lowerText171		normalizeTerm := normalize &&172			lowerText == string(algo.NormalizeRunes([]rune(lowerText)))173		if !caseSensitive {174			text = lowerText175		}176		if !fuzzy {177			typ = termExact178		}179180		if len(set) > 0 && !afterBar && text == "|" {181			switchSet = false182			afterBar = true183			continue184		}185		afterBar = false186187		if strings.HasPrefix(text, "!") {188			inv = true189			typ = termExact190			text = text[1:]191		}192193		if text != "$" && strings.HasSuffix(text, "$") {194			typ = termSuffix195			text = text[:len(text)-1]196		}197198		if len(text) > 2 && strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") {199			typ = termExactBoundary200			text = text[1 : len(text)-1]201		} else if strings.HasPrefix(text, "'") {202			// Flip exactness203			if fuzzy && !inv {204				typ = termExact205			} else {206				typ = termFuzzy207			}208			text = text[1:]209		} else if strings.HasPrefix(text, "^") {210			if typ == termSuffix {211				typ = termEqual212			} else {213				typ = termPrefix214			}215			text = text[1:]216		}217218		if len(text) > 0 {219			if switchSet {220				sets = append(sets, set)221				set = termSet{}222			}223			textRunes := []rune(text)224			if normalizeTerm {225				textRunes = algo.NormalizeRunes(textRunes)226			}227			set = append(set, term{228				typ:           typ,229				inv:           inv,230				text:          textRunes,231				caseSensitive: caseSensitive,232				normalize:     normalizeTerm})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 := p.cache.Lookup(chunk, cacheKey); cached != nil {279			return cached280		}281	}282283	// Prefix/suffix cache284	space := p.cache.Search(chunk, cacheKey)285286	matches := p.matchChunk(chunk, space, slab)287288	if p.cacheable {289		p.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], p.withPos, slab); match != nil {300				matches = append(matches, *match)301			}302		}303	} else {304		for _, result := range space {305			if match, _, _ := p.MatchItem(result.item, p.withPos, 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{{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{{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, term.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}