Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

401 lines · 9.5 KiB · Go

Last changed by

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

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	normalize     bool47	forward       bool48	text          []rune49	termSets      []termSet50	cacheable     bool51	delimiter     Delimiter52	nth           []Range53	procFun       map[termType]algo.Algo54}5556var (57	_patternCache map[string]*Pattern58	_splitRegex   *regexp.Regexp59	_cache        ChunkCache60)6162func init() {63	_splitRegex = regexp.MustCompile("\\s+")64	clearPatternCache()65	clearChunkCache()66}6768func clearPatternCache() {69	// We can uniquely identify the pattern for a given string since70	// search mode and caseMode do not change while the program is running71	_patternCache = make(map[string]*Pattern)72}7374func clearChunkCache() {75	_cache = NewChunkCache()76}7778// BuildPattern builds Pattern object from the given arguments79func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,80	cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8182	var asString string83	if extended {84		asString = strings.Trim(string(runes), " ")85	} else {86		asString = string(runes)87	}8889	cached, found := _patternCache[asString]90	if found {91		return cached92	}9394	caseSensitive := true95	termSets := []termSet{}9697	if extended {98		termSets = parseTerms(fuzzy, caseMode, normalize, asString)99	Loop:100		for _, termSet := range termSets {101			for idx, term := range termSet {102				// If the query contains inverse search terms or OR operators,103				// we cannot cache the search scope104				if !cacheable || idx > 0 || term.inv {105					cacheable = false106					break Loop107				}108			}109		}110	} else {111		lowerString := strings.ToLower(asString)112		caseSensitive = caseMode == CaseRespect ||113			caseMode == CaseSmart && lowerString != asString114		if !caseSensitive {115			asString = lowerString116		}117	}118119	ptr := &Pattern{120		fuzzy:         fuzzy,121		fuzzyAlgo:     fuzzyAlgo,122		extended:      extended,123		caseSensitive: caseSensitive,124		normalize:     normalize,125		forward:       forward,126		text:          []rune(asString),127		termSets:      termSets,128		cacheable:     cacheable,129		nth:           nth,130		delimiter:     delimiter,131		procFun:       make(map[termType]algo.Algo)}132133	ptr.procFun[termFuzzy] = fuzzyAlgo134	ptr.procFun[termEqual] = algo.EqualMatch135	ptr.procFun[termExact] = algo.ExactMatchNaive136	ptr.procFun[termPrefix] = algo.PrefixMatch137	ptr.procFun[termSuffix] = algo.SuffixMatch138139	_patternCache[asString] = ptr140	return ptr141}142143func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {144	tokens := _splitRegex.Split(str, -1)145	sets := []termSet{}146	set := termSet{}147	switchSet := false148	for _, token := range tokens {149		typ, inv, text := termFuzzy, false, token150		lowerText := strings.ToLower(text)151		caseSensitive := caseMode == CaseRespect ||152			caseMode == CaseSmart && text != lowerText153		if !caseSensitive {154			text = lowerText155		}156		origText := []rune(text)157		if !fuzzy {158			typ = termExact159		}160161		if text == "|" {162			switchSet = false163			continue164		}165166		if strings.HasPrefix(text, "!") {167			inv = true168			typ = termExact169			text = text[1:]170		}171172		if strings.HasPrefix(text, "'") {173			// Flip exactness174			if fuzzy && !inv {175				typ = termExact176				text = text[1:]177			} else {178				typ = termFuzzy179				text = text[1:]180			}181		} else if strings.HasPrefix(text, "^") {182			if strings.HasSuffix(text, "$") {183				typ = termEqual184				text = text[1 : len(text)-1]185			} else {186				typ = termPrefix187				text = text[1:]188			}189		} else if strings.HasSuffix(text, "$") {190			typ = termSuffix191			text = text[:len(text)-1]192		}193194		if len(text) > 0 {195			if switchSet {196				sets = append(sets, set)197				set = termSet{}198			}199			textRunes := []rune(text)200			if normalize {201				textRunes = algo.NormalizeRunes(textRunes)202			}203			set = append(set, term{204				typ:           typ,205				inv:           inv,206				text:          textRunes,207				caseSensitive: caseSensitive,208				origText:      origText})209			switchSet = true210		}211	}212	if len(set) > 0 {213		sets = append(sets, set)214	}215	return sets216}217218// IsEmpty returns true if the pattern is effectively empty219func (p *Pattern) IsEmpty() bool {220	if !p.extended {221		return len(p.text) == 0222	}223	return len(p.termSets) == 0224}225226// AsString returns the search query in string type227func (p *Pattern) AsString() string {228	return string(p.text)229}230231// CacheKey is used to build string to be used as the key of result cache232func (p *Pattern) CacheKey() string {233	if !p.extended {234		return p.AsString()235	}236	cacheableTerms := []string{}237	for _, termSet := range p.termSets {238		if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {239			cacheableTerms = append(cacheableTerms, string(termSet[0].origText))240		}241	}242	return strings.Join(cacheableTerms, " ")243}244245// Match returns the list of matches Items in the given Chunk246func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {247	// ChunkCache: Exact match248	cacheKey := p.CacheKey()249	if p.cacheable {250		if cached, found := _cache.Find(chunk, cacheKey); found {251			return cached252		}253	}254255	// Prefix/suffix cache256	var space []*Result257Loop:258	for idx := 1; idx < len(cacheKey); idx++ {259		// [---------| ] | [ |---------]260		// [--------|  ] | [  |--------]261		// [-------|   ] | [   |-------]262		prefix := cacheKey[:len(cacheKey)-idx]263		suffix := cacheKey[idx:]264		for _, substr := range [2]*string{&prefix, &suffix} {265			if cached, found := _cache.Find(chunk, *substr); found {266				space = cached267				break Loop268			}269		}270	}271272	matches := p.matchChunk(chunk, space, slab)273274	if p.cacheable {275		_cache.Add(chunk, cacheKey, matches)276	}277	return matches278}279280func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {281	matches := []*Result{}282283	if space == nil {284		for _, item := range *chunk {285			if match, _, _ := p.MatchItem(item, false, slab); match != nil {286				matches = append(matches, match)287			}288		}289	} else {290		for _, result := range space {291			if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {292				matches = append(matches, match)293			}294		}295	}296	return matches297}298299// MatchItem returns true if the Item is a match300func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {301	if p.extended {302		if offsets, bonus, trimLen, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {303			return buildResult(item, offsets, bonus, trimLen), offsets, pos304		}305		return nil, nil, nil306	}307	offset, bonus, trimLen, pos := p.basicMatch(item, withPos, slab)308	if sidx := offset[0]; sidx >= 0 {309		offsets := []Offset{offset}310		return buildResult(item, offsets, bonus, trimLen), offsets, pos311	}312	return nil, nil, nil313}314315func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {316	input := p.prepareInput(item)317	if p.fuzzy {318		return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)319	}320	return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)321}322323func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, int, *[]int) {324	input := p.prepareInput(item)325	offsets := []Offset{}326	var totalScore int327	var totalTrimLen int328	var allPos *[]int329	if withPos {330		allPos = &[]int{}331	}332	for _, termSet := range p.termSets {333		var offset Offset334		var currentScore int335		var trimLen int336		matched := false337		for _, term := range termSet {338			pfun := p.procFun[term.typ]339			off, score, tLen, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)340			if sidx := off[0]; sidx >= 0 {341				if term.inv {342					continue343				}344				offset, currentScore, trimLen = off, score, tLen345				matched = true346				if withPos {347					if pos != nil {348						*allPos = append(*allPos, *pos...)349					} else {350						for idx := off[0]; idx < off[1]; idx++ {351							*allPos = append(*allPos, int(idx))352						}353					}354				}355				break356			} else if term.inv {357				offset, currentScore, trimLen = Offset{0, 0}, 0, 0358				matched = true359				continue360			}361		}362		if matched {363			offsets = append(offsets, offset)364			totalScore += currentScore365			totalTrimLen += trimLen366		}367	}368	return offsets, totalScore, totalTrimLen, allPos369}370371func (p *Pattern) prepareInput(item *Item) []Token {372	if item.transformed != nil {373		return item.transformed374	}375376	var ret []Token377	if len(p.nth) == 0 {378		ret = []Token{Token{text: &item.text, prefixLength: 0, trimLength: int32(item.text.TrimLength())}}379	} else {380		tokens := Tokenize(item.text, p.delimiter)381		ret = Transform(tokens, p.nth)382	}383	item.transformed = ret384	return ret385}386387func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {388	for _, part := range tokens {389		if res, pos := pfun(caseSensitive, normalize, forward, *part.text, pattern, withPos, slab); res.Start >= 0 {390			sidx := int32(res.Start) + part.prefixLength391			eidx := int32(res.End) + part.prefixLength392			if pos != nil {393				for idx := range *pos {394					(*pos)[idx] += int(part.prefixLength)395				}396			}397			return Offset{sidx, eidx}, res.Score, int(part.trimLength), pos398		}399	}400	return Offset{-1, -1}, 0, -1, nil401}