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
The walk stopped after 200 commits: lines older than de1c6b8 point at it.
[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 1–12why, one step back1package fzf23import (4 "regexp"5 "strings"67 "github.com/junegunn/fzf/src/algo"8 "github.com/junegunn/fzf/src/util"9)1011// fuzzy12// 'exactFix invalid cache lookupsJunegunn Choibefore adoption999d374
lines 13–18why, one step back13// ^prefix-exact14// suffix-exact$15// !inverse-exact16// !'inverse-fuzzy17// !^inverse-prefix-exact18// !inverse-suffix-exact$[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 19–44why, one step back1920type 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 boolMerge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 45why, one step back45 normalize bool[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 46–49why, one step back46 forward bool47 text []rune48 termSets []termSet49 cacheable boolBuild cache key for a pattern only onceJunegunn Choibefore adoptione55e029
line 50why, one step back50 cacheKey string[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 51–56why, one step back51 delimiter Delimiter52 nth []Range53 procFun map[termType]algo.Algo54}5556var (Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c
lines 57–59why, one step back57 _patternCache map[string]*Pattern58 _splitRegex *regexp.Regexp59 _cache ChunkCache[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 60–62why, one step back60)6162func init() {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 63why, one step back63 _splitRegex = regexp.MustCompile(" +")[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 64–78why, one step back64 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 argumentsMerge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 79why, one step back79func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 80–83why, one step back80 cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8182 var asString string83 if extended {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
lines 84–87why, one step back84 asString = strings.TrimLeft(string(runes), " ")85 for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {86 asString = asString[:len(asString)-1]87 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 88–100why, one step back88 } 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 {Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 101why, one step back101 termSets = parseTerms(fuzzy, caseMode, normalize, asString)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 102–106why, one step back102 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 scopeFix invalid cache lookupsJunegunn Choibefore adoption999d374
line 107why, one step back107 if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 108–126why, one step back108 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,Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 127why, one step back127 normalize: normalize,[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 128–135why, one step back128 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)}135Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029
line 136why, one step back136 ptr.cacheKey = ptr.buildCacheKey()[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 137–146why, one step back137 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}146Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 147why, one step back147func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 148why, one step back148 str = strings.Replace(str, "\\ ", "\t", -1)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 149–152why, one step back149 tokens := _splitRegex.Split(str, -1)150 sets := []termSet{}151 set := termSet{}152 switchSet := falseTreat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 153why, one step back153 afterBar := false[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 154why, one step back154 for _, token := range tokens {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 155why, one step back155 typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 156–165why, one step back156 lowerText := strings.ToLower(text)157 caseSensitive := caseMode == CaseRespect ||158 caseMode == CaseSmart && text != lowerText159 if !caseSensitive {160 text = lowerText161 }162 if !fuzzy {163 typ = termExact164 }165Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 166why, one step back166 if len(set) > 0 && !afterBar && text == "|" {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 167why, one step back167 switchSet = falseTreat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 168why, one step back168 afterBar = true[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 169–170why, one step back169 continue170 }Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 171why, one step back171 afterBar = false[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 172–178why, one step back172173 if strings.HasPrefix(text, "!") {174 inv = true175 typ = termExact176 text = text[1:]177 }178Treat $ as proper search queryJunegunn Choibefore adoption02a7b96
line 179why, one step back179 if text != "$" && strings.HasSuffix(text, "$") {Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c
lines 180–181why, one step back180 typ = termSuffix181 text = text[:len(text)-1]Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
lines 182–183why, one step back182 }183Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c
line 184why, one step back184 if strings.HasPrefix(text, "'") {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 185–193why, one step back185 // 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, "^") {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 194why, one step back194 if typ == termSuffix {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 195–198why, one step back195 typ = termEqual196 } else {197 typ = termPrefix198 }Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
lines 199–201why, one step back199 text = text[1:]200 }201[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 202–206why, one step back202 if len(text) > 0 {203 if switchSet {204 sets = append(sets, set)205 set = termSet{}206 }Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
lines 207–210why, one step back207 textRunes := []rune(text)208 if normalize {209 textRunes = algo.NormalizeRunes(textRunes)210 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 211–213why, one step back211 set = append(set, term{212 typ: typ,213 inv: inv,Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 214why, one step back214 text: textRunes,Fix invalid cache lookupsJunegunn Choibefore adoption999d374
line 215why, one step back215 caseSensitive: caseSensitive})[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 216–237why, one step back216 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}237Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029
line 238why, one step back238func (p *Pattern) buildCacheKey() string {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 239–244why, one step back239 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) {Fix invalid cache lookupsJunegunn Choibefore adoption999d374
line 245why, one step back245 cacheableTerms = append(cacheableTerms, string(termSet[0].text))[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 246–247why, one step back246 }247 }Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 248why, one step back248 return strings.Join(cacheableTerms, "\t")Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029
lines 249–253why, one step back249}250251// CacheKey is used to build string to be used as the key of result cache252func (p *Pattern) CacheKey() string {253 return p.cacheKey[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 254–256why, one step back254}255256// Match returns the list of matches Items in the given ChunkConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 257why, one step back257func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 258–260why, one step back258 // ChunkCache: Exact match259 cacheKey := p.CacheKey()260 if p.cacheable {Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
line 261why, one step back261 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 262–266why, one step back262 return cached263 }264 }265266 // Prefix/suffix cacheRefactor cache lookupJunegunn Choibefore adoption8dbdd55
line 267why, one step back267 space := _cache.Search(chunk, cacheKey)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 268–276why, one step back268269 matches := p.matchChunk(chunk, space, slab)270271 if p.cacheable {272 _cache.Add(chunk, cacheKey, matches)273 }274 return matches275}276Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 277–278why, one step back277func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {278 matches := []Result{}[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 279–280why, one step back279280 if space == nil {Remove special nilItemJunegunn Choibefore adoption0d171ba
lines 281–282why, one step back281 for idx := 0; idx < chunk.count; idx++ {282 if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 283why, one step back283 matches = append(matches, *match)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 284–288why, one step back284 }285 }286 } else {287 for _, result := range space {288 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 289why, one step back289 matches = append(matches, *match)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 290–298why, one step back290 }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 {Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 299why, one step back299 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 300–301why, one step back300 result := buildResult(item, offsets, bonus)301 return &result, offsets, pos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 302–304why, one step back302 }303 return nil, nil, nil304 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 305why, one step back305 offset, bonus, pos := p.basicMatch(item, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 306–307why, one step back306 if sidx := offset[0]; sidx >= 0 {307 offsets := []Offset{offset}Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 308–309why, one step back308 result := buildResult(item, offsets, bonus)309 return &result, offsets, pos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 310–313why, one step back310 }311 return nil, nil, nil312}313Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 314why, one step back314func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
lines 315–320why, one step back315 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 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 321why, one step back321 if p.fuzzy {Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 322why, one step back322 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 323why, one step back323 }Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 324why, one step back324 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 325–326why, one step back325}326Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 327why, one step back327func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
lines 328–333why, one step back328 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 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 334–345why, one step back334 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]Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 346why, one step back346 off, score, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 347–350why, one step back347 if sidx := off[0]; sidx >= 0 {348 if term.inv {349 continue350 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 351why, one step back351 offset, currentScore = off, score[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 352–363why, one step back352 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 {Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 364why, one step back364 offset, currentScore = Offset{0, 0}, 0[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 365–373why, one step back365 matched = true366 continue367 }368 }369 if matched {370 offsets = append(offsets, offset)371 totalScore += currentScore372 }373 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 374why, one step back374 return offsets, totalScore, allPos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 375–376why, one step back375}376Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
line 377why, one step back377func (p *Pattern) transformInput(item *Item) []Token {Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
lines 378–379why, one step back378 if item.transformed != nil {379 return *item.transformed[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 380why, one step back380 }Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
line 381why, one step back381Avoid unconditionally storsing input as runesJunegunn Choibefore adoptionc9f16b6
line 382why, one step back382 tokens := Tokenize(item.text.ToString(), p.delimiter)Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
lines 383–384why, one step back383 ret := Transform(tokens, p.nth)384 item.transformed = &ret[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 385–387why, one step back385 return ret386}387Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 388why, one step back388func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 389why, one step back389 for _, part := range tokens {Pass util.Chars by pointerJunegunn Choibefore adoptiona2a4df0
line 390why, one step back390 if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 391–397why, one step back391 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 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 398why, one step back398 return Offset{sidx, eidx}, res.Score, pos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 399–400why, one step back399 }400 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 401why, one step back401 return Offset{-1, -1}, 0, nil[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 402why, one step back402}