pattern.go
This file
Path
src/pattern.go
402 lines · 9.5 KiB · Go
Last changed by
Pass util.Chars by pointerJunegunn Choibefore adoptiona2a4df0
History of this fileTake 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// ^prefix-exact14// suffix-exact$15// !inverse-exact16// !'inverse-fuzzy17// !^inverse-prefix-exact18// !inverse-suffix-exact$1920type termType int2122const (23 termFuzzy termType = iota24 termExact25 termPrefix26 termSuffix27 termEqual28)2930type term struct {31 typ termType32 inv bool33 text []rune34 caseSensitive bool35}3637type termSet []term3839// Pattern represents search pattern40type Pattern struct {41 fuzzy bool42 fuzzyAlgo algo.Algo43 extended bool44 caseSensitive bool45 normalize bool46 forward bool47 text []rune48 termSets []termSet49 cacheable bool50 cacheKey string51 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(" +")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.TrimLeft(string(runes), " ")85 for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {86 asString = asString[:len(asString)-1]87 }88 } else {89 asString = string(runes)90 }9192 cached, found := _patternCache[asString]93 if found {94 return cached95 }9697 caseSensitive := true98 termSets := []termSet{}99100 if extended {101 termSets = parseTerms(fuzzy, caseMode, normalize, asString)102 Loop:103 for _, termSet := range termSets {104 for idx, term := range termSet {105 // If the query contains inverse search terms or OR operators,106 // we cannot cache the search scope107 if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {108 cacheable = false109 break Loop110 }111 }112 }113 } else {114 lowerString := strings.ToLower(asString)115 caseSensitive = caseMode == CaseRespect ||116 caseMode == CaseSmart && lowerString != asString117 if !caseSensitive {118 asString = lowerString119 }120 }121122 ptr := &Pattern{123 fuzzy: fuzzy,124 fuzzyAlgo: fuzzyAlgo,125 extended: extended,126 caseSensitive: caseSensitive,127 normalize: normalize,128 forward: forward,129 text: []rune(asString),130 termSets: termSets,131 cacheable: cacheable,132 nth: nth,133 delimiter: delimiter,134 procFun: make(map[termType]algo.Algo)}135136 ptr.cacheKey = ptr.buildCacheKey()137 ptr.procFun[termFuzzy] = fuzzyAlgo138 ptr.procFun[termEqual] = algo.EqualMatch139 ptr.procFun[termExact] = algo.ExactMatchNaive140 ptr.procFun[termPrefix] = algo.PrefixMatch141 ptr.procFun[termSuffix] = algo.SuffixMatch142143 _patternCache[asString] = ptr144 return ptr145}146147func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {148 str = strings.Replace(str, "\\ ", "\t", -1)149 tokens := _splitRegex.Split(str, -1)150 sets := []termSet{}151 set := termSet{}152 switchSet := false153 afterBar := false154 for _, token := range tokens {155 typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)156 lowerText := strings.ToLower(text)157 caseSensitive := caseMode == CaseRespect ||158 caseMode == CaseSmart && text != lowerText159 if !caseSensitive {160 text = lowerText161 }162 if !fuzzy {163 typ = termExact164 }165166 if len(set) > 0 && !afterBar && text == "|" {167 switchSet = false168 afterBar = true169 continue170 }171 afterBar = false172173 if strings.HasPrefix(text, "!") {174 inv = true175 typ = termExact176 text = text[1:]177 }178179 if text != "$" && strings.HasSuffix(text, "$") {180 typ = termSuffix181 text = text[:len(text)-1]182 }183184 if strings.HasPrefix(text, "'") {185 // Flip exactness186 if fuzzy && !inv {187 typ = termExact188 text = text[1:]189 } else {190 typ = termFuzzy191 text = text[1:]192 }193 } else if strings.HasPrefix(text, "^") {194 if typ == termSuffix {195 typ = termEqual196 } else {197 typ = termPrefix198 }199 text = text[1:]200 }201202 if len(text) > 0 {203 if switchSet {204 sets = append(sets, set)205 set = termSet{}206 }207 textRunes := []rune(text)208 if normalize {209 textRunes = algo.NormalizeRunes(textRunes)210 }211 set = append(set, term{212 typ: typ,213 inv: inv,214 text: textRunes,215 caseSensitive: caseSensitive})216 switchSet = true217 }218 }219 if len(set) > 0 {220 sets = append(sets, set)221 }222 return sets223}224225// IsEmpty returns true if the pattern is effectively empty226func (p *Pattern) IsEmpty() bool {227 if !p.extended {228 return len(p.text) == 0229 }230 return len(p.termSets) == 0231}232233// AsString returns the search query in string type234func (p *Pattern) AsString() string {235 return string(p.text)236}237238func (p *Pattern) buildCacheKey() string {239 if !p.extended {240 return p.AsString()241 }242 cacheableTerms := []string{}243 for _, termSet := range p.termSets {244 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {245 cacheableTerms = append(cacheableTerms, string(termSet[0].text))246 }247 }248 return strings.Join(cacheableTerms, "\t")249}250251// CacheKey is used to build string to be used as the key of result cache252func (p *Pattern) CacheKey() string {253 return p.cacheKey254}255256// Match returns the list of matches Items in the given Chunk257func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {258 // ChunkCache: Exact match259 cacheKey := p.CacheKey()260 if p.cacheable {261 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {262 return cached263 }264 }265266 // Prefix/suffix cache267 space := _cache.Search(chunk, cacheKey)268269 matches := p.matchChunk(chunk, space, slab)270271 if p.cacheable {272 _cache.Add(chunk, cacheKey, matches)273 }274 return matches275}276277func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {278 matches := []Result{}279280 if space == nil {281 for idx := 0; idx < chunk.count; idx++ {282 if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {283 matches = append(matches, *match)284 }285 }286 } else {287 for _, result := range space {288 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {289 matches = append(matches, *match)290 }291 }292 }293 return matches294}295296// MatchItem returns true if the Item is a match297func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {298 if p.extended {299 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {300 result := buildResult(item, offsets, bonus)301 return &result, offsets, pos302 }303 return nil, nil, nil304 }305 offset, bonus, pos := p.basicMatch(item, withPos, slab)306 if sidx := offset[0]; sidx >= 0 {307 offsets := []Offset{offset}308 result := buildResult(item, offsets, bonus)309 return &result, offsets, pos310 }311 return nil, nil, nil312}313314func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {315 var input []Token316 if len(p.nth) == 0 {317 input = []Token{Token{text: &item.text, prefixLength: 0}}318 } else {319 input = p.transformInput(item)320 }321 if p.fuzzy {322 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)323 }324 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)325}326327func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {328 var input []Token329 if len(p.nth) == 0 {330 input = []Token{Token{text: &item.text, prefixLength: 0}}331 } else {332 input = p.transformInput(item)333 }334 offsets := []Offset{}335 var totalScore int336 var allPos *[]int337 if withPos {338 allPos = &[]int{}339 }340 for _, termSet := range p.termSets {341 var offset Offset342 var currentScore int343 matched := false344 for _, term := range termSet {345 pfun := p.procFun[term.typ]346 off, score, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)347 if sidx := off[0]; sidx >= 0 {348 if term.inv {349 continue350 }351 offset, currentScore = off, score352 matched = true353 if withPos {354 if pos != nil {355 *allPos = append(*allPos, *pos...)356 } else {357 for idx := off[0]; idx < off[1]; idx++ {358 *allPos = append(*allPos, int(idx))359 }360 }361 }362 break363 } else if term.inv {364 offset, currentScore = Offset{0, 0}, 0365 matched = true366 continue367 }368 }369 if matched {370 offsets = append(offsets, offset)371 totalScore += currentScore372 }373 }374 return offsets, totalScore, allPos375}376377func (p *Pattern) transformInput(item *Item) []Token {378 if item.transformed != nil {379 return *item.transformed380 }381382 tokens := Tokenize(item.text.ToString(), p.delimiter)383 ret := Transform(tokens, p.nth)384 item.transformed = &ret385 return ret386}387388func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {389 for _, part := range tokens {390 if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {391 sidx := int32(res.Start) + part.prefixLength392 eidx := int32(res.End) + part.prefixLength393 if pos != nil {394 for idx := range *pos {395 (*pos)[idx] += int(part.prefixLength)396 }397 }398 return Offset{sidx, eidx}, res.Score, pos399 }400 }401 return Offset{-1, -1}, 0, nil402}