Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

328 lines · 7.4 KiB · Go

Last changed by

Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27

History of this file

Take it

1package fzf23import (4	"regexp"5	"sort"6	"strings"78	"github.com/junegunn/fzf/src/algo"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)2829type term struct {30	typ           termType31	inv           bool32	text          []rune33	caseSensitive bool34	origText      []rune35}3637// Pattern represents search pattern38type Pattern struct {39	mode          Mode40	caseSensitive bool41	text          []rune42	terms         []term43	hasInvTerm    bool44	delimiter     *regexp.Regexp45	nth           []Range46	procFun       map[termType]func(bool, *[]rune, []rune) (int, int)47}4849var (50	_patternCache map[string]*Pattern51	_splitRegex   *regexp.Regexp52	_cache        ChunkCache53)5455func init() {56	_splitRegex = regexp.MustCompile("\\s+")57	clearPatternCache()58	clearChunkCache()59}6061func clearPatternCache() {62	// We can uniquely identify the pattern for a given string since63	// mode and caseMode do not change while the program is running64	_patternCache = make(map[string]*Pattern)65}6667func clearChunkCache() {68	_cache = NewChunkCache()69}7071// BuildPattern builds Pattern object from the given arguments72func BuildPattern(mode Mode, caseMode Case,73	nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {7475	var asString string76	switch mode {77	case ModeExtended, ModeExtendedExact:78		asString = strings.Trim(string(runes), " ")79	default:80		asString = string(runes)81	}8283	cached, found := _patternCache[asString]84	if found {85		return cached86	}8788	caseSensitive, hasInvTerm := true, false89	terms := []term{}9091	switch mode {92	case ModeExtended, ModeExtendedExact:93		terms = parseTerms(mode, caseMode, asString)94		for _, term := range terms {95			if term.inv {96				hasInvTerm = true97			}98		}99	default:100		lowerString := strings.ToLower(asString)101		caseSensitive = caseMode == CaseRespect ||102			caseMode == CaseSmart && lowerString != asString103		if !caseSensitive {104			asString = lowerString105		}106	}107108	ptr := &Pattern{109		mode:          mode,110		caseSensitive: caseSensitive,111		text:          []rune(asString),112		terms:         terms,113		hasInvTerm:    hasInvTerm,114		nth:           nth,115		delimiter:     delimiter,116		procFun:       make(map[termType]func(bool, *[]rune, []rune) (int, int))}117118	ptr.procFun[termFuzzy] = algo.FuzzyMatch119	ptr.procFun[termExact] = algo.ExactMatchNaive120	ptr.procFun[termPrefix] = algo.PrefixMatch121	ptr.procFun[termSuffix] = algo.SuffixMatch122123	_patternCache[asString] = ptr124	return ptr125}126127func parseTerms(mode Mode, caseMode Case, str string) []term {128	tokens := _splitRegex.Split(str, -1)129	terms := []term{}130	for _, token := range tokens {131		typ, inv, text := termFuzzy, false, token132		lowerText := strings.ToLower(text)133		caseSensitive := caseMode == CaseRespect ||134			caseMode == CaseSmart && text != lowerText135		if !caseSensitive {136			text = lowerText137		}138		origText := []rune(text)139		if mode == ModeExtendedExact {140			typ = termExact141		}142143		if strings.HasPrefix(text, "!") {144			inv = true145			text = text[1:]146		}147148		if strings.HasPrefix(text, "'") {149			if mode == ModeExtended {150				typ = termExact151				text = text[1:]152			}153		} else if strings.HasPrefix(text, "^") {154			typ = termPrefix155			text = text[1:]156		} else if strings.HasSuffix(text, "$") {157			typ = termSuffix158			text = text[:len(text)-1]159		}160161		if len(text) > 0 {162			terms = append(terms, term{163				typ:           typ,164				inv:           inv,165				text:          []rune(text),166				caseSensitive: caseSensitive,167				origText:      origText})168		}169	}170	return terms171}172173// IsEmpty returns true if the pattern is effectively empty174func (p *Pattern) IsEmpty() bool {175	if p.mode == ModeFuzzy {176		return len(p.text) == 0177	}178	return len(p.terms) == 0179}180181// AsString returns the search query in string type182func (p *Pattern) AsString() string {183	return string(p.text)184}185186// CacheKey is used to build string to be used as the key of result cache187func (p *Pattern) CacheKey() string {188	if p.mode == ModeFuzzy {189		return p.AsString()190	}191	cacheableTerms := []string{}192	for _, term := range p.terms {193		if term.inv {194			continue195		}196		cacheableTerms = append(cacheableTerms, string(term.origText))197	}198	return strings.Join(cacheableTerms, " ")199}200201// Match returns the list of matches Items in the given Chunk202func (p *Pattern) Match(chunk *Chunk) []*Item {203	space := chunk204205	// ChunkCache: Exact match206	cacheKey := p.CacheKey()207	if !p.hasInvTerm { // Because we're excluding Inv-term from cache key208		if cached, found := _cache.Find(chunk, cacheKey); found {209			return cached210		}211	}212213	// ChunkCache: Prefix/suffix match214Loop:215	for idx := 1; idx < len(cacheKey); idx++ {216		// [---------| ] | [ |---------]217		// [--------|  ] | [  |--------]218		// [-------|   ] | [   |-------]219		prefix := cacheKey[:len(cacheKey)-idx]220		suffix := cacheKey[idx:]221		for _, substr := range [2]*string{&prefix, &suffix} {222			if cached, found := _cache.Find(chunk, *substr); found {223				cachedChunk := Chunk(cached)224				space = &cachedChunk225				break Loop226			}227		}228	}229230	matches := p.matchChunk(space)231232	if !p.hasInvTerm {233		_cache.Add(chunk, cacheKey, matches)234	}235	return matches236}237238func (p *Pattern) matchChunk(chunk *Chunk) []*Item {239	matches := []*Item{}240	if p.mode == ModeFuzzy {241		for _, item := range *chunk {242			if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {243				matches = append(matches,244					dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))245			}246		}247	} else {248		for _, item := range *chunk {249			if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {250				matches = append(matches, dupItem(item, offsets))251			}252		}253	}254	return matches255}256257// MatchItem returns true if the Item is a match258func (p *Pattern) MatchItem(item *Item) bool {259	if p.mode == ModeFuzzy {260		sidx, _ := p.fuzzyMatch(item)261		return sidx >= 0262	}263	offsets := p.extendedMatch(item)264	return len(offsets) == len(p.terms)265}266267func dupItem(item *Item, offsets []Offset) *Item {268	sort.Sort(ByOrder(offsets))269	return &Item{270		text:        item.text,271		origText:    item.origText,272		transformed: item.transformed,273		index:       item.index,274		offsets:     offsets,275		colors:      item.colors,276		rank:        Rank{0, 0, item.index}}277}278279func (p *Pattern) fuzzyMatch(item *Item) (int, int) {280	input := p.prepareInput(item)281	return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)282}283284func (p *Pattern) extendedMatch(item *Item) []Offset {285	input := p.prepareInput(item)286	offsets := []Offset{}287	for _, term := range p.terms {288		pfun := p.procFun[term.typ]289		if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {290			if term.inv {291				break292			}293			offsets = append(offsets, Offset{int32(sidx), int32(eidx)})294		} else if term.inv {295			offsets = append(offsets, Offset{0, 0})296		}297	}298	return offsets299}300301func (p *Pattern) prepareInput(item *Item) *[]Token {302	if item.transformed != nil {303		return item.transformed304	}305306	var ret *[]Token307	if len(p.nth) > 0 {308		tokens := Tokenize(item.text, p.delimiter)309		ret = Transform(tokens, p.nth)310	} else {311		runes := []rune(*item.text)312		trans := []Token{Token{text: &runes, prefixLength: 0}}313		ret = &trans314	}315	item.transformed = ret316	return ret317}318319func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),320	tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {321	for _, part := range *tokens {322		prefixLength := part.prefixLength323		if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {324			return sidx + prefixLength, eidx + prefixLength325		}326	}327	return -1, -1328}