Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

427 lines · 10.3 KiB · Go

Last changed by

Fix incorrect ordering of `--tiebreak=chunk`Junegunn Choibefore adoption38259d0

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				text = text[1:]213			} else {214				typ = termFuzzy215				text = text[1:]216			}217		} else if strings.HasPrefix(text, "^") {218			if typ == termSuffix {219				typ = termEqual220			} else {221				typ = termPrefix222			}223			text = text[1:]224		}225226		if len(text) > 0 {227			if switchSet {228				sets = append(sets, set)229				set = termSet{}230			}231			textRunes := []rune(text)232			if normalizeTerm {233				textRunes = algo.NormalizeRunes(textRunes)234			}235			set = append(set, term{236				typ:           typ,237				inv:           inv,238				text:          textRunes,239				caseSensitive: caseSensitive,240				normalize:     normalizeTerm})241			switchSet = true242		}243	}244	if len(set) > 0 {245		sets = append(sets, set)246	}247	return sets248}249250// IsEmpty returns true if the pattern is effectively empty251func (p *Pattern) IsEmpty() bool {252	if !p.extended {253		return len(p.text) == 0254	}255	return len(p.termSets) == 0256}257258// AsString returns the search query in string type259func (p *Pattern) AsString() string {260	return string(p.text)261}262263func (p *Pattern) buildCacheKey() string {264	if !p.extended {265		return p.AsString()266	}267	cacheableTerms := []string{}268	for _, termSet := range p.termSets {269		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {270			cacheableTerms = append(cacheableTerms, string(termSet[0].text))271		}272	}273	return strings.Join(cacheableTerms, "\t")274}275276// CacheKey is used to build string to be used as the key of result cache277func (p *Pattern) CacheKey() string {278	return p.cacheKey279}280281// Match returns the list of matches Items in the given Chunk282func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {283	// ChunkCache: Exact match284	cacheKey := p.CacheKey()285	if p.cacheable {286		if cached := _cache.Lookup(chunk, cacheKey); cached != nil {287			return cached288		}289	}290291	// Prefix/suffix cache292	space := _cache.Search(chunk, cacheKey)293294	matches := p.matchChunk(chunk, space, slab)295296	if p.cacheable {297		_cache.Add(chunk, cacheKey, matches)298	}299	return matches300}301302func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {303	matches := []Result{}304305	if space == nil {306		for idx := 0; idx < chunk.count; idx++ {307			if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match != nil {308				matches = append(matches, *match)309			}310		}311	} else {312		for _, result := range space {313			if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match != nil {314				matches = append(matches, *match)315			}316		}317	}318	return matches319}320321// MatchItem returns true if the Item is a match322func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {323	if p.extended {324		if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {325			result := buildResult(item, offsets, bonus)326			return &result, offsets, pos327		}328		return nil, nil, nil329	}330	offset, bonus, pos := p.basicMatch(item, withPos, slab)331	if sidx := offset[0]; sidx >= 0 {332		offsets := []Offset{offset}333		result := buildResult(item, offsets, bonus)334		return &result, offsets, pos335	}336	return nil, nil, nil337}338339func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {340	var input []Token341	if len(p.nth) == 0 {342		input = []Token{{text: &item.text, prefixLength: 0}}343	} else {344		input = p.transformInput(item)345	}346	if p.fuzzy {347		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)348	}349	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)350}351352func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {353	var input []Token354	if len(p.nth) == 0 {355		input = []Token{{text: &item.text, prefixLength: 0}}356	} else {357		input = p.transformInput(item)358	}359	offsets := []Offset{}360	var totalScore int361	var allPos *[]int362	if withPos {363		allPos = &[]int{}364	}365	for _, termSet := range p.termSets {366		var offset Offset367		var currentScore int368		matched := false369		for _, term := range termSet {370			pfun := p.procFun[term.typ]371			off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)372			if sidx := off[0]; sidx >= 0 {373				if term.inv {374					continue375				}376				offset, currentScore = off, score377				matched = true378				if withPos {379					if pos != nil {380						*allPos = append(*allPos, *pos...)381					} else {382						for idx := off[0]; idx < off[1]; idx++ {383							*allPos = append(*allPos, int(idx))384						}385					}386				}387				break388			} else if term.inv {389				offset, currentScore = Offset{0, 0}, 0390				matched = true391				continue392			}393		}394		if matched {395			offsets = append(offsets, offset)396			totalScore += currentScore397		}398	}399	return offsets, totalScore, allPos400}401402func (p *Pattern) transformInput(item *Item) []Token {403	if item.transformed != nil {404		return *item.transformed405	}406407	tokens := Tokenize(item.text.ToString(), p.delimiter)408	ret := Transform(tokens, p.nth)409	item.transformed = &ret410	return ret411}412413func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {414	for _, part := range tokens {415		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {416			sidx := int32(res.Start) + part.prefixLength417			eidx := int32(res.End) + part.prefixLength418			if pos != nil {419				for idx := range *pos {420					(*pos)[idx] += int(part.prefixLength)421				}422			}423			return Offset{sidx, eidx}, res.Score, pos424		}425	}426	return Offset{-1, -1}, 0, nil427}