Debian Codegraph @

src/algo/algo.go

raw
1 package algo
2
3 /*
4
5 Algorithm
6 ---------
7
8 FuzzyMatchV1 finds the first "fuzzy" occurrence of the pattern within the given
9 text in O(n) time where n is the length of the text. Once the position of the
10 last character is located, it traverses backwards to see if there's a shorter
11 substring that matches the pattern.
12
13 a_____b___abc__ To find "abc"
14 *-----*-----*> 1. Forward scan
15 <*** 2. Backward scan
16
17 The algorithm is simple and fast, but as it only sees the first occurrence,
18 it is not guaranteed to find the occurrence with the highest score.
19
20 a_____b__c__abc
21 *-----*--* ***
22
23 FuzzyMatchV2 implements a modified version of Smith-Waterman algorithm to find
24 the optimal solution (highest score) according to the scoring criteria. Unlike
25 the original algorithm, omission or mismatch of a character in the pattern is
26 not allowed.
27
28 Performance
29 -----------
30
31 The new V2 algorithm is slower than V1 as it examines all occurrences of the
32 pattern instead of stopping immediately after finding the first one. The time
33 complexity of the algorithm is O(nm) if a match is found and O(n) otherwise
34 where n is the length of the item and m is the length of the pattern. Thus, the
35 performance overhead may not be noticeable for a query with high selectivity.
36 However, if the performance is more important than the quality of the result,
37 you can still choose v1 algorithm with --algo=v1.
38
39 Scoring criteria
40 ----------------
41
42 - We prefer matches at special positions, such as the start of a word, or
43 uppercase character in camelCase words.
44
45 - That is, we prefer an occurrence of the pattern with more characters
46 matching at special positions, even if the total match length is longer.
47 e.g. "fuzzyfinder" vs. "fuzzy-finder" on "ff"
48 ````````````
49 - Also, if the first character in the pattern appears at one of the special
50 positions, the bonus point for the position is multiplied by a constant
51 as it is extremely likely that the first character in the typed pattern
52 has more significance than the rest.
53 e.g. "fo-bar" vs. "foob-r" on "br"
54 ``````
55 - But since fzf is still a fuzzy finder, not an acronym finder, we should also
56 consider the total length of the matched substring. This is why we have the
57 gap penalty. The gap penalty increases as the length of the gap (distance
58 between the matching characters) increases, so the effect of the bonus is
59 eventually cancelled at some point.
60 e.g. "fuzzyfinder" vs. "fuzzy-blurry-finder" on "ff"
61 ```````````
62 - Consequently, it is crucial to find the right balance between the bonus
63 and the gap penalty. The parameters were chosen that the bonus is cancelled
64 when the gap size increases beyond 8 characters.
65
66 - The bonus mechanism can have the undesirable side effect where consecutive
67 matches are ranked lower than the ones with gaps.
68 e.g. "foobar" vs. "foo-bar" on "foob"
69 ```````
70 - To correct this anomaly, we also give extra bonus point to each character
71 in a consecutive matching chunk.
72 e.g. "foobar" vs. "foo-bar" on "foob"
73 ``````
74 - The amount of consecutive bonus is primarily determined by the bonus of the
75 first character in the chunk.
76 e.g. "foobar" vs. "out-of-bound" on "oob"
77 ````````````
78 */
79
80 import (
81 "bytes"
82 "fmt"
83 "os"
84 "strings"
85 "unicode"
86 "unicode/utf8"
87
88 "github.com/junegunn/fzf/src/util"
89 )
90
91 var DEBUG bool
92
93 var delimiterChars = "/,:;|"
94
95 const whiteChars = " \t\n\v\f\r\x85\xA0"
96
97 func indexAt(index int, max int, forward bool) int {
98 if forward {
99 return index
100 }
101 return max - index - 1
102 }
103
104 // Result contains the results of running a match function.
105 type Result struct {
106 // TODO int32 should suffice
107 Start int
108 End int
109 Score int
110 }
111
112 const (
113 scoreMatch = 16
114 scoreGapStart = -3
115 scoreGapExtension = -1
116
117 // We prefer matches at the beginning of a word, but the bonus should not be
118 // too great to prevent the longer acronym matches from always winning over
119 // shorter fuzzy matches. The bonus point here was specifically chosen that
120 // the bonus is cancelled when the gap between the acronyms grows over
121 // 8 characters, which is approximately the average length of the words found
122 // in web2 dictionary and my file system.
123 bonusBoundary = scoreMatch / 2
124
125 // Although bonus point for non-word characters is non-contextual, we need it
126 // for computing bonus points for consecutive chunks starting with a non-word
127 // character.
128 bonusNonWord = scoreMatch / 2
129
130 // Edge-triggered bonus for matches in camelCase words.
131 // Compared to word-boundary case, they don't accompany single-character gaps
132 // (e.g. FooBar vs. foo-bar), so we deduct bonus point accordingly.
133 bonusCamel123 = bonusBoundary + scoreGapExtension
134
135 // Minimum bonus point given to characters in consecutive chunks.
136 // Note that bonus points for consecutive matches shouldn't have needed if we
137 // used fixed match score as in the original algorithm.
138 bonusConsecutive = -(scoreGapStart + scoreGapExtension)
139
140 // The first character in the typed pattern usually has more significance
141 // than the rest so it's important that it appears at special positions where
142 // bonus points are given, e.g. "to-go" vs. "ongoing" on "og" or on "ogo".
143 // The amount of the extra bonus should be limited so that the gap penalty is
144 // still respected.
145 bonusFirstCharMultiplier = 2
146 )
147
148 var (
149 // Extra bonus for word boundary after whitespace character or beginning of the string
150 bonusBoundaryWhite int16 = bonusBoundary + 2
151
152 // Extra bonus for word boundary after slash, colon, semi-colon, and comma
153 bonusBoundaryDelimiter int16 = bonusBoundary + 1
154
155 initialCharClass = charWhite
156
157 // A minor optimization that can give 15%+ performance boost
158 asciiCharClasses [unicode.MaxASCII + 1]charClass
159
160 // A minor optimization that can give yet another 5% performance boost
161 bonusMatrix [charNumber + 1][charNumber + 1]int16
162 )
163
164 type charClass int
165
166 const (
167 charWhite charClass = iota
168 charNonWord
169 charDelimiter
170 charLower
171 charUpper
172 charLetter
173 charNumber
174 )
175
176 func Init(scheme string) bool {
177 switch scheme {
178 case "default":
179 bonusBoundaryWhite = bonusBoundary + 2
180 bonusBoundaryDelimiter = bonusBoundary + 1
181 case "path":
182 bonusBoundaryWhite = bonusBoundary
183 bonusBoundaryDelimiter = bonusBoundary + 1
184 if os.PathSeparator == '/' {
185 delimiterChars = "/"
186 } else {
187 delimiterChars = string([]rune{os.PathSeparator, '/'})
188 }
189 initialCharClass = charDelimiter
190 case "history":
191 bonusBoundaryWhite = bonusBoundary
192 bonusBoundaryDelimiter = bonusBoundary
193 default:
194 return false
195 }
196 for i := 0; i <= unicode.MaxASCII; i++ {
197 char := rune(i)
198 c := charNonWord
199 if char >= 'a' && char <= 'z' {
200 c = charLower
201 } else if char >= 'A' && char <= 'Z' {
202 c = charUpper
203 } else if char >= '0' && char <= '9' {
204 c = charNumber
205 } else if strings.ContainsRune(whiteChars, char) {
206 c = charWhite
207 } else if strings.ContainsRune(delimiterChars, char) {
208 c = charDelimiter
209 }
210 asciiCharClasses[i] = c
211 }
212 for i := 0; i <= int(charNumber); i++ {
213 for j := 0; j <= int(charNumber); j++ {
214 bonusMatrix[i][j] = bonusFor(charClass(i), charClass(j))
215 }
216 }
217 return true
218 }
219
220 func posArray(withPos bool, len int) *[]int {
221 if withPos {
222 pos := make([]int, 0, len)
223 return &pos
224 }
225 return nil
226 }
227
228 func alloc16(offset int, slab *util.Slab, size int) (int, []int16) {
229 if slab != nil && cap(slab.I16) > offset+size {
230 slice := slab.I16[offset : offset+size]
231 return offset + size, slice
232 }
233 return offset, make([]int16, size)
234 }
235
236 func alloc32(offset int, slab *util.Slab, size int) (int, []int32) {
237 if slab != nil && cap(slab.I32) > offset+size {
238 slice := slab.I32[offset : offset+size]
239 return offset + size, slice
240 }
241 return offset, make([]int32, size)
242 }
243
244 func charClassOfNonAscii(char rune) charClass {
245 if unicode.IsLower(char) {
246 return charLower
247 } else if unicode.IsUpper(char) {
248 return charUpper
249 } else if unicode.IsNumber(char) {
250 return charNumber
251 } else if unicode.IsLetter(char) {
252 return charLetter
253 } else if unicode.IsSpace(char) {
254 return charWhite
255 } else if strings.ContainsRune(delimiterChars, char) {
256 return charDelimiter
257 }
258 return charNonWord
259 }
260
261 func charClassOf(char rune) charClass {
262 if char <= unicode.MaxASCII {
263 return asciiCharClasses[char]
264 }
265 return charClassOfNonAscii(char)
266 }
267
268 func bonusFor(prevClass charClass, class charClass) int16 {
269 if class >= charNonWord {
270 switch prevClass {
271 case charWhite:
272 // Word boundary after whitespace
273 return bonusBoundaryWhite
274 case charDelimiter:
275 // Word boundary after a delimiter character
276 return bonusBoundaryDelimiter
277 case charNonWord:
278 // Word boundary
279 return bonusBoundary
280 }
281 }
282
283 if prevClass == charLower && class == charUpper ||
284 prevClass != charNumber && class == charNumber {
285 // camelCase letter123
286 return bonusCamel123
287 }
288
289 switch class {
290 case charNonWord, charDelimiter:
291 return bonusNonWord
292 case charWhite:
293 return bonusBoundaryWhite
294 }
295 return 0
296 }
297
298 func bonusAt(input *util.Chars, idx int) int16 {
299 if idx == 0 {
300 return bonusBoundaryWhite
301 }
302 return bonusMatrix[charClassOf(input.Get(idx-1))][charClassOf(input.Get(idx))]
303 }
304
305 func normalizeRune(r rune) rune {
306 // Every key of the map folds to ASCII, so a rune the bitmap rejects cannot
307 // be in it. TestNormalizedKeysAreFlagged verifies that.
308 if !util.MayFoldToAscii(r) {
309 return r
310 }
311
312 n := normalized[r]
313 if n > 0 {
314 return n
315 }
316 return r
317 }
318
319 // Algo functions make two assumptions
320 // 1. "pattern" is given in lowercase if "caseSensitive" is false
321 // 2. "pattern" is already normalized if "normalize" is true
322 type Algo func(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int)
323
324 func trySkip(input *util.Chars, caseSensitive bool, b byte, from int) int {
325 byteArray := input.Bytes()[from:]
326 // For case-insensitive search of a letter, search for both cases in one pass
327 if !caseSensitive && b >= 'a' && b <= 'z' {
328 idx := IndexByteTwo(byteArray, b, b-32)
329 if idx < 0 {
330 return -1
331 }
332 return from + idx
333 }
334 idx := bytes.IndexByte(byteArray, b)
335 if idx < 0 {
336 return -1
337 }
338 return from + idx
339 }
340
341 func isAscii(runes []rune) bool {
342 for _, r := range runes {
343 if r >= utf8.RuneSelf {
344 return false
345 }
346 }
347 return true
348 }
349
350 // runePrefilterable reports whether scanning the rune array can decide this
351 // pattern against this item without missing a match. Phase 2 lowercases an
352 // uppercase text rune and then normalizes it, and the scan sees neither
353 // transform, so every pattern rune must be unreachable by them.
354 func runePrefilterable(input *util.Chars, pattern []rune, caseSensitive bool) bool {
355 if input.MayFoldToAscii() {
356 // A non-ASCII rune of this item could fold onto an ASCII pattern char
357 for _, r := range pattern {
358 if r < utf8.RuneSelf {
359 return false
360 }
361 }
362 }
363 if caseSensitive {
364 // No case transform is applied, and normalization only ever produces
365 // ASCII, so nothing can reach a non-ASCII pattern rune
366 return true
367 }
368 for _, r := range pattern {
369 // Another rune must not lowercase onto this one. Being uncased is not
370 // enough by itself: U+00DF has no simple uppercase yet U+1E9E
371 // lowercases to it. Excluding the foldable set covers that.
372 if r >= utf8.RuneSelf &&
373 (unicode.ToUpper(r) != r || unicode.ToLower(r) != r || util.MayFoldToAscii(r)) {
374 return false
375 }
376 }
377 return true
378 }
379
380 // runeFuzzyIndex is asciiFuzzyIndex for rune-mode input. Only valid when
381 // runePrefilterable says so.
382 func runeFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) {
383 runes := input.Runes()
384 firstIdx, idx, lastIdx := 0, 0, 0
385 var last rune
386 for pidx := range pattern {
387 last = pattern[pidx]
388 if last < utf8.RuneSelf {
389 idx = indexAsciiRune(runes, caseSensitive, byte(last), idx)
390 } else {
391 idx = indexRune(runes, last, idx)
392 }
393 if idx < 0 {
394 return -1, -1
395 }
396 if pidx == 0 && idx > 0 {
397 // Step back to find the right bonus point
398 firstIdx = idx - 1
399 }
400 lastIdx = idx
401 idx++
402 }
403
404 // Find the last appearance of the last character of the pattern to limit
405 // the search scope
406 if lastIdx+1 < len(runes) {
407 var end int
408 if last < utf8.RuneSelf {
409 end = lastIndexAsciiRune(runes, caseSensitive, byte(last), lastIdx+1)
410 } else {
411 end = lastIndexRune(runes, last, lastIdx+1)
412 }
413 if end >= 0 {
414 return firstIdx, end + 1
415 }
416 }
417 return firstIdx, lastIdx + 1
418 }
419
420 func asciiFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) {
421 if !input.IsBytes() {
422 if disableRunePrefilter {
423 return 0, input.Length()
424 }
425 // runePrefilterable does not inline, so keep the common case out of
426 // it: an ASCII pattern against an item that cannot fold to ASCII is
427 // always scannable, and both of these checks do inline.
428 if input.MayFoldToAscii() || !isAscii(pattern) {
429 if !runePrefilterable(input, pattern, caseSensitive) {
430 return 0, input.Length()
431 }
432 }
433 return runeFuzzyIndex(input, pattern, caseSensitive)
434 }
435
436 // Not possible
437 if !isAscii(pattern) {
438 return -1, -1
439 }
440
441 firstIdx, idx, lastIdx := 0, 0, 0
442 var b byte
443 for pidx := range pattern {
444 b = byte(pattern[pidx])
445 idx = trySkip(input, caseSensitive, b, idx)
446 if idx < 0 {
447 return -1, -1
448 }
449 if pidx == 0 && idx > 0 {
450 // Step back to find the right bonus point
451 firstIdx = idx - 1
452 }
453 lastIdx = idx
454 idx++
455 }
456
457 // Find the last appearance of the last character of the pattern to limit the search scope
458 scope := input.Bytes()[lastIdx:]
459 if len(scope) > 1 {
460 tail := scope[1:]
461 var end int
462 if !caseSensitive && b >= 'a' && b <= 'z' {
463 end = lastIndexByteTwo(tail, b, b-32)
464 } else {
465 end = bytes.LastIndexByte(tail, b)
466 }
467 if end >= 0 {
468 return firstIdx, lastIdx + 1 + end + 1
469 }
470 }
471 return firstIdx, lastIdx + 1
472 }
473
474 func debugV2(T []rune, pattern []rune, F []int32, lastIdx int, H []int16, C []int16) {
475 width := lastIdx - int(F[0]) + 1
476
477 for i, f := range F {
478 I := i * width
479 if i == 0 {
480 fmt.Print(" ")
481 for j := int(f); j <= lastIdx; j++ {
482 fmt.Print(" " + string(T[j]) + " ")
483 }
484 fmt.Println()
485 }
486 fmt.Print(string(pattern[i]) + " ")
487 for idx := int(F[0]); idx < int(f); idx++ {
488 fmt.Print(" 0 ")
489 }
490 for idx := int(f); idx <= lastIdx; idx++ {
491 fmt.Printf("%2d ", H[i*width+idx-int(F[0])])
492 }
493 fmt.Println()
494
495 fmt.Print(" ")
496 for idx, p := range C[I : I+width] {
497 if idx+int(F[0]) < int(F[i]) {
498 p = 0
499 }
500 if p > 0 {
501 fmt.Printf("%2d ", p)
502 } else {
503 fmt.Print(" ")
504 }
505 }
506 fmt.Println()
507 }
508 }
509
510 // fuzzyMatchV2Single is a fast path for a single-character ASCII pattern on
511 // ASCII input. Same scoring and tiebreaks as Phase 2 of FuzzyMatchV2, but
512 // jumps between occurrences instead of scanning every character, and
513 // allocates no arrays.
514 func fuzzyMatchV2Single(caseSensitive bool, forward bool, input *util.Chars, b byte, withPos bool) (Result, *[]int) {
515 byteArray := input.Bytes()
516 maxScore, maxScorePos := int16(0), -1
517 for idx := 0; idx < len(byteArray); {
518 idx = trySkip(input, caseSensitive, b, idx)
519 if idx < 0 {
520 break
521 }
522 class := asciiCharClasses[byteArray[idx]]
523 prevClass := initialCharClass
524 if idx > 0 {
525 prevClass = asciiCharClasses[byteArray[idx-1]]
526 }
527 bonus := bonusMatrix[prevClass][class]
528 score := scoreMatch + bonus*bonusFirstCharMultiplier
529 if forward && score > maxScore || !forward && score >= maxScore {
530 maxScore, maxScorePos = score, idx
531 if forward && bonus >= bonusBoundary {
532 break
533 }
534 }
535 idx++
536 }
537 if maxScorePos < 0 {
538 return Result{-1, -1, 0}, nil
539 }
540 result := Result{maxScorePos, maxScorePos + 1, int(maxScore)}
541 if !withPos {
542 return result, nil
543 }
544 pos := []int{maxScorePos}
545 return result, &pos
546 }
547
548 // Test hooks: force the general path instead of a fast path, so the two can
549 // be compared for equivalence.
550 var (
551 disableSingle bool
552 disableTwo bool
553 disableRunePrefilter bool
554 )
555
556 // fuzzyMatchV2Two is a fused fast path for a two-character ASCII pattern on
557 // ASCII input. It replicates Phase 2 (row 0) and Phase 3 (row 1) of
558 // FuzzyMatchV2 in a single pass, carrying the row-0 diagonal/left values and
559 // the row-1 left value as scalars instead of materializing score arrays.
560 // When withPos is set, the two DP rows are stored so the backtrace can
561 // recover the matched character positions, exactly as the general Phase 4.
562 func fuzzyMatchV2Two(caseSensitive bool, forward bool, input *util.Chars, pchar0 byte, pchar1 byte, minIdx int, maxIdx int, withPos bool, slab *util.Slab) (Result, *[]int) {
563 sl := input.Bytes()
564 N := maxIdx - minIdx
565
566 // Row storage, only needed for the backtrace
567 var H0, C0, H1, C1 []int16
568 if withPos {
569 o := 0
570 o, H0 = alloc16(o, slab, N)
571 o, C0 = alloc16(o, slab, N)
572 o, H1 = alloc16(o, slab, N)
573 _, C1 = alloc16(o, slab, N)
574 }
575
576 maxScore, maxScorePos := int16(0), 0
577 prevClass := initialCharClass
578
579 // Subsequence tracking (equivalent to F[0], F[1] in Phase 2). The scope
580 // from asciiFuzzyIndex ends exactly at the last pchar1, so row 1's upper
581 // bound (Phase 3 lastIdx) is the final loop position; no separate var.
582 f0, f1 := -1, -1
583
584 // Row 0 running state at the previous position
585 var h0Prev, c0Prev, bPrev int16
586 inGap0 := false
587
588 // Row 1 running state
589 var h1Prev int16
590 inGap1 := false
591
592 for off := range N {
593 pos := minIdx + off
594 b := sl[pos]
595 class := asciiCharClasses[b]
596 lb := b
597 if !caseSensitive && b >= 'A' && b <= 'Z' {
598 lb = b + 32
599 }
600 bonus := bonusMatrix[prevClass][class]
601 prevClass = class
602
603 // Subsequence advance: pchar0 then pchar1
604 if f0 < 0 {
605 if lb == pchar0 {
606 f0 = off
607 }
608 } else if lb == pchar1 && f1 < 0 {
609 f1 = off
610 }
611
612 // Row 0 (pchar0)
613 var h0Cur, c0Cur int16
614 if lb == pchar0 {
615 h0Cur = scoreMatch + bonus*bonusFirstCharMultiplier
616 c0Cur = 1
617 inGap0 = false
618 } else {
619 if inGap0 {
620 h0Cur = max(h0Prev+scoreGapExtension, 0)
621 } else {
622 h0Cur = max(h0Prev+scoreGapStart, 0)
623 }
624 c0Cur = 0
625 inGap0 = true
626 }
627 if withPos {
628 H0[off], C0[off] = h0Cur, c0Cur
629 }
630
631 // Row 1 (pchar1), only within [f1, lastIdx]
632 if f1 >= 0 && off >= f1 {
633 var s1, s2, consecutive int16
634 hleft := h1Prev
635 if off == f1 {
636 hleft = 0
637 }
638 if inGap1 {
639 s2 = hleft + scoreGapExtension
640 } else {
641 s2 = hleft + scoreGapStart
642 }
643 if lb == pchar1 {
644 s1 = h0Prev + scoreMatch
645 bb := bonus
646 consecutive = c0Prev + 1
647 if consecutive > 1 {
648 fb := bPrev
649 if bb >= bonusBoundary && bb > fb {
650 consecutive = 1
651 } else {
652 bb = max(bb, bonusConsecutive, fb)
653 }
654 }
655 if s1+bb < s2 {
656 s1 += bonus
657 consecutive = 0
658 } else {
659 s1 += bb
660 }
661 }
662 inGap1 = s1 < s2
663 score := max(s1, s2, 0)
664 if forward && score > maxScore || !forward && score >= maxScore {
665 maxScore, maxScorePos = score, off
666 }
667 h1Prev = score
668 if withPos {
669 H1[off], C1[off] = score, consecutive
670 }
671 }
672
673 h0Prev, c0Prev, bPrev = h0Cur, c0Cur, bonus
674 }
675
676 if f1 < 0 {
677 return Result{-1, -1, 0}, nil
678 }
679 if !withPos {
680 return Result{minIdx + f0, minIdx + maxScorePos + 1, int(maxScore)}, nil
681 }
682
683 // Phase 4 backtrace, specialized to two rows. Mirrors the general loop:
684 // record a cell when it dominates its diagonal and left neighbors, then
685 // step up a row; otherwise step left. preferMatch breaks score ties and
686 // must not read row 1 left of f1 (unwritten, possibly stale slab data).
687 pos := posArray(true, 2)
688 i := 1
689 j := maxScorePos
690 preferMatch := true
691 for {
692 var s, s1, s2, cCur int16
693 if i == 1 {
694 s, cCur = H1[j], C1[j]
695 if j >= f1 {
696 s1 = H0[j-1]
697 }
698 if j > f1 {
699 s2 = H1[j-1]
700 }
701 } else {
702 s, cCur = H0[j], C0[j]
703 if j > f0 {
704 s2 = H0[j-1]
705 }
706 }
707 row := i
708 if s > s1 && (s > s2 || s == s2 && preferMatch) {
709 *pos = append(*pos, j+minIdx)
710 if i == 0 {
711 break
712 }
713 i--
714 }
715 preferMatch = cCur > 1 ||
716 row == 0 && j < N-1 && j+1 >= f1 && C1[j+1] > 0
717 j--
718 }
719 return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos
720 }
721
722 func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
723 // Assume that pattern is given in lowercase if case-insensitive.
724 // First check if there's a match and calculate bonus for each position.
725 // If the input string is too long, consider finding the matching chars in
726 // this phase as well (non-optimal alignment).
727 M := len(pattern)
728 if M == 0 {
729 return Result{0, 0, 0}, posArray(withPos, M)
730 }
731 N := input.Length()
732 if M > N {
733 return Result{-1, -1, 0}, nil
734 }
735
736 // Since O(nm) algorithm can be prohibitively expensive for large input,
737 // we fall back to the greedy algorithm.
738 // Also, we should not allow a very long pattern to avoid 16-bit integer
739 // overflow in the score matrix. 1000 is a safe limit.
740 if slab != nil && int64(N)*int64(M) > int64(cap(slab.I16)) || M > 1000 {
741 return FuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos, slab)
742 }
743
744 // Single-character ASCII pattern needs neither the prefilter nor the
745 // score matrix
746 if !disableSingle && M == 1 && input.IsBytes() && pattern[0] < utf8.RuneSelf {
747 return fuzzyMatchV2Single(caseSensitive, forward, input, byte(pattern[0]), withPos)
748 }
749
750 // Phase 1. Optimized search for ASCII string
751 minIdx, maxIdx := asciiFuzzyIndex(input, pattern, caseSensitive)
752 if minIdx < 0 {
753 return Result{-1, -1, 0}, nil
754 }
755 // fmt.Println(N, maxIdx, idx, maxIdx-idx, input.ToString())
756 N = maxIdx - minIdx
757
758 // Two-character ASCII pattern: rows 0 and 1 collapse to scalar running
759 // state, so the general score arrays are unnecessary
760 if !disableTwo && M == 2 && input.IsBytes() &&
761 pattern[0] < utf8.RuneSelf && pattern[1] < utf8.RuneSelf {
762 return fuzzyMatchV2Two(caseSensitive, forward, input, byte(pattern[0]), byte(pattern[1]), minIdx, maxIdx, withPos, slab)
763 }
764
765 // Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages
766 offset16 := 0
767 offset32 := 0
768 offset16, H0 := alloc16(offset16, slab, N)
769 offset16, C0 := alloc16(offset16, slab, N)
770 // Bonus point for each position
771 offset16, B := alloc16(offset16, slab, N)
772 // The first occurrence of each character in the pattern
773 offset32, F := alloc32(offset32, slab, M)
774 // Rune array
775 _, T := alloc32(offset32, slab, N)
776 input.CopyRunes(T, minIdx)
777
778 // Phase 2. Calculate bonus for each point
779 maxScore, maxScorePos := int16(0), 0
780 pidx, lastIdx := 0, 0
781 pchar0, pchar, prevH0, prevClass, inGap := pattern[0], pattern[0], int16(0), initialCharClass, false
782 for off, char := range T {
783 var class charClass
784 if char <= unicode.MaxASCII {
785 class = asciiCharClasses[char]
786 if !caseSensitive && class == charUpper {
787 char += 32
788 T[off] = char
789 }
790 } else {
791 class = charClassOfNonAscii(char)
792 if !caseSensitive && class == charUpper {
793 char = unicode.To(unicode.LowerCase, char)
794 }
795 if normalize {
796 char = normalizeRune(char)
797 }
798 T[off] = char
799 }
800
801 bonus := bonusMatrix[prevClass][class]
802 B[off] = bonus
803 prevClass = class
804
805 if char == pchar {
806 if pidx < M {
807 F[pidx] = int32(off)
808 pidx++
809 pchar = pattern[min(pidx, M-1)]
810 }
811 lastIdx = off
812 }
813
814 if char == pchar0 {
815 score := scoreMatch + bonus*bonusFirstCharMultiplier
816 H0[off] = score
817 C0[off] = 1
818 if M == 1 && (forward && score > maxScore || !forward && score >= maxScore) {
819 maxScore, maxScorePos = score, off
820 if forward && bonus >= bonusBoundary {
821 break
822 }
823 }
824 inGap = false
825 } else {
826 if inGap {
827 H0[off] = max(prevH0+scoreGapExtension, 0)
828 } else {
829 H0[off] = max(prevH0+scoreGapStart, 0)
830 }
831 C0[off] = 0
832 inGap = true
833 }
834 prevH0 = H0[off]
835 }
836 if pidx != M {
837 return Result{-1, -1, 0}, nil
838 }
839 if M == 1 {
840 result := Result{minIdx + maxScorePos, minIdx + maxScorePos + 1, int(maxScore)}
841 if !withPos {
842 return result, nil
843 }
844 pos := []int{minIdx + maxScorePos}
845 return result, &pos
846 }
847
848 // Phase 3. Fill in score matrix (H)
849 // Unlike the original algorithm, we do not allow omission.
850 f0 := int(F[0])
851 width := lastIdx - f0 + 1
852 offset16, H := alloc16(offset16, slab, width*M)
853 copy(H, H0[f0:lastIdx+1])
854
855 // Possible length of consecutive chunk at each position.
856 _, C := alloc16(offset16, slab, width*M)
857 copy(C, C0[f0:lastIdx+1])
858
859 Fsub := F[1:]
860 Psub := pattern[1:][:len(Fsub)]
861 for off, f := range Fsub {
862 f := int(f)
863 pchar := Psub[off]
864 pidx := off + 1
865 row := pidx * width
866 inGap := false
867 Tsub := T[f : lastIdx+1]
868 Bsub := B[f:][:len(Tsub)]
869 Csub := C[row+f-f0:][:len(Tsub)]
870 Cdiag := C[row+f-f0-1-width:][:len(Tsub)]
871 Hsub := H[row+f-f0:][:len(Tsub)]
872 Hdiag := H[row+f-f0-1-width:][:len(Tsub)]
873 Hleft := H[row+f-f0-1:][:len(Tsub)]
874 Hleft[0] = 0
875 for off, char := range Tsub {
876 col := off + f
877 var s1, s2, consecutive int16
878
879 if inGap {
880 s2 = Hleft[off] + scoreGapExtension
881 } else {
882 s2 = Hleft[off] + scoreGapStart
883 }
884
885 if pchar == char {
886 s1 = Hdiag[off] + scoreMatch
887 b := Bsub[off]
888 consecutive = Cdiag[off] + 1
889 if consecutive > 1 {
890 fb := B[col-int(consecutive)+1]
891 // Break consecutive chunk
892 if b >= bonusBoundary && b > fb {
893 consecutive = 1
894 } else {
895 b = max(b, bonusConsecutive, fb)
896 }
897 }
898 if s1+b < s2 {
899 s1 += Bsub[off]
900 consecutive = 0
901 } else {
902 s1 += b
903 }
904 }
905 Csub[off] = consecutive
906
907 inGap = s1 < s2
908 score := max(s1, s2, 0)
909 if pidx == M-1 && (forward && score > maxScore || !forward && score >= maxScore) {
910 maxScore, maxScorePos = score, col
911 }
912 Hsub[off] = score
913 }
914 }
915
916 if DEBUG {
917 debugV2(T, pattern, F, lastIdx, H, C)
918 }
919
920 // Phase 4. (Optional) Backtrace to find character positions
921 pos := posArray(withPos, M)
922 j := f0
923 if withPos {
924 i := M - 1
925 j = maxScorePos
926 preferMatch := true
927 for {
928 I := i * width
929 j0 := j - f0
930 s := H[I+j0]
931
932 var s1, s2 int16
933 if i > 0 && j >= int(F[i]) {
934 s1 = H[I-width+j0-1]
935 }
936 if j > int(F[i]) {
937 s2 = H[I+j0-1]
938 }
939
940 row := i
941 if s > s1 && (s > s2 || s == s2 && preferMatch) {
942 *pos = append(*pos, j+minIdx)
943 if i == 0 {
944 break
945 }
946 i--
947 }
948 // Row below is only written from column F[row+1]; don't read
949 // stale slab data left of it
950 preferMatch = C[I+j0] > 1 ||
951 row+1 < M && j < lastIdx && int32(j+1) >= F[row+1] && C[I+width+j0+1] > 0
952 j--
953 }
954 }
955 // Start offset we return here is only relevant when begin tiebreak is used.
956 // However finding the accurate offset requires backtracking, and we don't
957 // want to pay extra cost for the option that has lost its importance.
958 return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos
959 }
960
961 // Implement the same sorting criteria as V2
962 func calculateScore(caseSensitive bool, normalize bool, text *util.Chars, pattern []rune, sidx int, eidx int, withPos bool) (int, *[]int) {
963 pidx, score, inGap, consecutive, firstBonus := 0, 0, false, 0, int16(0)
964 pos := posArray(withPos, len(pattern))
965 prevClass := initialCharClass
966 if sidx > 0 {
967 prevClass = charClassOf(text.Get(sidx - 1))
968 }
969 for idx := sidx; idx < eidx; idx++ {
970 char := text.Get(idx)
971 class := charClassOf(char)
972 if !caseSensitive {
973 if char >= 'A' && char <= 'Z' {
974 char += 32
975 } else if char > unicode.MaxASCII {
976 char = unicode.To(unicode.LowerCase, char)
977 }
978 }
979 // pattern is already normalized
980 if normalize {
981 char = normalizeRune(char)
982 }
983 if char == pattern[pidx] {
984 if withPos {
985 *pos = append(*pos, idx)
986 }
987 score += scoreMatch
988 bonus := bonusMatrix[prevClass][class]
989 if consecutive == 0 {
990 firstBonus = bonus
991 } else {
992 // Break consecutive chunk
993 if bonus >= bonusBoundary && bonus > firstBonus {
994 firstBonus = bonus
995 }
996 bonus = max(bonus, firstBonus, bonusConsecutive)
997 }
998 if pidx == 0 {
999 score += int(bonus * bonusFirstCharMultiplier)
1000 } else {
1001 score += int(bonus)
1002 }
1003 inGap = false
1004 consecutive++
1005 pidx++
1006 } else {
1007 if inGap {
1008 score += scoreGapExtension
1009 } else {
1010 score += scoreGapStart
1011 }
1012 inGap = true
1013 consecutive = 0
1014 firstBonus = 0
1015 }
1016 prevClass = class
1017 }
1018 return score, pos
1019 }
1020
1021 // FuzzyMatchV1 performs fuzzy-match
1022 func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1023 if len(pattern) == 0 {
1024 return Result{0, 0, 0}, nil
1025 }
1026 idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive)
1027 if idx < 0 {
1028 return Result{-1, -1, 0}, nil
1029 }
1030
1031 pidx := 0
1032 sidx := -1
1033 eidx := -1
1034
1035 lenRunes := text.Length()
1036 lenPattern := len(pattern)
1037
1038 for index := range lenRunes {
1039 char := text.Get(indexAt(index, lenRunes, forward))
1040 // This is considerably faster than blindly applying strings.ToLower to the
1041 // whole string
1042 if !caseSensitive {
1043 // Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable
1044 // difference in CPU cost. (Measured on Go 1.4.1. Also note that the Go
1045 // compiler as of now does not inline non-leaf functions.)
1046 if char >= 'A' && char <= 'Z' {
1047 char += 32
1048 } else if char > unicode.MaxASCII {
1049 char = unicode.To(unicode.LowerCase, char)
1050 }
1051 }
1052 if normalize {
1053 char = normalizeRune(char)
1054 }
1055 pchar := pattern[indexAt(pidx, lenPattern, forward)]
1056 if char == pchar {
1057 if sidx < 0 {
1058 sidx = index
1059 }
1060 if pidx++; pidx == lenPattern {
1061 eidx = index + 1
1062 break
1063 }
1064 }
1065 }
1066
1067 if sidx >= 0 && eidx >= 0 {
1068 pidx--
1069 for index := eidx - 1; index >= sidx; index-- {
1070 tidx := indexAt(index, lenRunes, forward)
1071 char := text.Get(tidx)
1072 if !caseSensitive {
1073 if char >= 'A' && char <= 'Z' {
1074 char += 32
1075 } else if char > unicode.MaxASCII {
1076 char = unicode.To(unicode.LowerCase, char)
1077 }
1078 }
1079 if normalize {
1080 char = normalizeRune(char)
1081 }
1082
1083 pidx_ := indexAt(pidx, lenPattern, forward)
1084 pchar := pattern[pidx_]
1085 if char == pchar {
1086 if pidx--; pidx < 0 {
1087 sidx = index
1088 break
1089 }
1090 }
1091 }
1092
1093 if !forward {
1094 sidx, eidx = lenRunes-eidx, lenRunes-sidx
1095 }
1096
1097 score, pos := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos)
1098 return Result{sidx, eidx, score}, pos
1099 }
1100 return Result{-1, -1, 0}, nil
1101 }
1102
1103 // ExactMatchNaive is a basic string searching algorithm that handles case
1104 // sensitivity. Although naive, it still performs better than the combination
1105 // of strings.ToLower + strings.Index for typical fzf use cases where input
1106 // strings and patterns are not very long.
1107 //
1108 // Since 0.15.0, this function searches for the match with the highest
1109 // bonus point, instead of stopping immediately after finding the first match.
1110 // The solution is much cheaper since there is only one possible alignment of
1111 // the pattern.
1112 func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1113 return exactMatchNaive(caseSensitive, normalize, forward, false, text, pattern, withPos, slab)
1114 }
1115
1116 func ExactMatchBoundary(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1117 return exactMatchNaive(caseSensitive, normalize, forward, true, text, pattern, withPos, slab)
1118 }
1119
1120 func exactMatchNaive(caseSensitive bool, normalize bool, forward bool, boundaryCheck bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1121 if len(pattern) == 0 {
1122 return Result{0, 0, 0}, nil
1123 }
1124
1125 lenRunes := text.Length()
1126 lenPattern := len(pattern)
1127
1128 if lenRunes < lenPattern {
1129 return Result{-1, -1, 0}, nil
1130 }
1131
1132 idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive)
1133 if idx < 0 {
1134 return Result{-1, -1, 0}, nil
1135 }
1136
1137 // For simplicity, only look at the bonus at the first character position
1138 pidx := 0
1139 bestPos, bonus, bbonus, bestBonus := -1, int16(0), int16(0), int16(-1)
1140 for index := 0; index < lenRunes; index++ {
1141 index_ := indexAt(index, lenRunes, forward)
1142 char := text.Get(index_)
1143 if !caseSensitive {
1144 if char >= 'A' && char <= 'Z' {
1145 char += 32
1146 } else if char > unicode.MaxASCII {
1147 char = unicode.To(unicode.LowerCase, char)
1148 }
1149 }
1150 if normalize {
1151 char = normalizeRune(char)
1152 }
1153 pidx_ := indexAt(pidx, lenPattern, forward)
1154 pchar := pattern[pidx_]
1155 ok := pchar == char
1156 if ok {
1157 if pidx_ == 0 {
1158 bonus = bonusAt(text, index_)
1159 }
1160 if boundaryCheck {
1161 if forward && pidx_ == 0 {
1162 bbonus = bonus
1163 } else if !forward && pidx_ == lenPattern-1 {
1164 if index_ < lenRunes-1 {
1165 bbonus = bonusAt(text, index_+1)
1166 } else {
1167 bbonus = bonusBoundaryWhite
1168 }
1169 }
1170 ok = bbonus >= bonusBoundary
1171 if ok && pidx_ == 0 {
1172 ok = index_ == 0 || charClassOf(text.Get(index_-1)) <= charDelimiter
1173 }
1174 if ok && pidx_ == len(pattern)-1 {
1175 ok = index_ == lenRunes-1 || charClassOf(text.Get(index_+1)) <= charDelimiter
1176 }
1177 }
1178 }
1179 if ok {
1180 pidx++
1181 if pidx == lenPattern {
1182 if bonus > bestBonus {
1183 bestPos, bestBonus = index, bonus
1184 }
1185 if bonus >= bonusBoundary {
1186 break
1187 }
1188 index -= pidx - 1
1189 pidx, bonus = 0, 0
1190 }
1191 } else {
1192 index -= pidx
1193 pidx, bonus = 0, 0
1194 }
1195 }
1196 if bestPos >= 0 {
1197 var sidx, eidx int
1198 if forward {
1199 sidx = bestPos - lenPattern + 1
1200 eidx = bestPos + 1
1201 } else {
1202 sidx = lenRunes - (bestPos + 1)
1203 eidx = lenRunes - (bestPos - lenPattern + 1)
1204 }
1205 var score int
1206 if boundaryCheck {
1207 // Underscore boundaries should be ranked lower than the other types of boundaries
1208 score = int(bonus)
1209 deduct := int(bonus-bonusBoundary) + 1
1210 if sidx > 0 && text.Get(sidx-1) == '_' {
1211 score -= deduct + 1
1212 deduct = 1
1213 }
1214 if eidx < lenRunes && text.Get(eidx) == '_' {
1215 score -= deduct
1216 }
1217 // Add base score so that this can compete with other match types e.g. 'foo' | bar
1218 score += scoreMatch*lenPattern + int(bonusBoundaryWhite)*(lenPattern+1)
1219 } else {
1220 score, _ = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false)
1221 }
1222 return Result{sidx, eidx, score}, nil
1223 }
1224 return Result{-1, -1, 0}, nil
1225 }
1226
1227 // PrefixMatch performs prefix-match
1228 func PrefixMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1229 if len(pattern) == 0 {
1230 return Result{0, 0, 0}, nil
1231 }
1232
1233 trimmedLen := 0
1234 if !unicode.IsSpace(pattern[0]) {
1235 trimmedLen = text.LeadingWhitespaces()
1236 }
1237
1238 if text.Length()-trimmedLen < len(pattern) {
1239 return Result{-1, -1, 0}, nil
1240 }
1241
1242 for index, r := range pattern {
1243 char := text.Get(trimmedLen + index)
1244 if !caseSensitive {
1245 char = unicode.ToLower(char)
1246 }
1247 if normalize {
1248 char = normalizeRune(char)
1249 }
1250 if char != r {
1251 return Result{-1, -1, 0}, nil
1252 }
1253 }
1254 lenPattern := len(pattern)
1255 score, _ := calculateScore(caseSensitive, normalize, text, pattern, trimmedLen, trimmedLen+lenPattern, false)
1256 return Result{trimmedLen, trimmedLen + lenPattern, score}, nil
1257 }
1258
1259 // SuffixMatch performs suffix-match
1260 func SuffixMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1261 lenRunes := text.Length()
1262 trimmedLen := lenRunes
1263 if len(pattern) == 0 || !unicode.IsSpace(pattern[len(pattern)-1]) {
1264 trimmedLen -= text.TrailingWhitespaces()
1265 }
1266 if len(pattern) == 0 {
1267 return Result{trimmedLen, trimmedLen, 0}, nil
1268 }
1269 diff := trimmedLen - len(pattern)
1270 if diff < 0 {
1271 return Result{-1, -1, 0}, nil
1272 }
1273
1274 for index, r := range pattern {
1275 char := text.Get(index + diff)
1276 if !caseSensitive {
1277 char = unicode.ToLower(char)
1278 }
1279 if normalize {
1280 char = normalizeRune(char)
1281 }
1282 if char != r {
1283 return Result{-1, -1, 0}, nil
1284 }
1285 }
1286 lenPattern := len(pattern)
1287 sidx := trimmedLen - lenPattern
1288 eidx := trimmedLen
1289 score, _ := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false)
1290 return Result{sidx, eidx, score}, nil
1291 }
1292
1293 // EqualMatch performs equal-match
1294 func EqualMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
1295 lenPattern := len(pattern)
1296 if lenPattern == 0 {
1297 return Result{-1, -1, 0}, nil
1298 }
1299
1300 // Strip leading whitespaces
1301 trimmedLen := 0
1302 if !unicode.IsSpace(pattern[0]) {
1303 trimmedLen = text.LeadingWhitespaces()
1304 }
1305
1306 // Strip trailing whitespaces
1307 trimmedEndLen := 0
1308 if !unicode.IsSpace(pattern[lenPattern-1]) {
1309 trimmedEndLen = text.TrailingWhitespaces()
1310 }
1311
1312 if text.Length()-trimmedLen-trimmedEndLen != lenPattern {
1313 return Result{-1, -1, 0}, nil
1314 }
1315 match := true
1316 if normalize {
1317 runes := text.ToRunes()
1318 for idx, pchar := range pattern {
1319 char := runes[trimmedLen+idx]
1320 if !caseSensitive {
1321 char = unicode.To(unicode.LowerCase, char)
1322 }
1323 if normalizeRune(pchar) != normalizeRune(char) {
1324 match = false
1325 break
1326 }
1327 }
1328 } else {
1329 runes := text.ToRunes()
1330 runesStr := string(runes[trimmedLen : len(runes)-trimmedEndLen])
1331 if !caseSensitive {
1332 runesStr = strings.ToLower(runesStr)
1333 }
1334 match = runesStr == string(pattern)
1335 }
1336 if match {
1337 return Result{trimmedLen, trimmedLen + lenPattern, (scoreMatch+int(bonusBoundaryWhite))*lenPattern +
1338 (bonusFirstCharMultiplier-1)*int(bonusBoundaryWhite)}, nil
1339 }
1340 return Result{-1, -1, 0}, nil
1341 }