Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

339 lines · 7.8 KiB · Go

Last changed by

Use trimmed length when --nth is used with --tiebreak=lengthJunegunn Choibefore adoption92a75c9

History of this file

Take it

1package fzf23import (4	"regexp"5	"sort"6	"strings"78	"github.com/junegunn/fzf/src/algo"9	"github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact14// ^exact-prefix15// exact-suffix$16// !not-fuzzy17// !'not-exact18// !^not-exact-prefix19// !not-exact-suffix$2021type termType int2223const (24	termFuzzy termType = iota25	termExact26	termPrefix27	termSuffix28	termEqual29)3031type term struct {32	typ           termType33	inv           bool34	text          []rune35	caseSensitive bool36	origText      []rune37}3839// Pattern represents search pattern40type Pattern struct {41	mode          Mode42	caseSensitive bool43	forward       bool44	text          []rune45	terms         []term46	hasInvTerm    bool47	delimiter     Delimiter48	nth           []Range49	procFun       map[termType]func(bool, bool, []rune, []rune) (int, int)50}5152var (53	_patternCache map[string]*Pattern54	_splitRegex   *regexp.Regexp55	_cache        ChunkCache56)5758func init() {59	_splitRegex = regexp.MustCompile("\\s+")60	clearPatternCache()61	clearChunkCache()62}6364func clearPatternCache() {65	// We can uniquely identify the pattern for a given string since66	// mode and caseMode do not change while the program is running67	_patternCache = make(map[string]*Pattern)68}6970func clearChunkCache() {71	_cache = NewChunkCache()72}7374// BuildPattern builds Pattern object from the given arguments75func BuildPattern(mode Mode, caseMode Case, forward bool,76	nth []Range, delimiter Delimiter, runes []rune) *Pattern {7778	var asString string79	switch mode {80	case ModeExtended, ModeExtendedExact:81		asString = strings.Trim(string(runes), " ")82	default:83		asString = string(runes)84	}8586	cached, found := _patternCache[asString]87	if found {88		return cached89	}9091	caseSensitive, hasInvTerm := true, false92	terms := []term{}9394	switch mode {95	case ModeExtended, ModeExtendedExact:96		terms = parseTerms(mode, caseMode, asString)97		for _, term := range terms {98			if term.inv {99				hasInvTerm = true100			}101		}102	default:103		lowerString := strings.ToLower(asString)104		caseSensitive = caseMode == CaseRespect ||105			caseMode == CaseSmart && lowerString != asString106		if !caseSensitive {107			asString = lowerString108		}109	}110111	ptr := &Pattern{112		mode:          mode,113		caseSensitive: caseSensitive,114		forward:       forward,115		text:          []rune(asString),116		terms:         terms,117		hasInvTerm:    hasInvTerm,118		nth:           nth,119		delimiter:     delimiter,120		procFun:       make(map[termType]func(bool, bool, []rune, []rune) (int, int))}121122	ptr.procFun[termFuzzy] = algo.FuzzyMatch123	ptr.procFun[termEqual] = algo.EqualMatch124	ptr.procFun[termExact] = algo.ExactMatchNaive125	ptr.procFun[termPrefix] = algo.PrefixMatch126	ptr.procFun[termSuffix] = algo.SuffixMatch127128	_patternCache[asString] = ptr129	return ptr130}131132func parseTerms(mode Mode, caseMode Case, str string) []term {133	tokens := _splitRegex.Split(str, -1)134	terms := []term{}135	for _, token := range tokens {136		typ, inv, text := termFuzzy, false, token137		lowerText := strings.ToLower(text)138		caseSensitive := caseMode == CaseRespect ||139			caseMode == CaseSmart && text != lowerText140		if !caseSensitive {141			text = lowerText142		}143		origText := []rune(text)144		if mode == ModeExtendedExact {145			typ = termExact146		}147148		if strings.HasPrefix(text, "!") {149			inv = true150			text = text[1:]151		}152153		if strings.HasPrefix(text, "'") {154			if mode == ModeExtended {155				typ = termExact156				text = text[1:]157			} else if mode == ModeExtendedExact {158				typ = termFuzzy159				text = text[1:]160			}161		} else if strings.HasPrefix(text, "^") {162			if strings.HasSuffix(text, "$") {163				typ = termEqual164				text = text[1 : len(text)-1]165			} else {166				typ = termPrefix167				text = text[1:]168			}169		} else if strings.HasSuffix(text, "$") {170			typ = termSuffix171			text = text[:len(text)-1]172		}173174		if len(text) > 0 {175			terms = append(terms, term{176				typ:           typ,177				inv:           inv,178				text:          []rune(text),179				caseSensitive: caseSensitive,180				origText:      origText})181		}182	}183	return terms184}185186// IsEmpty returns true if the pattern is effectively empty187func (p *Pattern) IsEmpty() bool {188	if p.mode == ModeFuzzy {189		return len(p.text) == 0190	}191	return len(p.terms) == 0192}193194// AsString returns the search query in string type195func (p *Pattern) AsString() string {196	return string(p.text)197}198199// CacheKey is used to build string to be used as the key of result cache200func (p *Pattern) CacheKey() string {201	if p.mode == ModeFuzzy {202		return p.AsString()203	}204	cacheableTerms := []string{}205	for _, term := range p.terms {206		if term.inv {207			continue208		}209		cacheableTerms = append(cacheableTerms, string(term.origText))210	}211	return strings.Join(cacheableTerms, " ")212}213214// Match returns the list of matches Items in the given Chunk215func (p *Pattern) Match(chunk *Chunk) []*Item {216	space := chunk217218	// ChunkCache: Exact match219	cacheKey := p.CacheKey()220	if !p.hasInvTerm { // Because we're excluding Inv-term from cache key221		if cached, found := _cache.Find(chunk, cacheKey); found {222			return cached223		}224	}225226	// ChunkCache: Prefix/suffix match227Loop:228	for idx := 1; idx < len(cacheKey); idx++ {229		// [---------| ] | [ |---------]230		// [--------|  ] | [  |--------]231		// [-------|   ] | [   |-------]232		prefix := cacheKey[:len(cacheKey)-idx]233		suffix := cacheKey[idx:]234		for _, substr := range [2]*string{&prefix, &suffix} {235			if cached, found := _cache.Find(chunk, *substr); found {236				cachedChunk := Chunk(cached)237				space = &cachedChunk238				break Loop239			}240		}241	}242243	matches := p.matchChunk(space)244245	if !p.hasInvTerm {246		_cache.Add(chunk, cacheKey, matches)247	}248	return matches249}250251func (p *Pattern) matchChunk(chunk *Chunk) []*Item {252	matches := []*Item{}253	if p.mode == ModeFuzzy {254		for _, item := range *chunk {255			if sidx, eidx, tlen := p.fuzzyMatch(item); sidx >= 0 {256				matches = append(matches,257					dupItem(item, []Offset{Offset{int32(sidx), int32(eidx), int32(tlen)}}))258			}259		}260	} else {261		for _, item := range *chunk {262			if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {263				matches = append(matches, dupItem(item, offsets))264			}265		}266	}267	return matches268}269270// MatchItem returns true if the Item is a match271func (p *Pattern) MatchItem(item *Item) bool {272	if p.mode == ModeFuzzy {273		sidx, _, _ := p.fuzzyMatch(item)274		return sidx >= 0275	}276	offsets := p.extendedMatch(item)277	return len(offsets) == len(p.terms)278}279280func dupItem(item *Item, offsets []Offset) *Item {281	sort.Sort(ByOrder(offsets))282	return &Item{283		text:        item.text,284		origText:    item.origText,285		transformed: item.transformed,286		index:       item.index,287		offsets:     offsets,288		colors:      item.colors,289		rank:        Rank{0, 0, item.index}}290}291292func (p *Pattern) fuzzyMatch(item *Item) (int, int, int) {293	input := p.prepareInput(item)294	return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)295}296297func (p *Pattern) extendedMatch(item *Item) []Offset {298	input := p.prepareInput(item)299	offsets := []Offset{}300	for _, term := range p.terms {301		pfun := p.procFun[term.typ]302		if sidx, eidx, tlen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text); sidx >= 0 {303			if term.inv {304				break305			}306			offsets = append(offsets, Offset{int32(sidx), int32(eidx), int32(tlen)})307		} else if term.inv {308			offsets = append(offsets, Offset{0, 0, 0})309		}310	}311	return offsets312}313314func (p *Pattern) prepareInput(item *Item) []Token {315	if item.transformed != nil {316		return item.transformed317	}318319	var ret []Token320	if len(p.nth) > 0 {321		tokens := Tokenize(item.text, p.delimiter)322		ret = Transform(tokens, p.nth)323	} else {324		ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: util.TrimLen(item.text)}}325	}326	item.transformed = ret327	return ret328}329330func (p *Pattern) iter(pfun func(bool, bool, []rune, []rune) (int, int),331	tokens []Token, caseSensitive bool, forward bool, pattern []rune) (int, int, int) {332	for _, part := range tokens {333		prefixLength := part.prefixLength334		if sidx, eidx := pfun(caseSensitive, forward, part.text, pattern); sidx >= 0 {335			return sidx + prefixLength, eidx + prefixLength, part.trimLength336		}337	}338	return -1, -1, -1 // math.MaxUint16339}