Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

394 lines · 9.3 KiB · Go

Last changed by

Revise ranking algorithmJunegunn Choibefore adoption2fc7c18

History of this file

Take it

1package fzf23import (4	"regexp"5	"strings"67	"github.com/junegunn/fzf/src/algo"8	"github.com/junegunn/fzf/src/util"9)1011// fuzzy12// 'exact13// ^exact-prefix14// exact-suffix$15// !not-fuzzy16// !'not-exact17// !^not-exact-prefix18// !not-exact-suffix$1920type termType int2122const (23	termFuzzy termType = iota24	termExact25	termPrefix26	termSuffix27	termEqual28)2930type term struct {31	typ           termType32	inv           bool33	text          []rune34	caseSensitive bool35	origText      []rune36}3738type termSet []term3940// Pattern represents search pattern41type Pattern struct {42	fuzzy         bool43	fuzzyAlgo     algo.Algo44	extended      bool45	caseSensitive bool46	forward       bool47	text          []rune48	termSets      []termSet49	cacheable     bool50	delimiter     Delimiter51	nth           []Range52	procFun       map[termType]algo.Algo53}5455var (56	_patternCache map[string]*Pattern57	_splitRegex   *regexp.Regexp58	_cache        ChunkCache59)6061func init() {62	_splitRegex = regexp.MustCompile("\\s+")63	clearPatternCache()64	clearChunkCache()65}6667func clearPatternCache() {68	// We can uniquely identify the pattern for a given string since69	// search mode and caseMode do not change while the program is running70	_patternCache = make(map[string]*Pattern)71}7273func clearChunkCache() {74	_cache = NewChunkCache()75}7677// BuildPattern builds Pattern object from the given arguments78func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, forward bool,79	cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8081	var asString string82	if extended {83		asString = strings.Trim(string(runes), " ")84	} else {85		asString = string(runes)86	}8788	cached, found := _patternCache[asString]89	if found {90		return cached91	}9293	caseSensitive := true94	termSets := []termSet{}9596	if extended {97		termSets = parseTerms(fuzzy, caseMode, asString)98	Loop:99		for _, termSet := range termSets {100			for idx, term := range termSet {101				// If the query contains inverse search terms or OR operators,102				// we cannot cache the search scope103				if !cacheable || idx > 0 || term.inv {104					cacheable = false105					break Loop106				}107			}108		}109	} else {110		lowerString := strings.ToLower(asString)111		caseSensitive = caseMode == CaseRespect ||112			caseMode == CaseSmart && lowerString != asString113		if !caseSensitive {114			asString = lowerString115		}116	}117118	ptr := &Pattern{119		fuzzy:         fuzzy,120		fuzzyAlgo:     fuzzyAlgo,121		extended:      extended,122		caseSensitive: caseSensitive,123		forward:       forward,124		text:          []rune(asString),125		termSets:      termSets,126		cacheable:     cacheable,127		nth:           nth,128		delimiter:     delimiter,129		procFun:       make(map[termType]algo.Algo)}130131	ptr.procFun[termFuzzy] = fuzzyAlgo132	ptr.procFun[termEqual] = algo.EqualMatch133	ptr.procFun[termExact] = algo.ExactMatchNaive134	ptr.procFun[termPrefix] = algo.PrefixMatch135	ptr.procFun[termSuffix] = algo.SuffixMatch136137	_patternCache[asString] = ptr138	return ptr139}140141func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {142	tokens := _splitRegex.Split(str, -1)143	sets := []termSet{}144	set := termSet{}145	switchSet := false146	for _, token := range tokens {147		typ, inv, text := termFuzzy, false, token148		lowerText := strings.ToLower(text)149		caseSensitive := caseMode == CaseRespect ||150			caseMode == CaseSmart && text != lowerText151		if !caseSensitive {152			text = lowerText153		}154		origText := []rune(text)155		if !fuzzy {156			typ = termExact157		}158159		if text == "|" {160			switchSet = false161			continue162		}163164		if strings.HasPrefix(text, "!") {165			inv = true166			text = text[1:]167		}168169		if strings.HasPrefix(text, "'") {170			// Flip exactness171			if fuzzy {172				typ = termExact173				text = text[1:]174			} else {175				typ = termFuzzy176				text = text[1:]177			}178		} else if strings.HasPrefix(text, "^") {179			if strings.HasSuffix(text, "$") {180				typ = termEqual181				text = text[1 : len(text)-1]182			} else {183				typ = termPrefix184				text = text[1:]185			}186		} else if strings.HasSuffix(text, "$") {187			typ = termSuffix188			text = text[:len(text)-1]189		}190191		if len(text) > 0 {192			if switchSet {193				sets = append(sets, set)194				set = termSet{}195			}196			set = append(set, term{197				typ:           typ,198				inv:           inv,199				text:          []rune(text),200				caseSensitive: caseSensitive,201				origText:      origText})202			switchSet = true203		}204	}205	if len(set) > 0 {206		sets = append(sets, set)207	}208	return sets209}210211// IsEmpty returns true if the pattern is effectively empty212func (p *Pattern) IsEmpty() bool {213	if !p.extended {214		return len(p.text) == 0215	}216	return len(p.termSets) == 0217}218219// AsString returns the search query in string type220func (p *Pattern) AsString() string {221	return string(p.text)222}223224// CacheKey is used to build string to be used as the key of result cache225func (p *Pattern) CacheKey() string {226	if !p.extended {227		return p.AsString()228	}229	cacheableTerms := []string{}230	for _, termSet := range p.termSets {231		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {232			cacheableTerms = append(cacheableTerms, string(termSet[0].origText))233		}234	}235	return strings.Join(cacheableTerms, " ")236}237238// Match returns the list of matches Items in the given Chunk239func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {240	// ChunkCache: Exact match241	cacheKey := p.CacheKey()242	if p.cacheable {243		if cached, found := _cache.Find(chunk, cacheKey); found {244			return cached245		}246	}247248	// Prefix/suffix cache249	var space []*Result250Loop:251	for idx := 1; idx < len(cacheKey); idx++ {252		// [---------| ] | [ |---------]253		// [--------|  ] | [  |--------]254		// [-------|   ] | [   |-------]255		prefix := cacheKey[:len(cacheKey)-idx]256		suffix := cacheKey[idx:]257		for _, substr := range [2]*string{&prefix, &suffix} {258			if cached, found := _cache.Find(chunk, *substr); found {259				space = cached260				break Loop261			}262		}263	}264265	matches := p.matchChunk(chunk, space, slab)266267	if p.cacheable {268		_cache.Add(chunk, cacheKey, matches)269	}270	return matches271}272273func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {274	matches := []*Result{}275276	if space == nil {277		for _, item := range *chunk {278			if match, _, _ := p.MatchItem(item, false, slab); match != nil {279				matches = append(matches, match)280			}281		}282	} else {283		for _, result := range space {284			if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {285				matches = append(matches, match)286			}287		}288	}289	return matches290}291292// MatchItem returns true if the Item is a match293func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {294	if p.extended {295		if offsets, bonus, trimLen, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {296			return buildResult(item, offsets, bonus, trimLen), offsets, pos297		}298		return nil, nil, nil299	}300	offset, bonus, trimLen, pos := p.basicMatch(item, withPos, slab)301	if sidx := offset[0]; sidx >= 0 {302		offsets := []Offset{offset}303		return buildResult(item, offsets, bonus, trimLen), offsets, pos304	}305	return nil, nil, nil306}307308func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {309	input := p.prepareInput(item)310	if p.fuzzy {311		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.forward, p.text, withPos, slab)312	}313	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text, withPos, slab)314}315316func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, int, *[]int) {317	input := p.prepareInput(item)318	offsets := []Offset{}319	var totalScore int320	var totalTrimLen int321	var allPos *[]int322	if withPos {323		allPos = &[]int{}324	}325	for _, termSet := range p.termSets {326		var offset Offset327		var currentScore int328		var trimLen int329		matched := false330		for _, term := range termSet {331			pfun := p.procFun[term.typ]332			off, score, tLen, pos := p.iter(pfun, input, term.caseSensitive, p.forward, term.text, withPos, slab)333			if sidx := off[0]; sidx >= 0 {334				if term.inv {335					continue336				}337				offset, currentScore, trimLen = off, score, tLen338				matched = true339				if withPos {340					if pos != nil {341						*allPos = append(*allPos, *pos...)342					} else {343						for idx := off[0]; idx < off[1]; idx++ {344							*allPos = append(*allPos, int(idx))345						}346					}347				}348				break349			} else if term.inv {350				offset, currentScore, trimLen = Offset{0, 0}, 0, 0351				matched = true352				continue353			}354		}355		if matched {356			offsets = append(offsets, offset)357			totalScore += currentScore358			totalTrimLen += trimLen359		}360	}361	return offsets, totalScore, totalTrimLen, allPos362}363364func (p *Pattern) prepareInput(item *Item) []Token {365	if item.transformed != nil {366		return item.transformed367	}368369	var ret []Token370	if len(p.nth) == 0 {371		ret = []Token{Token{text: &item.text, prefixLength: 0, trimLength: int32(item.text.TrimLength())}}372	} else {373		tokens := Tokenize(item.text, p.delimiter)374		ret = Transform(tokens, p.nth)375	}376	item.transformed = ret377	return ret378}379380func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {381	for _, part := range tokens {382		if res, pos := pfun(caseSensitive, forward, *part.text, pattern, withPos, slab); res.Start >= 0 {383			sidx := int32(res.Start) + part.prefixLength384			eidx := int32(res.End) + part.prefixLength385			if pos != nil {386				for idx := range *pos {387					(*pos)[idx] += int(part.prefixLength)388				}389			}390			return Offset{sidx, eidx}, res.Score, int(part.trimLength), pos391		}392	}393	return Offset{-1, -1}, 0, -1, nil394}