pattern.go
This file
Path
src/pattern.go
335 lines · 7.5 KiB · Go
Last changed by
Allow ^EqualMatch$Junegunn Choibefore adoption0be4cea
History of this fileTake it
The walk stopped after 200 commits: lines older than 423317b point at it.
Update README.mdJunegunn Choibefore adoption423317b
lines 1–26why, one step back1package fzf23import (4 "regexp"5 "sort"6 "strings"78 "github.com/junegunn/fzf/src/algo"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 termSuffixAllow ^EqualMatch$Junegunn Choibefore adoption0be4cea
line 27why, one step back27 termEqualUpdate README.mdJunegunn Choibefore adoption423317b
lines 28–30why, one step back28)2930type term struct {Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
lines 31–35why, one step back31 typ termType32 inv bool33 text []rune34 caseSensitive bool35 origText []runeUpdate README.mdJunegunn Choibefore adoption423317b
lines 36–46why, one step back36}3738// Pattern represents search pattern39type Pattern struct {40 mode Mode41 caseSensitive bool42 text []rune43 terms []term44 hasInvTerm bool45 delimiter *regexp.Regexp46 nth []RangeImprovements in performance and memory usageJunegunn Choibefore adoption2fe1e28
line 47why, one step back47 procFun map[termType]func(bool, *[]rune, []rune) (int, int)Update README.mdJunegunn Choibefore adoption423317b
lines 48–57why, one step back48}4950var (51 _patternCache map[string]*Pattern52 _splitRegex *regexp.Regexp53 _cache ChunkCache54)5556func init() {57 _splitRegex = regexp.MustCompile("\\s+")Implement --toggle-sort option (#173)Junegunn Choibefore adoption50292ad
lines 58–59why, one step back58 clearPatternCache()59 clearChunkCache()Update README.mdJunegunn Choibefore adoption423317b
lines 60–62why, one step back60}6162func clearPatternCache() {Implement --toggle-sort option (#173)Junegunn Choibefore adoption50292ad
lines 63–64why, one step back63 // We can uniquely identify the pattern for a given string since64 // mode and caseMode do not change while the program is runningUpdate README.mdJunegunn Choibefore adoption423317b
line 65why, one step back65 _patternCache = make(map[string]*Pattern)Implement --toggle-sort option (#173)Junegunn Choibefore adoption50292ad
lines 66–69why, one step back66}6768func clearChunkCache() {69 _cache = NewChunkCache()Update README.mdJunegunn Choibefore adoption423317b
lines 70–93why, one step back70}7172// BuildPattern builds Pattern object from the given arguments73func BuildPattern(mode Mode, caseMode Case,74 nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {7576 var asString string77 switch mode {78 case ModeExtended, ModeExtendedExact:79 asString = strings.Trim(string(runes), " ")80 default:81 asString = string(runes)82 }8384 cached, found := _patternCache[asString]85 if found {86 return cached87 }8889 caseSensitive, hasInvTerm := true, false90 terms := []term{}9192 switch mode {93 case ModeExtended, ModeExtendedExact:Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 94why, one step back94 terms = parseTerms(mode, caseMode, asString)Update README.mdJunegunn Choibefore adoption423317b
lines 95–99why, one step back95 for _, term := range terms {96 if term.inv {97 hasInvTerm = true98 }99 }Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
lines 100–106why, one step back100 default:101 lowerString := strings.ToLower(asString)102 caseSensitive = caseMode == CaseRespect ||103 caseMode == CaseSmart && lowerString != asString104 if !caseSensitive {105 asString = lowerString106 }Update README.mdJunegunn Choibefore adoption423317b
lines 107–111why, one step back107 }108109 ptr := &Pattern{110 mode: mode,111 caseSensitive: caseSensitive,Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 112why, one step back112 text: []rune(asString),Update README.mdJunegunn Choibefore adoption423317b
lines 113–116why, one step back113 terms: terms,114 hasInvTerm: hasInvTerm,115 nth: nth,116 delimiter: delimiter,Improvements in performance and memory usageJunegunn Choibefore adoption2fe1e28
line 117why, one step back117 procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}Update README.mdJunegunn Choibefore adoption423317b
lines 118–119why, one step back118119 ptr.procFun[termFuzzy] = algo.FuzzyMatchAllow ^EqualMatch$Junegunn Choibefore adoption0be4cea
line 120why, one step back120 ptr.procFun[termEqual] = algo.EqualMatchUpdate README.mdJunegunn Choibefore adoption423317b
lines 121–128why, one step back121 ptr.procFun[termExact] = algo.ExactMatchNaive122 ptr.procFun[termPrefix] = algo.PrefixMatch123 ptr.procFun[termSuffix] = algo.SuffixMatch124125 _patternCache[asString] = ptr126 return ptr127}128Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 129why, one step back129func parseTerms(mode Mode, caseMode Case, str string) []term {Update README.mdJunegunn Choibefore adoption423317b
lines 130–133why, one step back130 tokens := _splitRegex.Split(str, -1)131 terms := []term{}132 for _, token := range tokens {133 typ, inv, text := termFuzzy, false, tokenSmart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
lines 134–139why, one step back134 lowerText := strings.ToLower(text)135 caseSensitive := caseMode == CaseRespect ||136 caseMode == CaseSmart && text != lowerText137 if !caseSensitive {138 text = lowerText139 }Update README.mdJunegunn Choibefore adoption423317b
lines 140–155why, one step back140 origText := []rune(text)141 if mode == ModeExtendedExact {142 typ = termExact143 }144145 if strings.HasPrefix(text, "!") {146 inv = true147 text = text[1:]148 }149150 if strings.HasPrefix(text, "'") {151 if mode == ModeExtended {152 typ = termExact153 text = text[1:]154 }155 } else if strings.HasPrefix(text, "^") {Allow ^EqualMatch$Junegunn Choibefore adoption0be4cea
lines 156–162why, one step back156 if strings.HasSuffix(text, "$") {157 typ = termEqual158 text = text[1 : len(text)-1]159 } else {160 typ = termPrefix161 text = text[1:]162 }Update README.mdJunegunn Choibefore adoption423317b
lines 163–169why, one step back163 } else if strings.HasSuffix(text, "$") {164 typ = termSuffix165 text = text[:len(text)-1]166 }167168 if len(text) > 0 {169 terms = append(terms, term{Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
lines 170–174why, one step back170 typ: typ,171 inv: inv,172 text: []rune(text),173 caseSensitive: caseSensitive,174 origText: origText})Update README.mdJunegunn Choibefore adoption423317b
lines 175–236why, one step back175 }176 }177 return terms178}179180// IsEmpty returns true if the pattern is effectively empty181func (p *Pattern) IsEmpty() bool {182 if p.mode == ModeFuzzy {183 return len(p.text) == 0184 }185 return len(p.terms) == 0186}187188// AsString returns the search query in string type189func (p *Pattern) AsString() string {190 return string(p.text)191}192193// CacheKey is used to build string to be used as the key of result cache194func (p *Pattern) CacheKey() string {195 if p.mode == ModeFuzzy {196 return p.AsString()197 }198 cacheableTerms := []string{}199 for _, term := range p.terms {200 if term.inv {201 continue202 }203 cacheableTerms = append(cacheableTerms, string(term.origText))204 }205 return strings.Join(cacheableTerms, " ")206}207208// Match returns the list of matches Items in the given Chunk209func (p *Pattern) Match(chunk *Chunk) []*Item {210 space := chunk211212 // ChunkCache: Exact match213 cacheKey := p.CacheKey()214 if !p.hasInvTerm { // Because we're excluding Inv-term from cache key215 if cached, found := _cache.Find(chunk, cacheKey); found {216 return cached217 }218 }219220 // ChunkCache: Prefix/suffix match221Loop:222 for idx := 1; idx < len(cacheKey); idx++ {223 // [---------| ] | [ |---------]224 // [--------| ] | [ |--------]225 // [-------| ] | [ |-------]226 prefix := cacheKey[:len(cacheKey)-idx]227 suffix := cacheKey[idx:]228 for _, substr := range [2]*string{&prefix, &suffix} {229 if cached, found := _cache.Find(chunk, *substr); found {230 cachedChunk := Chunk(cached)231 space = &cachedChunk232 break Loop233 }234 }235 }236Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
line 237why, one step back237 matches := p.matchChunk(space)Update README.mdJunegunn Choibefore adoption423317b
lines 238–244why, one step back238239 if !p.hasInvTerm {240 _cache.Add(chunk, cacheKey, matches)241 }242 return matches243}244Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
lines 245–273why, one step back245func (p *Pattern) matchChunk(chunk *Chunk) []*Item {246 matches := []*Item{}247 if p.mode == ModeFuzzy {248 for _, item := range *chunk {249 if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {250 matches = append(matches,251 dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))252 }253 }254 } else {255 for _, item := range *chunk {256 if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {257 matches = append(matches, dupItem(item, offsets))258 }259 }260 }261 return matches262}263264// MatchItem returns true if the Item is a match265func (p *Pattern) MatchItem(item *Item) bool {266 if p.mode == ModeFuzzy {267 sidx, _ := p.fuzzyMatch(item)268 return sidx >= 0269 }270 offsets := p.extendedMatch(item)271 return len(offsets) == len(p.terms)272}273Update README.mdJunegunn Choibefore adoption423317b
lines 274–281why, one step back274func dupItem(item *Item, offsets []Offset) *Item {275 sort.Sort(ByOrder(offsets))276 return &Item{277 text: item.text,278 origText: item.origText,279 transformed: item.transformed,280 index: item.index,281 offsets: offsets,Add support for ANSI color codesJunegunn Choibefore adoptione70a2a5
line 282why, one step back282 colors: item.colors,Update README.mdJunegunn Choibefore adoption423317b
lines 283–285why, one step back283 rank: Rank{0, 0, item.index}}284}285Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
lines 286–287why, one step back286func (p *Pattern) fuzzyMatch(item *Item) (int, int) {287 input := p.prepareInput(item)Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 288why, one step back288 return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)Update README.mdJunegunn Choibefore adoption423317b
lines 289–290why, one step back289}290Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
lines 291–295why, one step back291func (p *Pattern) extendedMatch(item *Item) []Offset {292 input := p.prepareInput(item)293 offsets := []Offset{}294 for _, term := range p.terms {295 pfun := p.procFun[term.typ]Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 296why, one step back296 if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
lines 297–298why, one step back297 if term.inv {298 breakUpdate README.mdJunegunn Choibefore adoption423317b
line 299why, one step back299 }Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
lines 300–302why, one step back300 offsets = append(offsets, Offset{int32(sidx), int32(eidx)})301 } else if term.inv {302 offsets = append(offsets, Offset{0, 0})Update README.mdJunegunn Choibefore adoption423317b
lines 303–304why, one step back303 }304 }Merge pull request #134 from junegunn/develJunegunn Choibefore adoptiond4b41c5
line 305why, one step back305 return offsetsUpdate README.mdJunegunn Choibefore adoption423317b
lines 306–307why, one step back306}307Improvements in performance and memory usageJunegunn Choibefore adoption2fe1e28
line 308why, one step back308func (p *Pattern) prepareInput(item *Item) *[]Token {Update README.mdJunegunn Choibefore adoption423317b
lines 309–312why, one step back309 if item.transformed != nil {310 return item.transformed311 }312Improvements in performance and memory usageJunegunn Choibefore adoption2fe1e28
line 313why, one step back313 var ret *[]TokenUpdate README.mdJunegunn Choibefore adoption423317b
lines 314–317why, one step back314 if len(p.nth) > 0 {315 tokens := Tokenize(item.text, p.delimiter)316 ret = Transform(tokens, p.nth)317 } else {Improvements in performance and memory usageJunegunn Choibefore adoption2fe1e28
lines 318–319why, one step back318 runes := []rune(*item.text)319 trans := []Token{Token{text: &runes, prefixLength: 0}}Update README.mdJunegunn Choibefore adoption423317b
lines 320–325why, one step back320 ret = &trans321 }322 item.transformed = ret323 return ret324}325Improvements in performance and memory usageJunegunn Choibefore adoption2fe1e28
line 326why, one step back326func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),Smart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 327why, one step back327 tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {Improvements in performance and memory usageJunegunn Choibefore adoption2fe1e28
line 328why, one step back328 for _, part := range *tokens {Update README.mdJunegunn Choibefore adoption423317b
line 329why, one step back329 prefixLength := part.prefixLengthSmart-case for each term in extended-search modeJunegunn Choibefore adoptione82eb27
line 330why, one step back330 if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {Update README.mdJunegunn Choibefore adoption423317b
lines 331–335why, one step back331 return sidx + prefixLength, eidx + prefixLength332 }333 }334 return -1, -1335}