Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

425 lines · 10.3 KiB · Go

Last changed by

Smart match of accented charactersJunegunn Choibefore adoptionf092e40

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	text          []rune55	termSets      []termSet56	sortable      bool57	cacheable     bool58	cacheKey      string59	delimiter     Delimiter60	nth           []Range61	procFun       map[termType]algo.Algo62}6364var (65	_patternCache map[string]*Pattern66	_splitRegex   *regexp.Regexp67	_cache        ChunkCache68)6970func init() {71	_splitRegex = regexp.MustCompile(" +")72	clearPatternCache()73	clearChunkCache()74}7576func clearPatternCache() {77	// We can uniquely identify the pattern for a given string since78	// search mode and caseMode do not change while the program is running79	_patternCache = make(map[string]*Pattern)80}8182func clearChunkCache() {83	_cache = NewChunkCache()84}8586// BuildPattern builds Pattern object from the given arguments87func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,88	cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8990	var asString string91	if extended {92		asString = strings.TrimLeft(string(runes), " ")93		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {94			asString = asString[:len(asString)-1]95		}96	} else {97		asString = string(runes)98	}99100	cached, found := _patternCache[asString]101	if found {102		return cached103	}104105	caseSensitive := true106	sortable := true107	termSets := []termSet{}108109	if extended {110		termSets = parseTerms(fuzzy, caseMode, normalize, asString)111		// We should not sort the result if there are only inverse search terms112		sortable = false113	Loop:114		for _, termSet := range termSets {115			for idx, term := range termSet {116				if !term.inv {117					sortable = true118				}119				// If the query contains inverse search terms or OR operators,120				// we cannot cache the search scope121				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {122					cacheable = false123					if sortable {124						// Can't break until we see at least one non-inverse term125						break Loop126					}127				}128			}129		}130	} else {131		lowerString := strings.ToLower(asString)132		normalize = normalize &&133			lowerString == string(algo.NormalizeRunes([]rune(lowerString)))134		caseSensitive = caseMode == CaseRespect ||135			caseMode == CaseSmart && lowerString != asString136		if !caseSensitive {137			asString = lowerString138		}139	}140141	ptr := &Pattern{142		fuzzy:         fuzzy,143		fuzzyAlgo:     fuzzyAlgo,144		extended:      extended,145		caseSensitive: caseSensitive,146		normalize:     normalize,147		forward:       forward,148		text:          []rune(asString),149		termSets:      termSets,150		sortable:      sortable,151		cacheable:     cacheable,152		nth:           nth,153		delimiter:     delimiter,154		procFun:       make(map[termType]algo.Algo)}155156	ptr.cacheKey = ptr.buildCacheKey()157	ptr.procFun[termFuzzy] = fuzzyAlgo158	ptr.procFun[termEqual] = algo.EqualMatch159	ptr.procFun[termExact] = algo.ExactMatchNaive160	ptr.procFun[termPrefix] = algo.PrefixMatch161	ptr.procFun[termSuffix] = algo.SuffixMatch162163	_patternCache[asString] = ptr164	return ptr165}166167func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {168	str = strings.Replace(str, "\\ ", "\t", -1)169	tokens := _splitRegex.Split(str, -1)170	sets := []termSet{}171	set := termSet{}172	switchSet := false173	afterBar := false174	for _, token := range tokens {175		typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)176		lowerText := strings.ToLower(text)177		caseSensitive := caseMode == CaseRespect ||178			caseMode == CaseSmart && text != lowerText179		normalizeTerm := normalize &&180			lowerText == string(algo.NormalizeRunes([]rune(lowerText)))181		if !caseSensitive {182			text = lowerText183		}184		if !fuzzy {185			typ = termExact186		}187188		if len(set) > 0 && !afterBar && text == "|" {189			switchSet = false190			afterBar = true191			continue192		}193		afterBar = false194195		if strings.HasPrefix(text, "!") {196			inv = true197			typ = termExact198			text = text[1:]199		}200201		if text != "$" && strings.HasSuffix(text, "$") {202			typ = termSuffix203			text = text[:len(text)-1]204		}205206		if strings.HasPrefix(text, "'") {207			// Flip exactness208			if fuzzy && !inv {209				typ = termExact210				text = text[1:]211			} else {212				typ = termFuzzy213				text = text[1:]214			}215		} else if strings.HasPrefix(text, "^") {216			if typ == termSuffix {217				typ = termEqual218			} else {219				typ = termPrefix220			}221			text = text[1:]222		}223224		if len(text) > 0 {225			if switchSet {226				sets = append(sets, set)227				set = termSet{}228			}229			textRunes := []rune(text)230			if normalizeTerm {231				textRunes = algo.NormalizeRunes(textRunes)232			}233			set = append(set, term{234				typ:           typ,235				inv:           inv,236				text:          textRunes,237				caseSensitive: caseSensitive,238				normalize:     normalizeTerm})239			switchSet = true240		}241	}242	if len(set) > 0 {243		sets = append(sets, set)244	}245	return sets246}247248// IsEmpty returns true if the pattern is effectively empty249func (p *Pattern) IsEmpty() bool {250	if !p.extended {251		return len(p.text) == 0252	}253	return len(p.termSets) == 0254}255256// AsString returns the search query in string type257func (p *Pattern) AsString() string {258	return string(p.text)259}260261func (p *Pattern) buildCacheKey() string {262	if !p.extended {263		return p.AsString()264	}265	cacheableTerms := []string{}266	for _, termSet := range p.termSets {267		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {268			cacheableTerms = append(cacheableTerms, string(termSet[0].text))269		}270	}271	return strings.Join(cacheableTerms, "\t")272}273274// CacheKey is used to build string to be used as the key of result cache275func (p *Pattern) CacheKey() string {276	return p.cacheKey277}278279// Match returns the list of matches Items in the given Chunk280func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {281	// ChunkCache: Exact match282	cacheKey := p.CacheKey()283	if p.cacheable {284		if cached := _cache.Lookup(chunk, cacheKey); cached != nil {285			return cached286		}287	}288289	// Prefix/suffix cache290	space := _cache.Search(chunk, cacheKey)291292	matches := p.matchChunk(chunk, space, slab)293294	if p.cacheable {295		_cache.Add(chunk, cacheKey, matches)296	}297	return matches298}299300func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {301	matches := []Result{}302303	if space == nil {304		for idx := 0; idx < chunk.count; idx++ {305			if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {306				matches = append(matches, *match)307			}308		}309	} else {310		for _, result := range space {311			if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {312				matches = append(matches, *match)313			}314		}315	}316	return matches317}318319// MatchItem returns true if the Item is a match320func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {321	if p.extended {322		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {323			result := buildResult(item, offsets, bonus)324			return &result, offsets, pos325		}326		return nil, nil, nil327	}328	offset, bonus, pos := p.basicMatch(item, withPos, slab)329	if sidx := offset[0]; sidx >= 0 {330		offsets := []Offset{offset}331		result := buildResult(item, offsets, bonus)332		return &result, offsets, pos333	}334	return nil, nil, nil335}336337func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {338	var input []Token339	if len(p.nth) == 0 {340		input = []Token{Token{text: &item.text, prefixLength: 0}}341	} else {342		input = p.transformInput(item)343	}344	if p.fuzzy {345		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)346	}347	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)348}349350func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {351	var input []Token352	if len(p.nth) == 0 {353		input = []Token{Token{text: &item.text, prefixLength: 0}}354	} else {355		input = p.transformInput(item)356	}357	offsets := []Offset{}358	var totalScore int359	var allPos *[]int360	if withPos {361		allPos = &[]int{}362	}363	for _, termSet := range p.termSets {364		var offset Offset365		var currentScore int366		matched := false367		for _, term := range termSet {368			pfun := p.procFun[term.typ]369			off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)370			if sidx := off[0]; sidx >= 0 {371				if term.inv {372					continue373				}374				offset, currentScore = off, score375				matched = true376				if withPos {377					if pos != nil {378						*allPos = append(*allPos, *pos...)379					} else {380						for idx := off[0]; idx < off[1]; idx++ {381							*allPos = append(*allPos, int(idx))382						}383					}384				}385				break386			} else if term.inv {387				offset, currentScore = Offset{0, 0}, 0388				matched = true389				continue390			}391		}392		if matched {393			offsets = append(offsets, offset)394			totalScore += currentScore395		}396	}397	return offsets, totalScore, allPos398}399400func (p *Pattern) transformInput(item *Item) []Token {401	if item.transformed != nil {402		return *item.transformed403	}404405	tokens := Tokenize(item.text.ToString(), p.delimiter)406	ret := Transform(tokens, p.nth)407	item.transformed = &ret408	return ret409}410411func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {412	for _, part := range tokens {413		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {414			sidx := int32(res.Start) + part.prefixLength415			eidx := int32(res.End) + part.prefixLength416			if pos != nil {417				for idx := range *pos {418					(*pos)[idx] += int(part.prefixLength)419				}420			}421			return Offset{sidx, eidx}, res.Score, pos422		}423	}424	return Offset{-1, -1}, 0, nil425}