pattern.go
This file
Path
src/pattern.go
414 lines · 10.2 KiB · Go
Last changed by
chore: use strings.ReplaceAll (#3801)Zhizhen Hebefore adoption01e7668
History of this fileTake it
1package fzf23import (4 "fmt"5 "regexp"6 "strings"78 "github.com/junegunn/fzf/src/algo"9 "github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact14// ^prefix-exact15// suffix-exact$16// !inverse-exact17// !'inverse-fuzzy18// !^inverse-prefix-exact19// !inverse-suffix-exact$2021type termType int2223const (24 termFuzzy termType = iota25 termExact26 termPrefix27 termSuffix28 termEqual29)3031type term struct {32 typ termType33 inv bool34 text []rune35 caseSensitive bool36 normalize bool37}3839// String returns the string representation of a term.40func (t term) String() string {41 return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)42}4344type termSet []term4546// Pattern represents search pattern47type Pattern struct {48 fuzzy bool49 fuzzyAlgo algo.Algo50 extended bool51 caseSensitive bool52 normalize bool53 forward bool54 withPos bool55 text []rune56 termSets []termSet57 sortable bool58 cacheable bool59 cacheKey string60 delimiter Delimiter61 nth []Range62 procFun map[termType]algo.Algo63 cache *ChunkCache64}6566var _splitRegex *regexp.Regexp6768func init() {69 _splitRegex = regexp.MustCompile(" +")70}7172// BuildPattern builds Pattern object from the given arguments73func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,74 withPos bool, cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {7576 var asString string77 if extended {78 asString = strings.TrimLeft(string(runes), " ")79 for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {80 asString = asString[:len(asString)-1]81 }82 } else {83 asString = string(runes)84 }8586 // We can uniquely identify the pattern for a given string since87 // search mode and caseMode do not change while the program is running88 cached, found := patternCache[asString]89 if found {90 return cached91 }9293 caseSensitive := true94 sortable := true95 termSets := []termSet{}9697 if extended {98 termSets = parseTerms(fuzzy, caseMode, normalize, asString)99 // We should not sort the result if there are only inverse search terms100 sortable = false101 Loop:102 for _, termSet := range termSets {103 for idx, term := range termSet {104 if !term.inv {105 sortable = true106 }107 // If the query contains inverse search terms or OR operators,108 // we cannot cache the search scope109 if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {110 cacheable = false111 if sortable {112 // Can't break until we see at least one non-inverse term113 break Loop114 }115 }116 }117 }118 } else {119 lowerString := strings.ToLower(asString)120 normalize = normalize &&121 lowerString == string(algo.NormalizeRunes([]rune(lowerString)))122 caseSensitive = caseMode == CaseRespect ||123 caseMode == CaseSmart && lowerString != asString124 if !caseSensitive {125 asString = lowerString126 }127 }128129 ptr := &Pattern{130 fuzzy: fuzzy,131 fuzzyAlgo: fuzzyAlgo,132 extended: extended,133 caseSensitive: caseSensitive,134 normalize: normalize,135 forward: forward,136 withPos: withPos,137 text: []rune(asString),138 termSets: termSets,139 sortable: sortable,140 cacheable: cacheable,141 nth: nth,142 delimiter: delimiter,143 cache: cache,144 procFun: make(map[termType]algo.Algo)}145146 ptr.cacheKey = ptr.buildCacheKey()147 ptr.procFun[termFuzzy] = fuzzyAlgo148 ptr.procFun[termEqual] = algo.EqualMatch149 ptr.procFun[termExact] = algo.ExactMatchNaive150 ptr.procFun[termPrefix] = algo.PrefixMatch151 ptr.procFun[termSuffix] = algo.SuffixMatch152153 patternCache[asString] = ptr154 return ptr155}156157func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {158 str = strings.ReplaceAll(str, "\\ ", "\t")159 tokens := _splitRegex.Split(str, -1)160 sets := []termSet{}161 set := termSet{}162 switchSet := false163 afterBar := false164 for _, token := range tokens {165 typ, inv, text := termFuzzy, false, strings.ReplaceAll(token, "\t", " ")166 lowerText := strings.ToLower(text)167 caseSensitive := caseMode == CaseRespect ||168 caseMode == CaseSmart && text != lowerText169 normalizeTerm := normalize &&170 lowerText == string(algo.NormalizeRunes([]rune(lowerText)))171 if !caseSensitive {172 text = lowerText173 }174 if !fuzzy {175 typ = termExact176 }177178 if len(set) > 0 && !afterBar && text == "|" {179 switchSet = false180 afterBar = true181 continue182 }183 afterBar = false184185 if strings.HasPrefix(text, "!") {186 inv = true187 typ = termExact188 text = text[1:]189 }190191 if text != "$" && strings.HasSuffix(text, "$") {192 typ = termSuffix193 text = text[:len(text)-1]194 }195196 if strings.HasPrefix(text, "'") {197 // Flip exactness198 if fuzzy && !inv {199 typ = termExact200 } else {201 typ = termFuzzy202 }203 text = text[1:]204 } else if strings.HasPrefix(text, "^") {205 if typ == termSuffix {206 typ = termEqual207 } else {208 typ = termPrefix209 }210 text = text[1:]211 }212213 if len(text) > 0 {214 if switchSet {215 sets = append(sets, set)216 set = termSet{}217 }218 textRunes := []rune(text)219 if normalizeTerm {220 textRunes = algo.NormalizeRunes(textRunes)221 }222 set = append(set, term{223 typ: typ,224 inv: inv,225 text: textRunes,226 caseSensitive: caseSensitive,227 normalize: normalizeTerm})228 switchSet = true229 }230 }231 if len(set) > 0 {232 sets = append(sets, set)233 }234 return sets235}236237// IsEmpty returns true if the pattern is effectively empty238func (p *Pattern) IsEmpty() bool {239 if !p.extended {240 return len(p.text) == 0241 }242 return len(p.termSets) == 0243}244245// AsString returns the search query in string type246func (p *Pattern) AsString() string {247 return string(p.text)248}249250func (p *Pattern) buildCacheKey() string {251 if !p.extended {252 return p.AsString()253 }254 cacheableTerms := []string{}255 for _, termSet := range p.termSets {256 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {257 cacheableTerms = append(cacheableTerms, string(termSet[0].text))258 }259 }260 return strings.Join(cacheableTerms, "\t")261}262263// CacheKey is used to build string to be used as the key of result cache264func (p *Pattern) CacheKey() string {265 return p.cacheKey266}267268// Match returns the list of matches Items in the given Chunk269func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {270 // ChunkCache: Exact match271 cacheKey := p.CacheKey()272 if p.cacheable {273 if cached := p.cache.Lookup(chunk, cacheKey); cached != nil {274 return cached275 }276 }277278 // Prefix/suffix cache279 space := p.cache.Search(chunk, cacheKey)280281 matches := p.matchChunk(chunk, space, slab)282283 if p.cacheable {284 p.cache.Add(chunk, cacheKey, matches)285 }286 return matches287}288289func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {290 matches := []Result{}291292 if space == nil {293 for idx := 0; idx < chunk.count; idx++ {294 if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match != nil {295 matches = append(matches, *match)296 }297 }298 } else {299 for _, result := range space {300 if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match != nil {301 matches = append(matches, *match)302 }303 }304 }305 return matches306}307308// MatchItem returns true if the Item is a match309func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {310 if p.extended {311 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {312 result := buildResult(item, offsets, bonus)313 return &result, offsets, pos314 }315 return nil, nil, nil316 }317 offset, bonus, pos := p.basicMatch(item, withPos, slab)318 if sidx := offset[0]; sidx >= 0 {319 offsets := []Offset{offset}320 result := buildResult(item, offsets, bonus)321 return &result, offsets, pos322 }323 return nil, nil, nil324}325326func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {327 var input []Token328 if len(p.nth) == 0 {329 input = []Token{{text: &item.text, prefixLength: 0}}330 } else {331 input = p.transformInput(item)332 }333 if p.fuzzy {334 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)335 }336 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)337}338339func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {340 var input []Token341 if len(p.nth) == 0 {342 input = []Token{{text: &item.text, prefixLength: 0}}343 } else {344 input = p.transformInput(item)345 }346 offsets := []Offset{}347 var totalScore int348 var allPos *[]int349 if withPos {350 allPos = &[]int{}351 }352 for _, termSet := range p.termSets {353 var offset Offset354 var currentScore int355 matched := false356 for _, term := range termSet {357 pfun := p.procFun[term.typ]358 off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)359 if sidx := off[0]; sidx >= 0 {360 if term.inv {361 continue362 }363 offset, currentScore = off, score364 matched = true365 if withPos {366 if pos != nil {367 *allPos = append(*allPos, *pos...)368 } else {369 for idx := off[0]; idx < off[1]; idx++ {370 *allPos = append(*allPos, int(idx))371 }372 }373 }374 break375 } else if term.inv {376 offset, currentScore = Offset{0, 0}, 0377 matched = true378 continue379 }380 }381 if matched {382 offsets = append(offsets, offset)383 totalScore += currentScore384 }385 }386 return offsets, totalScore, allPos387}388389func (p *Pattern) transformInput(item *Item) []Token {390 if item.transformed != nil {391 return *item.transformed392 }393394 tokens := Tokenize(item.text.ToString(), p.delimiter)395 ret := Transform(tokens, p.nth)396 item.transformed = &ret397 return ret398}399400func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {401 for _, part := range tokens {402 if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {403 sidx := int32(res.Start) + part.prefixLength404 eidx := int32(res.End) + part.prefixLength405 if pos != nil {406 for idx := range *pos {407 (*pos)[idx] += int(part.prefixLength)408 }409 }410 return Offset{sidx, eidx}, res.Score, pos411 }412 }413 return Offset{-1, -1}, 0, nil414}