Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

309 lines · 6.8 KiB · Go

Last changed by

Merge pull request #116 from junegunn/goJunegunn Choibefore adoption209a6d3

History of this file

Take it

1package fzf23import (4	"regexp"5	"sort"6	"strings"78	"github.com/junegunn/fzf/src/algo"9)1011const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"1213// fuzzy14// 'exact15// ^exact-prefix16// exact-suffix$17// !not-fuzzy18// !'not-exact19// !^not-exact-prefix20// !not-exact-suffix$2122type termType int2324const (25	termFuzzy termType = iota26	termExact27	termPrefix28	termSuffix29)3031type term struct {32	typ      termType33	inv      bool34	text     []rune35	origText []rune36}3738// Pattern represents search pattern39type Pattern struct {40	mode          Mode41	caseSensitive bool42	text          []rune43	terms         []term44	hasInvTerm    bool45	delimiter     *regexp.Regexp46	nth           []Range47	procFun       map[termType]func(bool, *string, []rune) (int, int)48}4950var (51	_patternCache map[string]*Pattern52	_splitRegex   *regexp.Regexp53	_cache        ChunkCache54)5556func init() {57	// We can uniquely identify the pattern for a given string since58	// mode and caseMode do not change while the program is running59	_patternCache = make(map[string]*Pattern)60	_splitRegex = regexp.MustCompile("\\s+")61	_cache = NewChunkCache()62}6364func clearPatternCache() {65	_patternCache = make(map[string]*Pattern)66}6768// BuildPattern builds Pattern object from the given arguments69func BuildPattern(mode Mode, caseMode Case,70	nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {7172	var asString string73	switch mode {74	case ModeExtended, ModeExtendedExact:75		asString = strings.Trim(string(runes), " ")76	default:77		asString = string(runes)78	}7980	cached, found := _patternCache[asString]81	if found {82		return cached83	}8485	caseSensitive, hasInvTerm := true, false86	terms := []term{}8788	switch caseMode {89	case CaseSmart:90		if !strings.ContainsAny(asString, uppercaseLetters) {91			runes, caseSensitive = []rune(strings.ToLower(asString)), false92		}93	case CaseIgnore:94		runes, caseSensitive = []rune(strings.ToLower(asString)), false95	}9697	switch mode {98	case ModeExtended, ModeExtendedExact:99		terms = parseTerms(mode, string(runes))100		for _, term := range terms {101			if term.inv {102				hasInvTerm = true103			}104		}105	}106107	ptr := &Pattern{108		mode:          mode,109		caseSensitive: caseSensitive,110		text:          runes,111		terms:         terms,112		hasInvTerm:    hasInvTerm,113		nth:           nth,114		delimiter:     delimiter,115		procFun:       make(map[termType]func(bool, *string, []rune) (int, int))}116117	ptr.procFun[termFuzzy] = algo.FuzzyMatch118	ptr.procFun[termExact] = algo.ExactMatchNaive119	ptr.procFun[termPrefix] = algo.PrefixMatch120	ptr.procFun[termSuffix] = algo.SuffixMatch121122	_patternCache[asString] = ptr123	return ptr124}125126func parseTerms(mode Mode, str string) []term {127	tokens := _splitRegex.Split(str, -1)128	terms := []term{}129	for _, token := range tokens {130		typ, inv, text := termFuzzy, false, token131		origText := []rune(text)132		if mode == ModeExtendedExact {133			typ = termExact134		}135136		if strings.HasPrefix(text, "!") {137			inv = true138			text = text[1:]139		}140141		if strings.HasPrefix(text, "'") {142			if mode == ModeExtended {143				typ = termExact144				text = text[1:]145			}146		} else if strings.HasPrefix(text, "^") {147			typ = termPrefix148			text = text[1:]149		} else if strings.HasSuffix(text, "$") {150			typ = termSuffix151			text = text[:len(text)-1]152		}153154		if len(text) > 0 {155			terms = append(terms, term{156				typ:      typ,157				inv:      inv,158				text:     []rune(text),159				origText: origText})160		}161	}162	return terms163}164165// IsEmpty returns true if the pattern is effectively empty166func (p *Pattern) IsEmpty() bool {167	if p.mode == ModeFuzzy {168		return len(p.text) == 0169	}170	return len(p.terms) == 0171}172173// AsString returns the search query in string type174func (p *Pattern) AsString() string {175	return string(p.text)176}177178// CacheKey is used to build string to be used as the key of result cache179func (p *Pattern) CacheKey() string {180	if p.mode == ModeFuzzy {181		return p.AsString()182	}183	cacheableTerms := []string{}184	for _, term := range p.terms {185		if term.inv {186			continue187		}188		cacheableTerms = append(cacheableTerms, string(term.origText))189	}190	return strings.Join(cacheableTerms, " ")191}192193// Match returns the list of matches Items in the given Chunk194func (p *Pattern) Match(chunk *Chunk) []*Item {195	space := chunk196197	// ChunkCache: Exact match198	cacheKey := p.CacheKey()199	if !p.hasInvTerm { // Because we're excluding Inv-term from cache key200		if cached, found := _cache.Find(chunk, cacheKey); found {201			return cached202		}203	}204205	// ChunkCache: Prefix/suffix match206Loop:207	for idx := 1; idx < len(cacheKey); idx++ {208		// [---------| ] | [ |---------]209		// [--------|  ] | [  |--------]210		// [-------|   ] | [   |-------]211		prefix := cacheKey[:len(cacheKey)-idx]212		suffix := cacheKey[idx:]213		for _, substr := range [2]*string{&prefix, &suffix} {214			if cached, found := _cache.Find(chunk, *substr); found {215				cachedChunk := Chunk(cached)216				space = &cachedChunk217				break Loop218			}219		}220	}221222	var matches []*Item223	if p.mode == ModeFuzzy {224		matches = p.fuzzyMatch(space)225	} else {226		matches = p.extendedMatch(space)227	}228229	if !p.hasInvTerm {230		_cache.Add(chunk, cacheKey, matches)231	}232	return matches233}234235func dupItem(item *Item, offsets []Offset) *Item {236	sort.Sort(ByOrder(offsets))237	return &Item{238		text:        item.text,239		origText:    item.origText,240		transformed: item.transformed,241		index:       item.index,242		offsets:     offsets,243		rank:        Rank{0, 0, item.index}}244}245246func (p *Pattern) fuzzyMatch(chunk *Chunk) []*Item {247	matches := []*Item{}248	for _, item := range *chunk {249		input := p.prepareInput(item)250		if sidx, eidx := p.iter(algo.FuzzyMatch, input, p.text); sidx >= 0 {251			matches = append(matches,252				dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))253		}254	}255	return matches256}257258func (p *Pattern) extendedMatch(chunk *Chunk) []*Item {259	matches := []*Item{}260	for _, item := range *chunk {261		input := p.prepareInput(item)262		offsets := []Offset{}263		for _, term := range p.terms {264			pfun := p.procFun[term.typ]265			if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {266				if term.inv {267					break268				}269				offsets = append(offsets, Offset{int32(sidx), int32(eidx)})270			} else if term.inv {271				offsets = append(offsets, Offset{0, 0})272			}273		}274		if len(offsets) == len(p.terms) {275			matches = append(matches, dupItem(item, offsets))276		}277	}278	return matches279}280281func (p *Pattern) prepareInput(item *Item) *Transformed {282	if item.transformed != nil {283		return item.transformed284	}285286	var ret *Transformed287	if len(p.nth) > 0 {288		tokens := Tokenize(item.text, p.delimiter)289		ret = Transform(tokens, p.nth)290	} else {291		trans := Transformed{292			whole: item.text,293			parts: []Token{Token{text: item.text, prefixLength: 0}}}294		ret = &trans295	}296	item.transformed = ret297	return ret298}299300func (p *Pattern) iter(pfun func(bool, *string, []rune) (int, int),301	inputs *Transformed, pattern []rune) (int, int) {302	for _, part := range inputs.parts {303		prefixLength := part.prefixLength304		if sidx, eidx := pfun(p.caseSensitive, part.text, pattern); sidx >= 0 {305			return sidx + prefixLength, eidx + prefixLength306		}307	}308	return -1, -1309}