Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

460 lines · 11.6 KiB · Go

Last changed by

Allow suffix match on --nth with custom --delimiterJunegunn Choibefore adoption9abf2c8

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	revision      revision64	procFun       map[termType]algo.Algo65	cache         *ChunkCache66	denylist      map[int32]struct{}67}6869var _splitRegex *regexp.Regexp7071func init() {72	_splitRegex = regexp.MustCompile(" +")73}7475// BuildPattern builds Pattern object from the given arguments76func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,77	withPos bool, cacheable bool, nth []Range, delimiter Delimiter, revision revision, runes []rune, denylist map[int32]struct{}) *Pattern {7879	var asString string80	if extended {81		asString = strings.TrimLeft(string(runes), " ")82		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {83			asString = asString[:len(asString)-1]84		}85	} else {86		asString = string(runes)87	}8889	// We can uniquely identify the pattern for a given string since90	// search mode and caseMode do not change while the program is running91	cached, found := patternCache[asString]92	if found {93		return cached94	}9596	caseSensitive := true97	sortable := true98	termSets := []termSet{}99100	if extended {101		termSets = parseTerms(fuzzy, caseMode, normalize, asString)102		// We should not sort the result if there are only inverse search terms103		sortable = false104	Loop:105		for _, termSet := range termSets {106			for idx, term := range termSet {107				if !term.inv {108					sortable = true109				}110				// If the query contains inverse search terms or OR operators,111				// we cannot cache the search scope112				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {113					cacheable = false114					if sortable {115						// Can't break until we see at least one non-inverse term116						break Loop117					}118				}119			}120		}121	} else {122		lowerString := strings.ToLower(asString)123		normalize = normalize &&124			lowerString == string(algo.NormalizeRunes([]rune(lowerString)))125		caseSensitive = caseMode == CaseRespect ||126			caseMode == CaseSmart && lowerString != asString127		if !caseSensitive {128			asString = lowerString129		}130	}131132	ptr := &Pattern{133		fuzzy:         fuzzy,134		fuzzyAlgo:     fuzzyAlgo,135		extended:      extended,136		caseSensitive: caseSensitive,137		normalize:     normalize,138		forward:       forward,139		withPos:       withPos,140		text:          []rune(asString),141		termSets:      termSets,142		sortable:      sortable,143		cacheable:     cacheable,144		nth:           nth,145		revision:      revision,146		delimiter:     delimiter,147		cache:         cache,148		denylist:      denylist,149		procFun:       make(map[termType]algo.Algo)}150151	ptr.cacheKey = ptr.buildCacheKey()152	ptr.procFun[termFuzzy] = fuzzyAlgo153	ptr.procFun[termEqual] = algo.EqualMatch154	ptr.procFun[termExact] = algo.ExactMatchNaive155	ptr.procFun[termExactBoundary] = algo.ExactMatchBoundary156	ptr.procFun[termPrefix] = algo.PrefixMatch157	ptr.procFun[termSuffix] = algo.SuffixMatch158159	patternCache[asString] = ptr160	return ptr161}162163func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {164	str = strings.ReplaceAll(str, "\\ ", "\t")165	tokens := _splitRegex.Split(str, -1)166	sets := []termSet{}167	set := termSet{}168	switchSet := false169	afterBar := false170	for _, token := range tokens {171		typ, inv, text := termFuzzy, false, strings.ReplaceAll(token, "\t", " ")172		lowerText := strings.ToLower(text)173		caseSensitive := caseMode == CaseRespect ||174			caseMode == CaseSmart && text != lowerText175		normalizeTerm := normalize &&176			lowerText == string(algo.NormalizeRunes([]rune(lowerText)))177		if !caseSensitive {178			text = lowerText179		}180		if !fuzzy {181			typ = termExact182		}183184		if len(set) > 0 && !afterBar && text == "|" {185			switchSet = false186			afterBar = true187			continue188		}189		afterBar = false190191		if strings.HasPrefix(text, "!") {192			inv = true193			typ = termExact194			text = text[1:]195		}196197		if text != "$" && strings.HasSuffix(text, "$") {198			typ = termSuffix199			text = text[:len(text)-1]200		}201202		if len(text) > 2 && strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") {203			typ = termExactBoundary204			text = text[1 : len(text)-1]205		} else if strings.HasPrefix(text, "'") {206			// Flip exactness207			if fuzzy && !inv {208				typ = termExact209			} else {210				typ = termFuzzy211			}212			text = text[1:]213		} else if strings.HasPrefix(text, "^") {214			if typ == termSuffix {215				typ = termEqual216			} else {217				typ = termPrefix218			}219			text = text[1:]220		}221222		if len(text) > 0 {223			if switchSet {224				sets = append(sets, set)225				set = termSet{}226			}227			textRunes := []rune(text)228			if normalizeTerm {229				textRunes = algo.NormalizeRunes(textRunes)230			}231			set = append(set, term{232				typ:           typ,233				inv:           inv,234				text:          textRunes,235				caseSensitive: caseSensitive,236				normalize:     normalizeTerm})237			switchSet = true238		}239	}240	if len(set) > 0 {241		sets = append(sets, set)242	}243	return sets244}245246// IsEmpty returns true if the pattern is effectively empty247func (p *Pattern) IsEmpty() bool {248	if len(p.denylist) > 0 {249		return false250	}251	if !p.extended {252		return len(p.text) == 0253	}254	return len(p.termSets) == 0255}256257// AsString returns the search query in string type258func (p *Pattern) AsString() string {259	return string(p.text)260}261262func (p *Pattern) buildCacheKey() string {263	if !p.extended {264		return p.AsString()265	}266	cacheableTerms := []string{}267	for _, termSet := range p.termSets {268		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {269			cacheableTerms = append(cacheableTerms, string(termSet[0].text))270		}271	}272	return strings.Join(cacheableTerms, "\t")273}274275// CacheKey is used to build string to be used as the key of result cache276func (p *Pattern) CacheKey() string {277	return p.cacheKey278}279280// Match returns the list of matches Items in the given Chunk281func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {282	// ChunkCache: Exact match283	cacheKey := p.CacheKey()284	if p.cacheable {285		if cached := p.cache.Lookup(chunk, cacheKey); cached != nil {286			return cached287		}288	}289290	// Prefix/suffix cache291	space := p.cache.Search(chunk, cacheKey)292293	matches := p.matchChunk(chunk, space, slab)294295	if p.cacheable {296		p.cache.Add(chunk, cacheKey, matches)297	}298	return matches299}300301func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {302	matches := []Result{}303304	if len(p.denylist) == 0 {305		// Huge code duplication for minimizing unnecessary map lookups306		if space == nil {307			for idx := 0; idx < chunk.count; idx++ {308				if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match != nil {309					matches = append(matches, *match)310				}311			}312		} else {313			for _, result := range space {314				if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match != nil {315					matches = append(matches, *match)316				}317			}318		}319		return matches320	}321322	if space == nil {323		for idx := 0; idx < chunk.count; idx++ {324			if _, prs := p.denylist[chunk.items[idx].Index()]; prs {325				continue326			}327			if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match != nil {328				matches = append(matches, *match)329			}330		}331	} else {332		for _, result := range space {333			if _, prs := p.denylist[result.item.Index()]; prs {334				continue335			}336			if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match != nil {337				matches = append(matches, *match)338			}339		}340	}341	return matches342}343344// MatchItem returns true if the Item is a match345func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {346	if p.extended {347		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {348			result := buildResult(item, offsets, bonus)349			return &result, offsets, pos350		}351		return nil, nil, nil352	}353	offset, bonus, pos := p.basicMatch(item, withPos, slab)354	if sidx := offset[0]; sidx >= 0 {355		offsets := []Offset{offset}356		result := buildResult(item, offsets, bonus)357		return &result, offsets, pos358	}359	return nil, nil, nil360}361362func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {363	var input []Token364	if len(p.nth) == 0 {365		input = []Token{{text: &item.text, prefixLength: 0}}366	} else {367		input = p.transformInput(item)368	}369	if p.fuzzy {370		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)371	}372	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)373}374375func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {376	var input []Token377	if len(p.nth) == 0 {378		input = []Token{{text: &item.text, prefixLength: 0}}379	} else {380		input = p.transformInput(item)381	}382	offsets := []Offset{}383	var totalScore int384	var allPos *[]int385	if withPos {386		allPos = &[]int{}387	}388	for _, termSet := range p.termSets {389		var offset Offset390		var currentScore int391		matched := false392		for _, term := range termSet {393			pfun := p.procFun[term.typ]394			off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)395			if sidx := off[0]; sidx >= 0 {396				if term.inv {397					continue398				}399				offset, currentScore = off, score400				matched = true401				if withPos {402					if pos != nil {403						*allPos = append(*allPos, *pos...)404					} else {405						for idx := off[0]; idx < off[1]; idx++ {406							*allPos = append(*allPos, int(idx))407						}408					}409				}410				break411			} else if term.inv {412				offset, currentScore = Offset{0, 0}, 0413				matched = true414				continue415			}416		}417		if matched {418			offsets = append(offsets, offset)419			totalScore += currentScore420		}421	}422	return offsets, totalScore, allPos423}424425func (p *Pattern) transformInput(item *Item) []Token {426	if item.transformed != nil {427		transformed := *item.transformed428		if transformed.revision == p.revision {429			return transformed.tokens430		}431	}432433	tokens := Tokenize(item.text.ToString(), p.delimiter)434	ret := Transform(tokens, p.nth)435	// Strip the last delimiter to allow suffix match436	if len(ret) > 0 && !p.delimiter.IsAwk() {437		chars := ret[len(ret)-1].text438		stripped := StripLastDelimiter(chars.ToString(), p.delimiter)439		newChars := util.ToChars(stringBytes(stripped))440		ret[len(ret)-1].text = &newChars441	}442	item.transformed = &transformed{p.revision, ret}443	return ret444}445446func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {447	for _, part := range tokens {448		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {449			sidx := int32(res.Start) + part.prefixLength450			eidx := int32(res.End) + part.prefixLength451			if pos != nil {452				for idx := range *pos {453					(*pos)[idx] += int(part.prefixLength)454				}455			}456			return Offset{sidx, eidx}, res.Score, pos457		}458	}459	return Offset{-1, -1}, 0, nil460}