Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

426 lines 路 10.3 KiB 路 Go

Last changed by

Remove duplicate codeonee-onlybefore adoption8061a2f

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	normalize     bool37}3839// String returns the string representation of a term.40func (t term) String() string {41	return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)42}4344type termSet []term4546// Pattern represents search pattern47type Pattern struct {48	fuzzy         bool49	fuzzyAlgo     algo.Algo50	extended      bool51	caseSensitive bool52	normalize     bool53	forward       bool54	withPos       bool55	text          []rune56	termSets      []termSet57	sortable      bool58	cacheable     bool59	cacheKey      string60	delimiter     Delimiter61	nth           []Range62	procFun       map[termType]algo.Algo63}6465var (66	_patternCache map[string]*Pattern67	_splitRegex   *regexp.Regexp68	_cache        ChunkCache69)7071func init() {72	_splitRegex = regexp.MustCompile(" +")73	clearPatternCache()74	clearChunkCache()75}7677func clearPatternCache() {78	// We can uniquely identify the pattern for a given string since79	// search mode and caseMode do not change while the program is running80	_patternCache = make(map[string]*Pattern)81}8283func clearChunkCache() {84	_cache = NewChunkCache()85}8687// BuildPattern builds Pattern object from the given arguments88func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,89	withPos bool, cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {9091	var asString string92	if extended {93		asString = strings.TrimLeft(string(runes), " ")94		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {95			asString = asString[:len(asString)-1]96		}97	} else {98		asString = string(runes)99	}100101	cached, found := _patternCache[asString]102	if found {103		return cached104	}105106	caseSensitive := true107	sortable := true108	termSets := []termSet{}109110	if extended {111		termSets = parseTerms(fuzzy, caseMode, normalize, asString)112		// We should not sort the result if there are only inverse search terms113		sortable = false114	Loop:115		for _, termSet := range termSets {116			for idx, term := range termSet {117				if !term.inv {118					sortable = true119				}120				// If the query contains inverse search terms or OR operators,121				// we cannot cache the search scope122				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {123					cacheable = false124					if sortable {125						// Can't break until we see at least one non-inverse term126						break Loop127					}128				}129			}130		}131	} else {132		lowerString := strings.ToLower(asString)133		normalize = normalize &&134			lowerString == string(algo.NormalizeRunes([]rune(lowerString)))135		caseSensitive = caseMode == CaseRespect ||136			caseMode == CaseSmart && lowerString != asString137		if !caseSensitive {138			asString = lowerString139		}140	}141142	ptr := &Pattern{143		fuzzy:         fuzzy,144		fuzzyAlgo:     fuzzyAlgo,145		extended:      extended,146		caseSensitive: caseSensitive,147		normalize:     normalize,148		forward:       forward,149		withPos:       withPos,150		text:          []rune(asString),151		termSets:      termSets,152		sortable:      sortable,153		cacheable:     cacheable,154		nth:           nth,155		delimiter:     delimiter,156		procFun:       make(map[termType]algo.Algo)}157158	ptr.cacheKey = ptr.buildCacheKey()159	ptr.procFun[termFuzzy] = fuzzyAlgo160	ptr.procFun[termEqual] = algo.EqualMatch161	ptr.procFun[termExact] = algo.ExactMatchNaive162	ptr.procFun[termPrefix] = algo.PrefixMatch163	ptr.procFun[termSuffix] = algo.SuffixMatch164165	_patternCache[asString] = ptr166	return ptr167}168169func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {170	str = strings.Replace(str, "\\ ", "\t", -1)171	tokens := _splitRegex.Split(str, -1)172	sets := []termSet{}173	set := termSet{}174	switchSet := false175	afterBar := false176	for _, token := range tokens {177		typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)178		lowerText := strings.ToLower(text)179		caseSensitive := caseMode == CaseRespect ||180			caseMode == CaseSmart && text != lowerText181		normalizeTerm := normalize &&182			lowerText == string(algo.NormalizeRunes([]rune(lowerText)))183		if !caseSensitive {184			text = lowerText185		}186		if !fuzzy {187			typ = termExact188		}189190		if len(set) > 0 && !afterBar && text == "|" {191			switchSet = false192			afterBar = true193			continue194		}195		afterBar = false196197		if strings.HasPrefix(text, "!") {198			inv = true199			typ = termExact200			text = text[1:]201		}202203		if text != "$" && strings.HasSuffix(text, "$") {204			typ = termSuffix205			text = text[:len(text)-1]206		}207208		if strings.HasPrefix(text, "'") {209			// Flip exactness210			if fuzzy && !inv {211				typ = termExact212			} else {213				typ = termFuzzy214			}215			text = text[1:]216		} else if strings.HasPrefix(text, "^") {217			if typ == termSuffix {218				typ = termEqual219			} else {220				typ = termPrefix221			}222			text = text[1:]223		}224225		if len(text) > 0 {226			if switchSet {227				sets = append(sets, set)228				set = termSet{}229			}230			textRunes := []rune(text)231			if normalizeTerm {232				textRunes = algo.NormalizeRunes(textRunes)233			}234			set = append(set, term{235				typ:           typ,236				inv:           inv,237				text:          textRunes,238				caseSensitive: caseSensitive,239				normalize:     normalizeTerm})240			switchSet = true241		}242	}243	if len(set) > 0 {244		sets = append(sets, set)245	}246	return sets247}248249// IsEmpty returns true if the pattern is effectively empty250func (p *Pattern) IsEmpty() bool {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 := _cache.Lookup(chunk, cacheKey); cached != nil {286			return cached287		}288	}289290	// Prefix/suffix cache291	space := _cache.Search(chunk, cacheKey)292293	matches := p.matchChunk(chunk, space, slab)294295	if p.cacheable {296		_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 space == nil {305		for idx := 0; idx < chunk.count; idx++ {306			if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match != nil {307				matches = append(matches, *match)308			}309		}310	} else {311		for _, result := range space {312			if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match != nil {313				matches = append(matches, *match)314			}315		}316	}317	return matches318}319320// MatchItem returns true if the Item is a match321func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {322	if p.extended {323		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {324			result := buildResult(item, offsets, bonus)325			return &result, offsets, pos326		}327		return nil, nil, nil328	}329	offset, bonus, pos := p.basicMatch(item, withPos, slab)330	if sidx := offset[0]; sidx >= 0 {331		offsets := []Offset{offset}332		result := buildResult(item, offsets, bonus)333		return &result, offsets, pos334	}335	return nil, nil, nil336}337338func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {339	var input []Token340	if len(p.nth) == 0 {341		input = []Token{{text: &item.text, prefixLength: 0}}342	} else {343		input = p.transformInput(item)344	}345	if p.fuzzy {346		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)347	}348	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)349}350351func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {352	var input []Token353	if len(p.nth) == 0 {354		input = []Token{{text: &item.text, prefixLength: 0}}355	} else {356		input = p.transformInput(item)357	}358	offsets := []Offset{}359	var totalScore int360	var allPos *[]int361	if withPos {362		allPos = &[]int{}363	}364	for _, termSet := range p.termSets {365		var offset Offset366		var currentScore int367		matched := false368		for _, term := range termSet {369			pfun := p.procFun[term.typ]370			off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)371			if sidx := off[0]; sidx >= 0 {372				if term.inv {373					continue374				}375				offset, currentScore = off, score376				matched = true377				if withPos {378					if pos != nil {379						*allPos = append(*allPos, *pos...)380					} else {381						for idx := off[0]; idx < off[1]; idx++ {382							*allPos = append(*allPos, int(idx))383						}384					}385				}386				break387			} else if term.inv {388				offset, currentScore = Offset{0, 0}, 0389				matched = true390				continue391			}392		}393		if matched {394			offsets = append(offsets, offset)395			totalScore += currentScore396		}397	}398	return offsets, totalScore, allPos399}400401func (p *Pattern) transformInput(item *Item) []Token {402	if item.transformed != nil {403		return *item.transformed404	}405406	tokens := Tokenize(item.text.ToString(), p.delimiter)407	ret := Transform(tokens, p.nth)408	item.transformed = &ret409	return ret410}411412func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {413	for _, part := range tokens {414		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {415			sidx := int32(res.Start) + part.prefixLength416			eidx := int32(res.End) + part.prefixLength417			if pos != nil {418				for idx := range *pos {419					(*pos)[idx] += int(part.prefixLength)420				}421			}422			return Offset{sidx, eidx}, res.Score, pos423		}424	}425	return Offset{-1, -1}, 0, nil426}