algo.go
This file
Path
src/algo/algo.go
1,341 lines · 36.3 KiB · Go
Last changed by
Clean up comments and testsJunegunn Choibefore adoption2885df8
History of this fileTake it
1package algo23/*45Algorithm6---------78FuzzyMatchV1 finds the first "fuzzy" occurrence of the pattern within the given9text in O(n) time where n is the length of the text. Once the position of the10last character is located, it traverses backwards to see if there's a shorter11substring that matches the pattern.1213 a_____b___abc__ To find "abc"14 *-----*-----*> 1. Forward scan15 <*** 2. Backward scan1617The algorithm is simple and fast, but as it only sees the first occurrence,18it is not guaranteed to find the occurrence with the highest score.1920 a_____b__c__abc21 *-----*--* ***2223FuzzyMatchV2 implements a modified version of Smith-Waterman algorithm to find24the optimal solution (highest score) according to the scoring criteria. Unlike25the original algorithm, omission or mismatch of a character in the pattern is26not allowed.2728Performance29-----------3031The new V2 algorithm is slower than V1 as it examines all occurrences of the32pattern instead of stopping immediately after finding the first one. The time33complexity of the algorithm is O(nm) if a match is found and O(n) otherwise34where n is the length of the item and m is the length of the pattern. Thus, the35performance overhead may not be noticeable for a query with high selectivity.36However, if the performance is more important than the quality of the result,37you can still choose v1 algorithm with --algo=v1.3839Scoring criteria40----------------4142- We prefer matches at special positions, such as the start of a word, or43 uppercase character in camelCase words.4445- That is, we prefer an occurrence of the pattern with more characters46 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 special50 positions, the bonus point for the position is multiplied by a constant51 as it is extremely likely that the first character in the typed pattern52 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 also56 consider the total length of the matched substring. This is why we have the57 gap penalty. The gap penalty increases as the length of the gap (distance58 between the matching characters) increases, so the effect of the bonus is59 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 bonus63 and the gap penalty. The parameters were chosen that the bonus is cancelled64 when the gap size increases beyond 8 characters.6566- The bonus mechanism can have the undesirable side effect where consecutive67 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 character71 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 the75 first character in the chunk.76 e.g. "foobar" vs. "out-of-bound" on "oob"77 ````````````78*/7980import (81 "bytes"82 "fmt"83 "os"84 "strings"85 "unicode"86 "unicode/utf8"8788 "github.com/junegunn/fzf/src/util"89)9091var DEBUG bool9293var delimiterChars = "/,:;|"9495const whiteChars = " \t\n\v\f\r\x85\xA0"9697func indexAt(index int, max int, forward bool) int {98 if forward {99 return index100 }101 return max - index - 1102}103104// Result contains the results of running a match function.105type Result struct {106 // TODO int32 should suffice107 Start int108 End int109 Score int110}111112const (113 scoreMatch = 16114 scoreGapStart = -3115 scoreGapExtension = -1116117 // We prefer matches at the beginning of a word, but the bonus should not be118 // too great to prevent the longer acronym matches from always winning over119 // shorter fuzzy matches. The bonus point here was specifically chosen that120 // the bonus is cancelled when the gap between the acronyms grows over121 // 8 characters, which is approximately the average length of the words found122 // in web2 dictionary and my file system.123 bonusBoundary = scoreMatch / 2124125 // Although bonus point for non-word characters is non-contextual, we need it126 // for computing bonus points for consecutive chunks starting with a non-word127 // character.128 bonusNonWord = scoreMatch / 2129130 // Edge-triggered bonus for matches in camelCase words.131 // Compared to word-boundary case, they don't accompany single-character gaps132 // (e.g. FooBar vs. foo-bar), so we deduct bonus point accordingly.133 bonusCamel123 = bonusBoundary + scoreGapExtension134135 // Minimum bonus point given to characters in consecutive chunks.136 // Note that bonus points for consecutive matches shouldn't have needed if we137 // used fixed match score as in the original algorithm.138 bonusConsecutive = -(scoreGapStart + scoreGapExtension)139140 // The first character in the typed pattern usually has more significance141 // than the rest so it's important that it appears at special positions where142 // 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 is144 // still respected.145 bonusFirstCharMultiplier = 2146)147148var (149 // Extra bonus for word boundary after whitespace character or beginning of the string150 bonusBoundaryWhite int16 = bonusBoundary + 2151152 // Extra bonus for word boundary after slash, colon, semi-colon, and comma153 bonusBoundaryDelimiter int16 = bonusBoundary + 1154155 initialCharClass = charWhite156157 // A minor optimization that can give 15%+ performance boost158 asciiCharClasses [unicode.MaxASCII + 1]charClass159160 // A minor optimization that can give yet another 5% performance boost161 bonusMatrix [charNumber + 1][charNumber + 1]int16162)163164type charClass int165166const (167 charWhite charClass = iota168 charNonWord169 charDelimiter170 charLower171 charUpper172 charLetter173 charNumber174)175176func Init(scheme string) bool {177 switch scheme {178 case "default":179 bonusBoundaryWhite = bonusBoundary + 2180 bonusBoundaryDelimiter = bonusBoundary + 1181 case "path":182 bonusBoundaryWhite = bonusBoundary183 bonusBoundaryDelimiter = bonusBoundary + 1184 if os.PathSeparator == '/' {185 delimiterChars = "/"186 } else {187 delimiterChars = string([]rune{os.PathSeparator, '/'})188 }189 initialCharClass = charDelimiter190 case "history":191 bonusBoundaryWhite = bonusBoundary192 bonusBoundaryDelimiter = bonusBoundary193 default:194 return false195 }196 for i := 0; i <= unicode.MaxASCII; i++ {197 char := rune(i)198 c := charNonWord199 if char >= 'a' && char <= 'z' {200 c = charLower201 } else if char >= 'A' && char <= 'Z' {202 c = charUpper203 } else if char >= '0' && char <= '9' {204 c = charNumber205 } else if strings.ContainsRune(whiteChars, char) {206 c = charWhite207 } else if strings.ContainsRune(delimiterChars, char) {208 c = charDelimiter209 }210 asciiCharClasses[i] = c211 }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 true218}219220func posArray(withPos bool, len int) *[]int {221 if withPos {222 pos := make([]int, 0, len)223 return &pos224 }225 return nil226}227228func 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, slice232 }233 return offset, make([]int16, size)234}235236func 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, slice240 }241 return offset, make([]int32, size)242}243244func charClassOfNonAscii(char rune) charClass {245 if unicode.IsLower(char) {246 return charLower247 } else if unicode.IsUpper(char) {248 return charUpper249 } else if unicode.IsNumber(char) {250 return charNumber251 } else if unicode.IsLetter(char) {252 return charLetter253 } else if unicode.IsSpace(char) {254 return charWhite255 } else if strings.ContainsRune(delimiterChars, char) {256 return charDelimiter257 }258 return charNonWord259}260261func charClassOf(char rune) charClass {262 if char <= unicode.MaxASCII {263 return asciiCharClasses[char]264 }265 return charClassOfNonAscii(char)266}267268func bonusFor(prevClass charClass, class charClass) int16 {269 if class >= charNonWord {270 switch prevClass {271 case charWhite:272 // Word boundary after whitespace273 return bonusBoundaryWhite274 case charDelimiter:275 // Word boundary after a delimiter character276 return bonusBoundaryDelimiter277 case charNonWord:278 // Word boundary279 return bonusBoundary280 }281 }282283 if prevClass == charLower && class == charUpper ||284 prevClass != charNumber && class == charNumber {285 // camelCase letter123286 return bonusCamel123287 }288289 switch class {290 case charNonWord, charDelimiter:291 return bonusNonWord292 case charWhite:293 return bonusBoundaryWhite294 }295 return 0296}297298func bonusAt(input *util.Chars, idx int) int16 {299 if idx == 0 {300 return bonusBoundaryWhite301 }302 return bonusMatrix[charClassOf(input.Get(idx-1))][charClassOf(input.Get(idx))]303}304305func normalizeRune(r rune) rune {306 // Every key of the map folds to ASCII, so a rune the bitmap rejects cannot307 // be in it. TestNormalizedKeysAreFlagged verifies that.308 if !util.MayFoldToAscii(r) {309 return r310 }311312 n := normalized[r]313 if n > 0 {314 return n315 }316 return r317}318319// Algo functions make two assumptions320// 1. "pattern" is given in lowercase if "caseSensitive" is false321// 2. "pattern" is already normalized if "normalize" is true322type Algo func(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int)323324func 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 pass327 if !caseSensitive && b >= 'a' && b <= 'z' {328 idx := IndexByteTwo(byteArray, b, b-32)329 if idx < 0 {330 return -1331 }332 return from + idx333 }334 idx := bytes.IndexByte(byteArray, b)335 if idx < 0 {336 return -1337 }338 return from + idx339}340341func isAscii(runes []rune) bool {342 for _, r := range runes {343 if r >= utf8.RuneSelf {344 return false345 }346 }347 return true348}349350// runePrefilterable reports whether scanning the rune array can decide this351// pattern against this item without missing a match. Phase 2 lowercases an352// uppercase text rune and then normalizes it, and the scan sees neither353// transform, so every pattern rune must be unreachable by them.354func 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 char357 for _, r := range pattern {358 if r < utf8.RuneSelf {359 return false360 }361 }362 }363 if caseSensitive {364 // No case transform is applied, and normalization only ever produces365 // ASCII, so nothing can reach a non-ASCII pattern rune366 return true367 }368 for _, r := range pattern {369 // Another rune must not lowercase onto this one. Being uncased is not370 // enough by itself: U+00DF has no simple uppercase yet U+1E9E371 // 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 false375 }376 }377 return true378}379380// runeFuzzyIndex is asciiFuzzyIndex for rune-mode input. Only valid when381// runePrefilterable says so.382func runeFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) {383 runes := input.Runes()384 firstIdx, idx, lastIdx := 0, 0, 0385 var last rune386 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, -1395 }396 if pidx == 0 && idx > 0 {397 // Step back to find the right bonus point398 firstIdx = idx - 1399 }400 lastIdx = idx401 idx++402 }403404 // Find the last appearance of the last character of the pattern to limit405 // the search scope406 if lastIdx+1 < len(runes) {407 var end int408 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 + 1415 }416 }417 return firstIdx, lastIdx + 1418}419420func 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 of426 // it: an ASCII pattern against an item that cannot fold to ASCII is427 // 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 }435436 // Not possible437 if !isAscii(pattern) {438 return -1, -1439 }440441 firstIdx, idx, lastIdx := 0, 0, 0442 var b byte443 for pidx := range pattern {444 b = byte(pattern[pidx])445 idx = trySkip(input, caseSensitive, b, idx)446 if idx < 0 {447 return -1, -1448 }449 if pidx == 0 && idx > 0 {450 // Step back to find the right bonus point451 firstIdx = idx - 1452 }453 lastIdx = idx454 idx++455 }456457 // Find the last appearance of the last character of the pattern to limit the search scope458 scope := input.Bytes()[lastIdx:]459 if len(scope) > 1 {460 tail := scope[1:]461 var end int462 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 + 1469 }470 }471 return firstIdx, lastIdx + 1472}473474func debugV2(T []rune, pattern []rune, F []int32, lastIdx int, H []int16, C []int16) {475 width := lastIdx - int(F[0]) + 1476477 for i, f := range F {478 I := i * width479 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()494495 fmt.Print(" ")496 for idx, p := range C[I : I+width] {497 if idx+int(F[0]) < int(F[i]) {498 p = 0499 }500 if p > 0 {501 fmt.Printf("%2d ", p)502 } else {503 fmt.Print(" ")504 }505 }506 fmt.Println()507 }508}509510// fuzzyMatchV2Single is a fast path for a single-character ASCII pattern on511// ASCII input. Same scoring and tiebreaks as Phase 2 of FuzzyMatchV2, but512// jumps between occurrences instead of scanning every character, and513// allocates no arrays.514func fuzzyMatchV2Single(caseSensitive bool, forward bool, input *util.Chars, b byte, withPos bool) (Result, *[]int) {515 byteArray := input.Bytes()516 maxScore, maxScorePos := int16(0), -1517 for idx := 0; idx < len(byteArray); {518 idx = trySkip(input, caseSensitive, b, idx)519 if idx < 0 {520 break521 }522 class := asciiCharClasses[byteArray[idx]]523 prevClass := initialCharClass524 if idx > 0 {525 prevClass = asciiCharClasses[byteArray[idx-1]]526 }527 bonus := bonusMatrix[prevClass][class]528 score := scoreMatch + bonus*bonusFirstCharMultiplier529 if forward && score > maxScore || !forward && score >= maxScore {530 maxScore, maxScorePos = score, idx531 if forward && bonus >= bonusBoundary {532 break533 }534 }535 idx++536 }537 if maxScorePos < 0 {538 return Result{-1, -1, 0}, nil539 }540 result := Result{maxScorePos, maxScorePos + 1, int(maxScore)}541 if !withPos {542 return result, nil543 }544 pos := []int{maxScorePos}545 return result, &pos546}547548// Test hooks: force the general path instead of a fast path, so the two can549// be compared for equivalence.550var (551 disableSingle bool552 disableTwo bool553 disableRunePrefilter bool554)555556// fuzzyMatchV2Two is a fused fast path for a two-character ASCII pattern on557// ASCII input. It replicates Phase 2 (row 0) and Phase 3 (row 1) of558// FuzzyMatchV2 in a single pass, carrying the row-0 diagonal/left values and559// 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 can561// recover the matched character positions, exactly as the general Phase 4.562func 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 - minIdx565566 // Row storage, only needed for the backtrace567 var H0, C0, H1, C1 []int16568 if withPos {569 o := 0570 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 }575576 maxScore, maxScorePos := int16(0), 0577 prevClass := initialCharClass578579 // Subsequence tracking (equivalent to F[0], F[1] in Phase 2). The scope580 // from asciiFuzzyIndex ends exactly at the last pchar1, so row 1's upper581 // bound (Phase 3 lastIdx) is the final loop position; no separate var.582 f0, f1 := -1, -1583584 // Row 0 running state at the previous position585 var h0Prev, c0Prev, bPrev int16586 inGap0 := false587588 // Row 1 running state589 var h1Prev int16590 inGap1 := false591592 for off := range N {593 pos := minIdx + off594 b := sl[pos]595 class := asciiCharClasses[b]596 lb := b597 if !caseSensitive && b >= 'A' && b <= 'Z' {598 lb = b + 32599 }600 bonus := bonusMatrix[prevClass][class]601 prevClass = class602603 // Subsequence advance: pchar0 then pchar1604 if f0 < 0 {605 if lb == pchar0 {606 f0 = off607 }608 } else if lb == pchar1 && f1 < 0 {609 f1 = off610 }611612 // Row 0 (pchar0)613 var h0Cur, c0Cur int16614 if lb == pchar0 {615 h0Cur = scoreMatch + bonus*bonusFirstCharMultiplier616 c0Cur = 1617 inGap0 = false618 } else {619 if inGap0 {620 h0Cur = max(h0Prev+scoreGapExtension, 0)621 } else {622 h0Cur = max(h0Prev+scoreGapStart, 0)623 }624 c0Cur = 0625 inGap0 = true626 }627 if withPos {628 H0[off], C0[off] = h0Cur, c0Cur629 }630631 // Row 1 (pchar1), only within [f1, lastIdx]632 if f1 >= 0 && off >= f1 {633 var s1, s2, consecutive int16634 hleft := h1Prev635 if off == f1 {636 hleft = 0637 }638 if inGap1 {639 s2 = hleft + scoreGapExtension640 } else {641 s2 = hleft + scoreGapStart642 }643 if lb == pchar1 {644 s1 = h0Prev + scoreMatch645 bb := bonus646 consecutive = c0Prev + 1647 if consecutive > 1 {648 fb := bPrev649 if bb >= bonusBoundary && bb > fb {650 consecutive = 1651 } else {652 bb = max(bb, bonusConsecutive, fb)653 }654 }655 if s1+bb < s2 {656 s1 += bonus657 consecutive = 0658 } else {659 s1 += bb660 }661 }662 inGap1 = s1 < s2663 score := max(s1, s2, 0)664 if forward && score > maxScore || !forward && score >= maxScore {665 maxScore, maxScorePos = score, off666 }667 h1Prev = score668 if withPos {669 H1[off], C1[off] = score, consecutive670 }671 }672673 h0Prev, c0Prev, bPrev = h0Cur, c0Cur, bonus674 }675676 if f1 < 0 {677 return Result{-1, -1, 0}, nil678 }679 if !withPos {680 return Result{minIdx + f0, minIdx + maxScorePos + 1, int(maxScore)}, nil681 }682683 // Phase 4 backtrace, specialized to two rows. Mirrors the general loop:684 // record a cell when it dominates its diagonal and left neighbors, then685 // step up a row; otherwise step left. preferMatch breaks score ties and686 // must not read row 1 left of f1 (unwritten, possibly stale slab data).687 pos := posArray(true, 2)688 i := 1689 j := maxScorePos690 preferMatch := true691 for {692 var s, s1, s2, cCur int16693 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 := i708 if s > s1 && (s > s2 || s == s2 && preferMatch) {709 *pos = append(*pos, j+minIdx)710 if i == 0 {711 break712 }713 i--714 }715 preferMatch = cCur > 1 ||716 row == 0 && j < N-1 && j+1 >= f1 && C1[j+1] > 0717 j--718 }719 return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos720}721722func 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 in726 // 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}, nil734 }735736 // 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 integer739 // 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 }743744 // Single-character ASCII pattern needs neither the prefilter nor the745 // score matrix746 if !disableSingle && M == 1 && input.IsBytes() && pattern[0] < utf8.RuneSelf {747 return fuzzyMatchV2Single(caseSensitive, forward, input, byte(pattern[0]), withPos)748 }749750 // Phase 1. Optimized search for ASCII string751 minIdx, maxIdx := asciiFuzzyIndex(input, pattern, caseSensitive)752 if minIdx < 0 {753 return Result{-1, -1, 0}, nil754 }755 // fmt.Println(N, maxIdx, idx, maxIdx-idx, input.ToString())756 N = maxIdx - minIdx757758 // Two-character ASCII pattern: rows 0 and 1 collapse to scalar running759 // state, so the general score arrays are unnecessary760 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 }764765 // Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages766 offset16 := 0767 offset32 := 0768 offset16, H0 := alloc16(offset16, slab, N)769 offset16, C0 := alloc16(offset16, slab, N)770 // Bonus point for each position771 offset16, B := alloc16(offset16, slab, N)772 // The first occurrence of each character in the pattern773 offset32, F := alloc32(offset32, slab, M)774 // Rune array775 _, T := alloc32(offset32, slab, N)776 input.CopyRunes(T, minIdx)777778 // Phase 2. Calculate bonus for each point779 maxScore, maxScorePos := int16(0), 0780 pidx, lastIdx := 0, 0781 pchar0, pchar, prevH0, prevClass, inGap := pattern[0], pattern[0], int16(0), initialCharClass, false782 for off, char := range T {783 var class charClass784 if char <= unicode.MaxASCII {785 class = asciiCharClasses[char]786 if !caseSensitive && class == charUpper {787 char += 32788 T[off] = char789 }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] = char799 }800801 bonus := bonusMatrix[prevClass][class]802 B[off] = bonus803 prevClass = class804805 if char == pchar {806 if pidx < M {807 F[pidx] = int32(off)808 pidx++809 pchar = pattern[min(pidx, M-1)]810 }811 lastIdx = off812 }813814 if char == pchar0 {815 score := scoreMatch + bonus*bonusFirstCharMultiplier816 H0[off] = score817 C0[off] = 1818 if M == 1 && (forward && score > maxScore || !forward && score >= maxScore) {819 maxScore, maxScorePos = score, off820 if forward && bonus >= bonusBoundary {821 break822 }823 }824 inGap = false825 } else {826 if inGap {827 H0[off] = max(prevH0+scoreGapExtension, 0)828 } else {829 H0[off] = max(prevH0+scoreGapStart, 0)830 }831 C0[off] = 0832 inGap = true833 }834 prevH0 = H0[off]835 }836 if pidx != M {837 return Result{-1, -1, 0}, nil838 }839 if M == 1 {840 result := Result{minIdx + maxScorePos, minIdx + maxScorePos + 1, int(maxScore)}841 if !withPos {842 return result, nil843 }844 pos := []int{minIdx + maxScorePos}845 return result, &pos846 }847848 // 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 + 1852 offset16, H := alloc16(offset16, slab, width*M)853 copy(H, H0[f0:lastIdx+1])854855 // Possible length of consecutive chunk at each position.856 _, C := alloc16(offset16, slab, width*M)857 copy(C, C0[f0:lastIdx+1])858859 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 + 1865 row := pidx * width866 inGap := false867 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] = 0875 for off, char := range Tsub {876 col := off + f877 var s1, s2, consecutive int16878879 if inGap {880 s2 = Hleft[off] + scoreGapExtension881 } else {882 s2 = Hleft[off] + scoreGapStart883 }884885 if pchar == char {886 s1 = Hdiag[off] + scoreMatch887 b := Bsub[off]888 consecutive = Cdiag[off] + 1889 if consecutive > 1 {890 fb := B[col-int(consecutive)+1]891 // Break consecutive chunk892 if b >= bonusBoundary && b > fb {893 consecutive = 1894 } else {895 b = max(b, bonusConsecutive, fb)896 }897 }898 if s1+b < s2 {899 s1 += Bsub[off]900 consecutive = 0901 } else {902 s1 += b903 }904 }905 Csub[off] = consecutive906907 inGap = s1 < s2908 score := max(s1, s2, 0)909 if pidx == M-1 && (forward && score > maxScore || !forward && score >= maxScore) {910 maxScore, maxScorePos = score, col911 }912 Hsub[off] = score913 }914 }915916 if DEBUG {917 debugV2(T, pattern, F, lastIdx, H, C)918 }919920 // Phase 4. (Optional) Backtrace to find character positions921 pos := posArray(withPos, M)922 j := f0923 if withPos {924 i := M - 1925 j = maxScorePos926 preferMatch := true927 for {928 I := i * width929 j0 := j - f0930 s := H[I+j0]931932 var s1, s2 int16933 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 }939940 row := i941 if s > s1 && (s > s2 || s == s2 && preferMatch) {942 *pos = append(*pos, j+minIdx)943 if i == 0 {944 break945 }946 i--947 }948 // Row below is only written from column F[row+1]; don't read949 // stale slab data left of it950 preferMatch = C[I+j0] > 1 ||951 row+1 < M && j < lastIdx && int32(j+1) >= F[row+1] && C[I+width+j0+1] > 0952 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't957 // want to pay extra cost for the option that has lost its importance.958 return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos959}960961// Implement the same sorting criteria as V2962func 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 := initialCharClass966 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 += 32975 } else if char > unicode.MaxASCII {976 char = unicode.To(unicode.LowerCase, char)977 }978 }979 // pattern is already normalized980 if normalize {981 char = normalizeRune(char)982 }983 if char == pattern[pidx] {984 if withPos {985 *pos = append(*pos, idx)986 }987 score += scoreMatch988 bonus := bonusMatrix[prevClass][class]989 if consecutive == 0 {990 firstBonus = bonus991 } else {992 // Break consecutive chunk993 if bonus >= bonusBoundary && bonus > firstBonus {994 firstBonus = bonus995 }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 = false1004 consecutive++1005 pidx++1006 } else {1007 if inGap {1008 score += scoreGapExtension1009 } else {1010 score += scoreGapStart1011 }1012 inGap = true1013 consecutive = 01014 firstBonus = 01015 }1016 prevClass = class1017 }1018 return score, pos1019}10201021// FuzzyMatchV1 performs fuzzy-match1022func 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}, nil1025 }1026 idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive)1027 if idx < 0 {1028 return Result{-1, -1, 0}, nil1029 }10301031 pidx := 01032 sidx := -11033 eidx := -110341035 lenRunes := text.Length()1036 lenPattern := len(pattern)10371038 for index := range lenRunes {1039 char := text.Get(indexAt(index, lenRunes, forward))1040 // This is considerably faster than blindly applying strings.ToLower to the1041 // whole string1042 if !caseSensitive {1043 // Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable1044 // difference in CPU cost. (Measured on Go 1.4.1. Also note that the Go1045 // compiler as of now does not inline non-leaf functions.)1046 if char >= 'A' && char <= 'Z' {1047 char += 321048 } 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 = index1059 }1060 if pidx++; pidx == lenPattern {1061 eidx = index + 11062 break1063 }1064 }1065 }10661067 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 += 321075 } else if char > unicode.MaxASCII {1076 char = unicode.To(unicode.LowerCase, char)1077 }1078 }1079 if normalize {1080 char = normalizeRune(char)1081 }10821083 pidx_ := indexAt(pidx, lenPattern, forward)1084 pchar := pattern[pidx_]1085 if char == pchar {1086 if pidx--; pidx < 0 {1087 sidx = index1088 break1089 }1090 }1091 }10921093 if !forward {1094 sidx, eidx = lenRunes-eidx, lenRunes-sidx1095 }10961097 score, pos := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos)1098 return Result{sidx, eidx, score}, pos1099 }1100 return Result{-1, -1, 0}, nil1101}11021103// ExactMatchNaive is a basic string searching algorithm that handles case1104// sensitivity. Although naive, it still performs better than the combination1105// of strings.ToLower + strings.Index for typical fzf use cases where input1106// strings and patterns are not very long.1107//1108// Since 0.15.0, this function searches for the match with the highest1109// bonus point, instead of stopping immediately after finding the first match.1110// The solution is much cheaper since there is only one possible alignment of1111// the pattern.1112func 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}11151116func 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}11191120func 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}, nil1123 }11241125 lenRunes := text.Length()1126 lenPattern := len(pattern)11271128 if lenRunes < lenPattern {1129 return Result{-1, -1, 0}, nil1130 }11311132 idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive)1133 if idx < 0 {1134 return Result{-1, -1, 0}, nil1135 }11361137 // For simplicity, only look at the bonus at the first character position1138 pidx := 01139 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 += 321146 } 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 == char1156 if ok {1157 if pidx_ == 0 {1158 bonus = bonusAt(text, index_)1159 }1160 if boundaryCheck {1161 if forward && pidx_ == 0 {1162 bbonus = bonus1163 } else if !forward && pidx_ == lenPattern-1 {1164 if index_ < lenRunes-1 {1165 bbonus = bonusAt(text, index_+1)1166 } else {1167 bbonus = bonusBoundaryWhite1168 }1169 }1170 ok = bbonus >= bonusBoundary1171 if ok && pidx_ == 0 {1172 ok = index_ == 0 || charClassOf(text.Get(index_-1)) <= charDelimiter1173 }1174 if ok && pidx_ == len(pattern)-1 {1175 ok = index_ == lenRunes-1 || charClassOf(text.Get(index_+1)) <= charDelimiter1176 }1177 }1178 }1179 if ok {1180 pidx++1181 if pidx == lenPattern {1182 if bonus > bestBonus {1183 bestPos, bestBonus = index, bonus1184 }1185 if bonus >= bonusBoundary {1186 break1187 }1188 index -= pidx - 11189 pidx, bonus = 0, 01190 }1191 } else {1192 index -= pidx1193 pidx, bonus = 0, 01194 }1195 }1196 if bestPos >= 0 {1197 var sidx, eidx int1198 if forward {1199 sidx = bestPos - lenPattern + 11200 eidx = bestPos + 11201 } else {1202 sidx = lenRunes - (bestPos + 1)1203 eidx = lenRunes - (bestPos - lenPattern + 1)1204 }1205 var score int1206 if boundaryCheck {1207 // Underscore boundaries should be ranked lower than the other types of boundaries1208 score = int(bonus)1209 deduct := int(bonus-bonusBoundary) + 11210 if sidx > 0 && text.Get(sidx-1) == '_' {1211 score -= deduct + 11212 deduct = 11213 }1214 if eidx < lenRunes && text.Get(eidx) == '_' {1215 score -= deduct1216 }1217 // Add base score so that this can compete with other match types e.g. 'foo' | bar1218 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}, nil1223 }1224 return Result{-1, -1, 0}, nil1225}12261227// PrefixMatch performs prefix-match1228func 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}, nil1231 }12321233 trimmedLen := 01234 if !unicode.IsSpace(pattern[0]) {1235 trimmedLen = text.LeadingWhitespaces()1236 }12371238 if text.Length()-trimmedLen < len(pattern) {1239 return Result{-1, -1, 0}, nil1240 }12411242 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}, nil1252 }1253 }1254 lenPattern := len(pattern)1255 score, _ := calculateScore(caseSensitive, normalize, text, pattern, trimmedLen, trimmedLen+lenPattern, false)1256 return Result{trimmedLen, trimmedLen + lenPattern, score}, nil1257}12581259// SuffixMatch performs suffix-match1260func 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 := lenRunes1263 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}, nil1268 }1269 diff := trimmedLen - len(pattern)1270 if diff < 0 {1271 return Result{-1, -1, 0}, nil1272 }12731274 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}, nil1284 }1285 }1286 lenPattern := len(pattern)1287 sidx := trimmedLen - lenPattern1288 eidx := trimmedLen1289 score, _ := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false)1290 return Result{sidx, eidx, score}, nil1291}12921293// EqualMatch performs equal-match1294func 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}, nil1298 }12991300 // Strip leading whitespaces1301 trimmedLen := 01302 if !unicode.IsSpace(pattern[0]) {1303 trimmedLen = text.LeadingWhitespaces()1304 }13051306 // Strip trailing whitespaces1307 trimmedEndLen := 01308 if !unicode.IsSpace(pattern[lenPattern-1]) {1309 trimmedEndLen = text.TrailingWhitespaces()1310 }13111312 if text.Length()-trimmedLen-trimmedEndLen != lenPattern {1313 return Result{-1, -1, 0}, nil1314 }1315 match := true1316 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 = false1325 break1326 }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)}, nil1339 }1340 return Result{-1, -1, 0}, nil1341}