Skip to content
Myr

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 file

Take 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 back
1package fzf
23import (4 "regexp"5 "strings"67 "github.com/junegunn/fzf/src/algo"8 "github.com/junegunn/fzf/src/util"9)1011// fuzzy12// 'exact

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

lines 13–18why, one step back
13// ^prefix-exact
14// 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 back
19
20type 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 bool

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 45why, one step back
45 normalize bool

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 46–49why, one step back
46 forward bool
47 text []rune48 termSets []termSet49 cacheable bool

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

line 50why, one step back
50 cacheKey string

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 51–56why, one step back
51 delimiter Delimiter
52 nth []Range53 procFun map[termType]algo.Algo54}5556var (

Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c

lines 57–59why, one step back
57 _patternCache map[string]*Pattern
58 _splitRegex *regexp.Regexp59 _cache ChunkCache

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 60–62why, one step back
60)
6162func init() {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 63why, one step back
63 _splitRegex = regexp.MustCompile(" +")

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 64–78why, one step back
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 arguments

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 79why, one step back
79func 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 back
80 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 back
84 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 back
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 {

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 101why, one step back
101 termSets = parseTerms(fuzzy, caseMode, normalize, asString)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 102–106why, one step back
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 scope

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

line 107why, one step back
107 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 back
108 cacheable = false
109 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 back
127 normalize: normalize,

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 128–135why, one step back
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)}135

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

line 136why, one step back
136 ptr.cacheKey = ptr.buildCacheKey()

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 137–146why, one step back
137 ptr.procFun[termFuzzy] = fuzzyAlgo
138 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}146

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 147why, one step back
147func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 148why, one step back
148 str = strings.Replace(str, "\\ ", "\t", -1)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 149–152why, one step back
149 tokens := _splitRegex.Split(str, -1)
150 sets := []termSet{}151 set := termSet{}152 switchSet := false

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 153why, one step back
153 afterBar := false

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

line 154why, one step back
154 for _, token := range tokens {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 155why, one step back
155 typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 156–165why, one step back
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 }165

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 166why, one step back
166 if len(set) > 0 && !afterBar && text == "|" {

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

line 167why, one step back
167 switchSet = false

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 168why, one step back
168 afterBar = true

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 169–170why, one step back
169 continue
170 }

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 171why, one step back
171 afterBar = false

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 172–178why, one step back
172
173 if strings.HasPrefix(text, "!") {174 inv = true175 typ = termExact176 text = text[1:]177 }178

Treat $ as proper search queryJunegunn Choibefore adoption02a7b96

line 179why, one step back
179 if text != "$" && strings.HasSuffix(text, "$") {

Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c

lines 180–181why, one step back
180 typ = termSuffix
181 text = text[:len(text)-1]

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

lines 182–183why, one step back
182 }
183

Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c

line 184why, one step back
184 if strings.HasPrefix(text, "'") {

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 185–193why, one step back
185 // Flip exactness
186 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 back
194 if typ == termSuffix {

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 195–198why, one step back
195 typ = termEqual
196 } else {197 typ = termPrefix198 }

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

lines 199–201why, one step back
199 text = text[1:]
200 }201

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 202–206why, one step back
202 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 back
207 textRunes := []rune(text)
208 if normalize {209 textRunes = algo.NormalizeRunes(textRunes)210 }

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 211–213why, one step back
211 set = append(set, term{
212 typ: typ,213 inv: inv,

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 214why, one step back
214 text: textRunes,

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

line 215why, one step back
215 caseSensitive: caseSensitive})

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 216–237why, one step back
216 switchSet = true
217 }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}237

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

line 238why, one step back
238func (p *Pattern) buildCacheKey() string {

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 239–244why, one step back
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) {

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

line 245why, one step back
245 cacheableTerms = append(cacheableTerms, string(termSet[0].text))

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 246–247why, one step back
246 }
247 }

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 248why, one step back
248 return strings.Join(cacheableTerms, "\t")

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

lines 249–253why, one step back
249}
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 back
254}
255256// Match returns the list of matches Items in the given Chunk

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

line 257why, one step back
257func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 258–260why, one step back
258 // ChunkCache: Exact match
259 cacheKey := p.CacheKey()260 if p.cacheable {

Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba

line 261why, one step back
261 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 262–266why, one step back
262 return cached
263 }264 }265266 // Prefix/suffix cache

Refactor cache lookupJunegunn Choibefore adoption8dbdd55

line 267why, one step back
267 space := _cache.Search(chunk, cacheKey)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 268–276why, one step back
268
269 matches := p.matchChunk(chunk, space, slab)270271 if p.cacheable {272 _cache.Add(chunk, cacheKey, matches)273 }274 return matches275}276

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 277–278why, one step back
277func (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 back
279
280 if space == nil {

Remove special nilItemJunegunn Choibefore adoption0d171ba

lines 281–282why, one step back
281 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 back
283 matches = append(matches, *match)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 284–288why, one step back
284 }
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 back
289 matches = append(matches, *match)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 290–298why, one step back
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 {

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 299why, one step back
299 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 back
300 result := buildResult(item, offsets, bonus)
301 return &result, offsets, pos

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 302–304why, one step back
302 }
303 return nil, nil, nil304 }

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 305why, one step back
305 offset, bonus, pos := p.basicMatch(item, withPos, slab)

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 306–307why, one step back
306 if sidx := offset[0]; sidx >= 0 {
307 offsets := []Offset{offset}

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 308–309why, one step back
308 result := buildResult(item, offsets, bonus)
309 return &result, offsets, pos

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 310–313why, one step back
310 }
311 return nil, nil, nil312}313

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 314why, one step back
314func (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 back
315 var input []Token
316 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 back
321 if p.fuzzy {

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 322why, one step back
322 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 back
323 }

Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a

line 324why, one step back
324 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 back
325}
326

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 327why, one step back
327func (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 back
328 var input []Token
329 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 back
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]

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 346why, one step back
346 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 back
347 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 back
351 offset, currentScore = off, score

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 352–363why, one step back
352 matched = true
353 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 back
364 offset, currentScore = Offset{0, 0}, 0

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 365–373why, one step back
365 matched = true
366 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 back
374 return offsets, totalScore, allPos

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 375–376why, one step back
375}
376

Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa

line 377why, one step back
377func (p *Pattern) transformInput(item *Item) []Token {

Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba

lines 378–379why, one step back
378 if item.transformed != nil {
379 return *item.transformed

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

line 380why, one step back
380 }

Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba

line 381why, one step back
381

Avoid unconditionally storsing input as runesJunegunn Choibefore adoptionc9f16b6

line 382why, one step back
382 tokens := Tokenize(item.text.ToString(), p.delimiter)

Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba

lines 383–384why, one step back
383 ret := Transform(tokens, p.nth)
384 item.transformed = &ret

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 385–387why, one step back
385 return ret
386}387

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 388why, one step back
388func (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 back
389 for _, part := range tokens {

Pass util.Chars by pointerJunegunn Choibefore adoptiona2a4df0

line 390why, one step back
390 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 back
391 sidx := int32(res.Start) + part.prefixLength
392 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 back
398 return Offset{sidx, eidx}, res.Score, pos

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

lines 399–400why, one step back
399 }
400 }

Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75

line 401why, one step back
401 return Offset{-1, -1}, 0, nil

[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8

line 402why, one step back
402}