Skip to content
Myr

Revise ranking algorithm

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Junegunn Choi · committed by Junegunn Choi · parent 8ef2420 · Browse files · 20 files+943 added−442 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

20 files+943 added−442 removed

  • tests:+70 added−152 removed
  • other:+873 added−290 removed

20 files+943 added−442 removed

modified:man/man1/fzf-tmux.1+1 added-1 removed
19 unmodified lines
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22THE SOFTWARE.23..24.TH fzf-tmux 1 "Aug 2016" "fzf 0.13.5" "fzf-tmux - open fzf in tmux split pane"24.TH fzf-tmux 1 "Sep 2016" "fzf 0.15.0" "fzf-tmux - open fzf in tmux split pane"2526.SH NAME27fzf-tmux - open fzf in tmux split pane28
26 unmodified lines
modified:man/man1/fzf.1+11 added-1 removed
19 unmodified lines
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22THE SOFTWARE.23..24.TH fzf 1 "Aug 2016" "fzf 0.13.5" "fzf - a command-line fuzzy finder"24.TH fzf 1 "Sep 2016" "fzf 0.15.0" "fzf - a command-line fuzzy finder"2526.SH NAME27fzf - a command-line fuzzy finder28
18 unmodified lines
47.TP48.B "+i"49Case-sensitive match50.TP51.BI "--algo=" TYPE52Fuzzy matching algorithm (default: v2)5354.br55.BR v2 " Optimal scoring algorithm (quality)"56.br57.BR v1 " Faster but not guaranteed to find the optimal result (performance)"58.br5960.TP61.BI "-n, --nth=" "N[,..]"62Comma-separated list of field index expressions for limiting search scope.63See \fBFIELD INDEX EXPRESSION\fR for the details.64.TP
435 unmodified lines
modified:src/algo/algo_test.go+101 added-42 removed
1package algo23import (4 "sort"5 "strings"6 "testing"78 "github.com/junegunn/fzf/src/util"9)1010func assertMatch(t *testing.T, fun func(bool, bool, util.Chars, []rune) Result, caseSensitive, forward bool, input, pattern string, sidx int, eidx int, bonus int) {11func assertMatch(t *testing.T, fun Algo, caseSensitive, forward bool, input, pattern string, sidx int, eidx int, score int) {12 if !caseSensitive {13 pattern = strings.ToLower(pattern)14 }14 res := fun(caseSensitive, forward, util.RunesToChars([]rune(input)), []rune(pattern))15 if res.Start != sidx {16 t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", res.Start, sidx, input, pattern)15 res, pos := fun(caseSensitive, forward, util.RunesToChars([]rune(input)), []rune(pattern), true, nil)16 var start, end int17 if pos == nil || len(*pos) == 0 {18 start = res.Start19 end = res.End20 } else {21 sort.Ints(*pos)22 start = (*pos)[0]23 end = (*pos)[len(*pos)-1] + 124 }18 if res.End != eidx {19 t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", res.End, eidx, input, pattern)25 if start != sidx {26 t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", start, sidx, input, pattern)27 }21 if res.Bonus != bonus {22 t.Errorf("Invalid bonus: %d (expected: %d, %s / %s)", res.Bonus, bonus, input, pattern)28 if end != eidx {29 t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", end, eidx, input, pattern)30 }31 if res.Score != score {32 t.Errorf("Invalid score: %d (expected: %d, %s / %s)", res.Score, score, input, pattern)33 }34}3536func TestFuzzyMatch(t *testing.T) {27 assertMatch(t, FuzzyMatch, false, true, "fooBarbaz", "oBZ", 2, 9, 2)28 assertMatch(t, FuzzyMatch, false, true, "foo bar baz", "fbb", 0, 9, 8)29 assertMatch(t, FuzzyMatch, false, true, "/AutomatorDocument.icns", "rdoc", 9, 13, 4)30 assertMatch(t, FuzzyMatch, false, true, "/man1/zshcompctl.1", "zshc", 6, 10, 7)31 assertMatch(t, FuzzyMatch, false, true, "/.oh-my-zsh/cache", "zshc", 8, 13, 8)32 assertMatch(t, FuzzyMatch, false, true, "ab0123 456", "12356", 3, 10, 3)33 assertMatch(t, FuzzyMatch, false, true, "abc123 456", "12356", 3, 10, 5)37 for _, fn := range []Algo{FuzzyMatchV1, FuzzyMatchV2} {38 for _, forward := range []bool{true, false} {39 assertMatch(t, fn, false, forward, "fooBarbaz1", "oBZ", 2, 9,40 scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtention*3)41 assertMatch(t, fn, false, forward, "foo bar baz", "fbb", 0, 9,42 scoreMatch*3+bonusBoundary*bonusFirstCharMultiplier+43 bonusBoundary*2+2*scoreGapStart+4*scoreGapExtention)44 assertMatch(t, fn, false, forward, "/AutomatorDocument.icns", "rdoc", 9, 13,45 scoreMatch*4+bonusCamel123+bonusConsecutive*2)46 assertMatch(t, fn, false, forward, "/man1/zshcompctl.1", "zshc", 6, 10,47 scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*3)48 assertMatch(t, fn, false, forward, "/.oh-my-zsh/cache", "zshc", 8, 13,49 scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*3+scoreGapStart)50 assertMatch(t, fn, false, forward, "ab0123 456", "12356", 3, 10,51 scoreMatch*5+bonusConsecutive*3+scoreGapStart+scoreGapExtention)52 assertMatch(t, fn, false, forward, "abc123 456", "12356", 3, 10,53 scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+bonusConsecutive+scoreGapStart+scoreGapExtention)54 assertMatch(t, fn, false, forward, "foo/bar/baz", "fbb", 0, 9,55 scoreMatch*3+bonusBoundary*bonusFirstCharMultiplier+56 bonusBoundary*2+2*scoreGapStart+4*scoreGapExtention)57 assertMatch(t, fn, false, forward, "fooBarBaz", "fbb", 0, 7,58 scoreMatch*3+bonusBoundary*bonusFirstCharMultiplier+59 bonusCamel123*2+2*scoreGapStart+2*scoreGapExtention)60 assertMatch(t, fn, false, forward, "foo barbaz", "fbb", 0, 8,61 scoreMatch*3+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary+62 scoreGapStart*2+scoreGapExtention*3)63 assertMatch(t, fn, false, forward, "fooBar Baz", "foob", 0, 4,64 scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*3)65 assertMatch(t, fn, false, forward, "xFoo-Bar Baz", "foo-b", 1, 6,66 scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+67 bonusNonWord+bonusBoundary)6835 assertMatch(t, FuzzyMatch, false, true, "foo/bar/baz", "fbb", 0, 9, 8)36 assertMatch(t, FuzzyMatch, false, true, "fooBarBaz", "fbb", 0, 7, 6)37 assertMatch(t, FuzzyMatch, false, true, "foo barbaz", "fbb", 0, 8, 6)38 assertMatch(t, FuzzyMatch, false, true, "fooBar Baz", "foob", 0, 4, 8)39 assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBZ", -1, -1, 0)40 assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBz", 2, 9, 2)41 assertMatch(t, FuzzyMatch, true, true, "Foo Bar Baz", "fbb", -1, -1, 0)42 assertMatch(t, FuzzyMatch, true, true, "Foo/Bar/Baz", "FBB", 0, 9, 8)43 assertMatch(t, FuzzyMatch, true, true, "FooBarBaz", "FBB", 0, 7, 6)44 assertMatch(t, FuzzyMatch, true, true, "foo BarBaz", "fBB", 0, 8, 7)45 assertMatch(t, FuzzyMatch, true, true, "FooBar Baz", "FooB", 0, 4, 8)46 assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "fooBarbazz", -1, -1, 0)69 assertMatch(t, fn, true, forward, "fooBarbaz", "oBz", 2, 9,70 scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtention*3)71 assertMatch(t, fn, true, forward, "Foo/Bar/Baz", "FBB", 0, 9,72 scoreMatch*3+bonusBoundary*(bonusFirstCharMultiplier+2)+73 scoreGapStart*2+scoreGapExtention*4)74 assertMatch(t, fn, true, forward, "FooBarBaz", "FBB", 0, 7,75 scoreMatch*3+bonusBoundary*bonusFirstCharMultiplier+bonusCamel123*2+76 scoreGapStart*2+scoreGapExtention*2)77 assertMatch(t, fn, true, forward, "FooBar Baz", "FooB", 0, 4,78 scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*2+79 util.Max(bonusCamel123, bonusBoundary))8081 // Consecutive bonus updated82 assertMatch(t, fn, true, forward, "foo-bar", "o-ba", 2, 6,83 scoreMatch*4+bonusBoundary*3)8485 // Non-match86 assertMatch(t, fn, true, forward, "fooBarbaz", "oBZ", -1, -1, 0)87 assertMatch(t, fn, true, forward, "Foo Bar Baz", "fbb", -1, -1, 0)88 assertMatch(t, fn, true, forward, "fooBarbaz", "fooBarbazz", -1, -1, 0)89 }90 }91}9293func TestFuzzyMatchBackward(t *testing.T) {50 assertMatch(t, FuzzyMatch, false, true, "foobar fb", "fb", 0, 4, 4)51 assertMatch(t, FuzzyMatch, false, false, "foobar fb", "fb", 7, 9, 5)94 assertMatch(t, FuzzyMatchV1, false, true, "foobar fb", "fb", 0, 4,95 scoreMatch*2+bonusBoundary*bonusFirstCharMultiplier+96 scoreGapStart+scoreGapExtention)97 assertMatch(t, FuzzyMatchV1, false, false, "foobar fb", "fb", 7, 9,98 scoreMatch*2+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary)99}100101func TestExactMatchNaive(t *testing.T) {102 for _, dir := range []bool{true, false} {56 assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5, 3)103 assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "oBA", -1, -1, 0)104 assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "fooBarbazz", -1, -1, 0)10560 assertMatch(t, ExactMatchNaive, false, dir, "/AutomatorDocument.icns", "rdoc", 9, 13, 4)61 assertMatch(t, ExactMatchNaive, false, dir, "/man1/zshcompctl.1", "zshc", 6, 10, 7)62 assertMatch(t, ExactMatchNaive, false, dir, "/.oh-my-zsh/cache", "zsh/c", 8, 13, 10)106 assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5,107 scoreMatch*3+bonusCamel123+bonusConsecutive)108 assertMatch(t, ExactMatchNaive, false, dir, "/AutomatorDocument.icns", "rdoc", 9, 13,109 scoreMatch*4+bonusCamel123+bonusConsecutive*2)110 assertMatch(t, ExactMatchNaive, false, dir, "/man1/zshcompctl.1", "zshc", 6, 10,111 scoreMatch*4+bonusBoundary*(bonusFirstCharMultiplier+3))112 assertMatch(t, ExactMatchNaive, false, dir, "/.oh-my-zsh/cache", "zsh/c", 8, 13,113 scoreMatch*5+bonusBoundary*(bonusFirstCharMultiplier+4))114 }115}116117func TestExactMatchNaiveBackward(t *testing.T) {67 assertMatch(t, ExactMatchNaive, false, true, "foobar foob", "oo", 1, 3, 1)68 assertMatch(t, ExactMatchNaive, false, false, "foobar foob", "oo", 8, 10, 1)118 assertMatch(t, ExactMatchNaive, false, true, "foobar foob", "oo", 1, 3,119 scoreMatch*2+bonusConsecutive)120 assertMatch(t, ExactMatchNaive, false, false, "foobar foob", "oo", 8, 10,121 scoreMatch*2+bonusConsecutive)122}123124func TestPrefixMatch(t *testing.T) {125 score := (scoreMatch+bonusBoundary)*3 + bonusBoundary*(bonusFirstCharMultiplier-1)126127 for _, dir := range []bool{true, false} {128 assertMatch(t, PrefixMatch, true, dir, "fooBarbaz", "Foo", -1, -1, 0)129 assertMatch(t, PrefixMatch, false, dir, "fooBarBaz", "baz", -1, -1, 0)75 assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3, 6)76 assertMatch(t, PrefixMatch, false, dir, "foOBarBaZ", "foo", 0, 3, 7)77 assertMatch(t, PrefixMatch, false, dir, "f-oBarbaz", "f-o", 0, 3, 8)130 assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3, score)131 assertMatch(t, PrefixMatch, false, dir, "foOBarBaZ", "foo", 0, 3, score)132 assertMatch(t, PrefixMatch, false, dir, "f-oBarbaz", "f-o", 0, 3, score)133 }134}135136func TestSuffixMatch(t *testing.T) {137 for _, dir := range []bool{true, false} {83 assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1, 0)84 assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9, 2)85 assertMatch(t, SuffixMatch, false, dir, "fooBarBaZ", "baz", 6, 9, 5)138 assertMatch(t, SuffixMatch, true, dir, "fooBarbaz", "Baz", -1, -1, 0)139 assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1, 0)140141 assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9,142 scoreMatch*3+bonusConsecutive*2)143 assertMatch(t, SuffixMatch, false, dir, "fooBarBaZ", "baz", 6, 9,144 (scoreMatch+bonusCamel123)*3+bonusCamel123*(bonusFirstCharMultiplier-1))145 }146}147148func TestEmptyPattern(t *testing.T) {149 for _, dir := range []bool{true, false} {92 assertMatch(t, FuzzyMatch, true, dir, "foobar", "", 0, 0, 0)150 assertMatch(t, FuzzyMatchV1, true, dir, "foobar", "", 0, 0, 0)151 assertMatch(t, FuzzyMatchV2, true, dir, "foobar", "", 0, 0, 0)152 assertMatch(t, ExactMatchNaive, true, dir, "foobar", "", 0, 0, 0)153 assertMatch(t, PrefixMatch, true, dir, "foobar", "", 0, 0, 0)154 assertMatch(t, SuffixMatch, true, dir, "foobar", "", 6, 6, 0)155 }
1 unmodified line
modified:src/algo/algo.go+508 added-109 removed
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 "fmt"82 "strings"83 "unicode"8485 "github.com/junegunn/fzf/src/util"86)8710/*11 * String matching algorithms here do not use strings.ToLower to avoid12 * performance penalty. And they assume pattern runes are given in lowercase13 * letters when caseSensitive is false.14 *15 * In short: They try to do as little work as possible.16 */88var DEBUG bool8990func indexAt(index int, max int, forward bool) int {91 if forward {92 return index
2 unmodified lines
95}9697// Result contains the results of running a match function.98type Result struct {99 // TODO int32 should suffice100 Start int101 End int2930 // Items are basically sorted by the lengths of matched substrings.31 // But we slightly adjust the score with bonus for better results.32 Bonus int102 Score int103}104105const (106 scoreMatch = 16107 scoreGapStart = -3108 scoreGapExtention = -1109110 // We prefer matches at the beginning of a word, but the bonus should not be111 // too great to prevent the longer acronym matches from always winning over112 // shorter fuzzy matches. The bonus point here was specifically chosen that113 // the bonus is cancelled when the gap between the acronyms grows over114 // 8 characters, which is approximately the average length of the words found115 // in web2 dictionary and my file system.116 bonusBoundary = scoreMatch / 2117118 // Although bonus point for non-word characters is non-contextual, we need it119 // for computing bonus points for consecutive chunks starting with a non-word120 // character.121 bonusNonWord = scoreMatch / 2122123 // Edge-triggered bonus for matches in camelCase words.124 // Compared to word-boundary case, they don't accompany single-character gaps125 // (e.g. FooBar vs. foo-bar), so we deduct bonus point accordingly.126 bonusCamel123 = bonusBoundary + scoreGapExtention127128 // Minimum bonus point given to characters in consecutive chunks.129 // Note that bonus points for consecutive matches shouldn't have needed if we130 // used fixed match score as in the original algorithm.131 bonusConsecutive = -(scoreGapStart + scoreGapExtention)132133 // The first character in the typed pattern usually has more significance134 // than the rest so it's important that it appears at special positions where135 // bonus points are given. e.g. "to-go" vs. "ongoing" on "og" or on "ogo".136 // The amount of the extra bonus should be limited so that the gap penalty is137 // still respected.138 bonusFirstCharMultiplier = 2139)140141type charClass int142143const (144 charNonWord charClass = iota
2 unmodified lines
147 charLetter148 charNumber149)15045func evaluateBonus(caseSensitive bool, text util.Chars, pattern []rune, sidx int, eidx int) int {46 var bonus int47 pidx := 048 lenPattern := len(pattern)49 consecutive := false50 prevClass := charNonWord51 for index := util.Max(0, sidx-1); index < eidx; index++ {52 char := text.Get(index)151func posArray(withPos bool, len int) *[]int {152 if withPos {153 pos := make([]int, 0, len)154 return &pos155 }156 return nil157}158159func alloc16(offset int, slab *util.Slab, size int, clear bool) (int, []int16) {160 if slab != nil && cap(slab.I16) > offset+size {161 slice := slab.I16[offset : offset+size]162 if clear {163 for idx := range slice {164 slice[idx] = 0165 }166 }167 return offset + size, slice168 }169 return offset, make([]int16, size)170}171172func alloc32(offset int, slab *util.Slab, size int, clear bool) (int, []int32) {173 if slab != nil && cap(slab.I32) > offset+size {174 slice := slab.I32[offset : offset+size]175 if clear {176 for idx := range slice {177 slice[idx] = 0178 }179 }180 return offset + size, slice181 }182 return offset, make([]int32, size)183}184185func charClassOfAscii(char rune) charClass {186 if char >= 'a' && char <= 'z' {187 return charLower188 } else if char >= 'A' && char <= 'Z' {189 return charUpper190 } else if char >= '0' && char <= '9' {191 return charNumber192 }193 return charNonWord194}195196func charClassOfNonAscii(char rune) charClass {197 if unicode.IsLower(char) {198 return charLower199 } else if unicode.IsUpper(char) {200 return charUpper201 } else if unicode.IsNumber(char) {202 return charNumber203 } else if unicode.IsLetter(char) {204 return charLetter205 }206 return charNonWord207}208209func charClassOf(char rune) charClass {210 if char <= unicode.MaxASCII {211 return charClassOfAscii(char)212 }213 return charClassOfNonAscii(char)214}215216func bonusFor(prevClass charClass, class charClass) int16 {217 if prevClass == charNonWord && class != charNonWord {218 // Word boundary219 return bonusBoundary220 } else if prevClass == charLower && class == charUpper ||221 prevClass != charNumber && class == charNumber {222 // camelCase letter123223 return bonusCamel123224 } else if class == charNonWord {225 return bonusNonWord226 }227 return 0228}229230func bonusAt(input util.Chars, idx int) int16 {231 if idx == 0 {232 return bonusBoundary233 }234 return bonusFor(charClassOf(input.Get(idx-1)), charClassOf(input.Get(idx)))235}236237type Algo func(caseSensitive bool, forward bool, input util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int)238239func FuzzyMatchV2(caseSensitive bool, forward bool, input util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {240 // Assume that pattern is given in lowercase if case-insensitive.241 // First check if there's a match and calculate bonus for each position.242 // If the input string is too long, consider finding the matching chars in243 // this phase as well (non-optimal alignment).244 N := input.Length()245 M := len(pattern)246 switch M {247 case 0:248 return Result{0, 0, 0}, posArray(withPos, M)249 case 1:250 return ExactMatchNaive(caseSensitive, forward, input, pattern[0:1], withPos, slab)251 }252253 // Since O(nm) algorithm can be prohibitively expensive for large input,254 // we fall back to the greedy algorithm.255 if slab != nil && N*M > cap(slab.I16) {256 return FuzzyMatchV1(caseSensitive, forward, input, pattern, withPos, slab)257 }258259 // Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages260 offset := 0261 // Bonus point for each position262 offset, B := alloc16(offset, slab, N, false)263 // The first occurrence of each character in the pattern264 offset, F := alloc16(offset, slab, M, false)265 // Rune array266 _, T := alloc32(0, slab, N, false)267268 // Phase 1. Check if there's a match and calculate bonus for each point269 pidx, lastIdx, prevClass := 0, 0, charNonWord270 for idx := 0; idx < N; idx++ {271 char := input.Get(idx)272 var class charClass54 if unicode.IsLower(char) {55 class = charLower56 } else if unicode.IsUpper(char) {57 class = charUpper58 } else if unicode.IsLetter(char) {59 class = charLetter60 } else if unicode.IsNumber(char) {61 class = charNumber273 if char <= unicode.MaxASCII {274 class = charClassOfAscii(char)275 } else {63 class = charNonWord276 class = charClassOfNonAscii(char)277 }27866 var point int67 if prevClass == charNonWord && class != charNonWord {68 // Word boundary69 point = 270 } else if prevClass == charLower && class == charUpper ||71 prevClass != charNumber && class == charNumber {72 // camelCase letter12373 point = 1279 if !caseSensitive && class == charUpper {280 if char <= unicode.MaxASCII {281 char += 32282 } else {283 char = unicode.To(unicode.LowerCase, char)284 }285 }286287 T[idx] = char288 B[idx] = bonusFor(prevClass, class)289 prevClass = class29077 if index >= sidx {78 if !caseSensitive {79 if char >= 'A' && char <= 'Z' {80 char += 3281 } else if char > unicode.MaxASCII {82 char = unicode.To(unicode.LowerCase, char)291 if pidx < M {292 if char == pattern[pidx] {293 lastIdx = idx294 F[pidx] = int16(idx)295 pidx++296 }297 } else {298 if char == pattern[M-1] {299 lastIdx = idx300 }301 }302 }303 if pidx != M {304 return Result{-1, -1, 0}, nil305 }306307 // Phase 2. Fill in score matrix (H)308 // Unlike the original algorithm, we do not allow omission.309 width := lastIdx - int(F[0]) + 1310 offset, H := alloc16(offset, slab, width*M, false)311312 // Possible length of consecutive chunk at each position.313 offset, C := alloc16(offset, slab, width*M, false)314315 maxScore, maxScorePos := int16(0), 0316 for i := 0; i < M; i++ {317 I := i * width318 inGap := false319 for j := int(F[i]); j <= lastIdx; j++ {320 j0 := j - int(F[0])321 var s1, s2, consecutive int16322323 if j > int(F[i]) {324 if inGap {325 s2 = H[I+j0-1] + scoreGapExtention326 } else {327 s2 = H[I+j0-1] + scoreGapStart328 }329 }85 pchar := pattern[pidx]86 if pchar == char {87 // Boost bonus for the first character in the pattern88 if pidx == 0 {89 point *= 2330331 if pattern[i] == T[j] {332 var diag int16333 if i > 0 && j0 > 0 {334 diag = H[I-width+j0-1]335 }91 // Bonus to consecutive matching chars92 if consecutive {93 point++336 s1 = diag + scoreMatch337 b := B[j]338 if i > 0 {339 // j > 0 if i > 0340 consecutive = C[I-width+j0-1] + 1341 // Break consecutive chunk342 if b == bonusBoundary {343 consecutive = 1344 } else if consecutive > 1 {345 b = util.Max16(b, util.Max16(bonusConsecutive, B[j-int(consecutive)+1]))346 }347 } else {348 consecutive = 1349 b *= bonusFirstCharMultiplier350 }95 bonus += point351 if s1+b < s2 {352 s1 += B[j]353 consecutive = 0354 } else {355 s1 += b356 }357 }358 C[I+j0] = consecutive35997 if pidx++; pidx == lenPattern {360 inGap = s1 < s2361 score := util.Max16(util.Max16(s1, s2), 0)362 if i == M-1 && (forward && score > maxScore || !forward && score >= maxScore) {363 maxScore, maxScorePos = score, j364 }365 H[I+j0] = score366 }367368 if DEBUG {369 if i == 0 {370 fmt.Print(" ")371 for j := int(F[i]); j <= lastIdx; j++ {372 fmt.Printf(" " + string(input.Get(j)) + " ")373 }374 fmt.Println()375 }376 fmt.Print(string(pattern[i]) + " ")377 for idx := int(F[0]); idx < int(F[i]); idx++ {378 fmt.Print(" 0 ")379 }380 for idx := int(F[i]); idx <= lastIdx; idx++ {381 fmt.Printf("%2d ", H[i*width+idx-int(F[0])])382 }383 fmt.Println()384385 fmt.Print(" ")386 for idx, p := range C[I : I+width] {387 if idx+int(F[0]) < int(F[i]) {388 p = 0389 }390 fmt.Printf("%2d ", p)391 }392 fmt.Println()393 }394 }395396 // Phase 3. (Optional) Backtrace to find character positions397 pos := posArray(withPos, M)398 j := int(F[0])399 if withPos {400 i := M - 1401 j = maxScorePos402 preferMatch := true403 for {404 I := i * width405 j0 := j - int(F[0])406 s := H[I+j0]407408 var s1, s2 int16409 if i > 0 && j >= int(F[i]) {410 s1 = H[I-width+j0-1]411 }412 if j > int(F[i]) {413 s2 = H[I+j0-1]414 }415416 if s > s1 && (s > s2 || s == s2 && preferMatch) {417 *pos = append(*pos, j)418 if i == 0 {419 break420 }100 consecutive = true421 i--422 }423 preferMatch = C[I+j0] > 1 || I+width+j0+1 < len(C) && C[I+width+j0+1] > 0424 j--425 }426 }427 // Start offset we return here is only relevant when begin tiebreak is used.428 // However finding the accurate offset requires backtracking, and we don't429 // want to pay extra cost for the option that has lost its importance.430 return Result{j, maxScorePos + 1, int(maxScore)}, pos431}432433// Implement the same sorting criteria as V2434func calculateScore(caseSensitive bool, text util.Chars, pattern []rune, sidx int, eidx int, withPos bool) (int, *[]int) {435 pidx, score, inGap, consecutive, firstBonus := 0, 0, false, 0, int16(0)436 pos := posArray(withPos, len(pattern))437 prevClass := charNonWord438 if sidx > 0 {439 prevClass = charClassOf(text.Get(sidx - 1))440 }441 for idx := sidx; idx < eidx; idx++ {442 char := text.Get(idx)443 class := charClassOf(char)444 if !caseSensitive {445 if char >= 'A' && char <= 'Z' {446 char += 32447 } else if char > unicode.MaxASCII {448 char = unicode.To(unicode.LowerCase, char)449 }450 }451 if char == pattern[pidx] {452 if withPos {453 *pos = append(*pos, idx)454 }455 score += scoreMatch456 bonus := bonusFor(prevClass, class)457 if consecutive == 0 {458 firstBonus = bonus459 } else {102 consecutive = false460 // Break consecutive chunk461 if bonus == bonusBoundary {462 firstBonus = bonus463 }464 bonus = util.Max16(util.Max16(bonus, firstBonus), bonusConsecutive)465 }466 if pidx == 0 {467 score += int(bonus * bonusFirstCharMultiplier)468 } else {469 score += int(bonus)470 }471 inGap = false472 consecutive++473 pidx++474 } else {475 if inGap {476 score += scoreGapExtention477 } else {478 score += scoreGapStart479 }480 inGap = true481 consecutive = 0482 firstBonus = 0483 }484 prevClass = class485 }106 return bonus486 return score, pos487}488109// FuzzyMatch performs fuzzy-match110func FuzzyMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune) Result {489// FuzzyMatchV1 performs fuzzy-match490func FuzzyMatchV1(caseSensitive bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {491 if len(pattern) == 0 {112 return Result{0, 0, 0}492 return Result{0, 0, 0}, nil493 }494115 // 0. (FIXME) How to find the shortest match?116 // a_____b__c__abc117 // ^^^^^^^^^^ ^^^118 // 1. forward scan (abc)119 // *-----*-----*>120 // a_____b___abc__121 // 2. reverse scan (cba)122 // a_____b___abc__123 // <***495 pidx := 0496 sidx := -1497 eidx := -1498
28 unmodified lines
527528 if sidx >= 0 && eidx >= 0 {529 pidx--530 for index := eidx - 1; index >= sidx; index-- {160 char := text.Get(indexAt(index, lenRunes, forward))531 tidx := indexAt(index, lenRunes, forward)532 char := text.Get(tidx)533 if !caseSensitive {534 if char >= 'A' && char <= 'Z' {535 char += 32536 } else if char > unicode.MaxASCII {537 char = unicode.To(unicode.LowerCase, char)538 }539 }540169 pchar := pattern[indexAt(pidx, lenPattern, forward)]541 pidx_ := indexAt(pidx, lenPattern, forward)542 pchar := pattern[pidx_]543 if char == pchar {544 if pidx--; pidx < 0 {545 sidx = index546 break547 }548 }549 }550178 // Calculate the bonus. This can't be done at the same time as the179 // pattern scan above because 'forward' may be false.551 if !forward {552 sidx, eidx = lenRunes-eidx, lenRunes-sidx553 }554184 return Result{sidx, eidx,185 evaluateBonus(caseSensitive, text, pattern, sidx, eidx)}555 score, pos := calculateScore(caseSensitive, text, pattern, sidx, eidx, withPos)556 return Result{sidx, eidx, score}, pos557 }187 return Result{-1, -1, 0}558 return Result{-1, -1, 0}, nil559}560561// ExactMatchNaive is a basic string searching algorithm that handles case562// sensitivity. Although naive, it still performs better than the combination563// of strings.ToLower + strings.Index for typical fzf use cases where input564// strings and patterns are not very long.565//195// We might try to implement better algorithms in the future:196// http://en.wikipedia.org/wiki/String_searching_algorithm197func ExactMatchNaive(caseSensitive bool, forward bool, text util.Chars, pattern []rune) Result {566// Since 0.15.0, this function searches for the match with the highest567// bonus point, instead of stopping immediately after finding the first match.568// The solution is much cheaper since there is only one possible alignment of569// the pattern.570func ExactMatchNaive(caseSensitive bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {571 if len(pattern) == 0 {199 return Result{0, 0, 0}572 return Result{0, 0, 0}, nil573 }574575 lenRunes := text.Length()576 lenPattern := len(pattern)577578 if lenRunes < lenPattern {206 return Result{-1, -1, 0}579 return Result{-1, -1, 0}, nil580 }581582 // For simplicity, only look at the bonus at the first character position583 pidx := 0584 bestPos, bonus, bestBonus := -1, int16(0), int16(-1)585 for index := 0; index < lenRunes; index++ {211 char := text.Get(indexAt(index, lenRunes, forward))586 index_ := indexAt(index, lenRunes, forward)587 char := text.Get(index_)588 if !caseSensitive {589 if char >= 'A' && char <= 'Z' {590 char += 32591 } else if char > unicode.MaxASCII {592 char = unicode.To(unicode.LowerCase, char)593 }594 }219 pchar := pattern[indexAt(pidx, lenPattern, forward)]595 pidx_ := indexAt(pidx, lenPattern, forward)596 pchar := pattern[pidx_]597 if pchar == char {598 if pidx_ == 0 {599 bonus = bonusAt(text, index_)600 }601 pidx++602 if pidx == lenPattern {223 var sidx, eidx int224 if forward {225 sidx = index - lenPattern + 1226 eidx = index + 1227 } else {228 sidx = lenRunes - (index + 1)229 eidx = lenRunes - (index - lenPattern + 1)603 if bonus > bestBonus {604 bestPos, bestBonus = index, bonus605 }231 return Result{sidx, eidx,232 evaluateBonus(caseSensitive, text, pattern, sidx, eidx)}606 if bonus == bonusBoundary {607 break608 }609 index -= pidx - 1610 pidx, bonus = 0, 0611 }612 } else {613 index -= pidx236 pidx = 0614 pidx, bonus = 0, 0615 }616 }617 if bestPos >= 0 {618 var sidx, eidx int619 if forward {620 sidx = bestPos - lenPattern + 1621 eidx = bestPos + 1622 } else {623 sidx = lenRunes - (bestPos + 1)624 eidx = lenRunes - (bestPos - lenPattern + 1)625 }626 score, _ := calculateScore(caseSensitive, text, pattern, sidx, eidx, false)627 return Result{sidx, eidx, score}, nil628 }239 return Result{-1, -1, 0}629 return Result{-1, -1, 0}, nil630}631632// PrefixMatch performs prefix-match243func PrefixMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune) Result {633func PrefixMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {634 if len(pattern) == 0 {635 return Result{0, 0, 0}, nil636 }637638 if text.Length() < len(pattern) {245 return Result{-1, -1, 0}639 return Result{-1, -1, 0}, nil640 }641642 for index, r := range pattern {643 char := text.Get(index)644 if !caseSensitive {645 char = unicode.ToLower(char)646 }647 if char != r {254 return Result{-1, -1, 0}648 return Result{-1, -1, 0}, nil649 }650 }651 lenPattern := len(pattern)258 return Result{0, lenPattern,259 evaluateBonus(caseSensitive, text, pattern, 0, lenPattern)}652 score, _ := calculateScore(caseSensitive, text, pattern, 0, lenPattern, false)653 return Result{0, lenPattern, score}, nil654}655656// SuffixMatch performs suffix-match263func SuffixMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune) Result {264 trimmedLen := text.Length() - text.TrailingWhitespaces()657func SuffixMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {658 lenRunes := text.Length()659 trimmedLen := lenRunes - text.TrailingWhitespaces()660 if len(pattern) == 0 {661 return Result{trimmedLen, trimmedLen, 0}, nil662 }663 diff := trimmedLen - len(pattern)664 if diff < 0 {267 return Result{-1, -1, 0}665 return Result{-1, -1, 0}, nil666 }667668 for index, r := range pattern {669 char := text.Get(index + diff)670 if !caseSensitive {671 char = unicode.ToLower(char)672 }673 if char != r {276 return Result{-1, -1, 0}674 return Result{-1, -1, 0}, nil675 }676 }677 lenPattern := len(pattern)678 sidx := trimmedLen - lenPattern679 eidx := trimmedLen282 return Result{sidx, eidx,283 evaluateBonus(caseSensitive, text, pattern, sidx, eidx)}680 score, _ := calculateScore(caseSensitive, text, pattern, sidx, eidx, false)681 return Result{sidx, eidx, score}, nil682}683684// EqualMatch performs equal-match287func EqualMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune) Result {288 // Note: EqualMatch always return a zero bonus.289 if text.Length() != len(pattern) {290 return Result{-1, -1, 0}685func EqualMatch(caseSensitive bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {686 lenPattern := len(pattern)687 if text.Length() != lenPattern {688 return Result{-1, -1, 0}, nil689 }690 runesStr := text.ToString()691 if !caseSensitive {692 runesStr = strings.ToLower(runesStr)693 }694 if runesStr == string(pattern) {297 return Result{0, len(pattern), 0}695 return Result{0, lenPattern, (scoreMatch+bonusBoundary)*lenPattern +696 (bonusFirstCharMultiplier-1)*bonusBoundary}, nil697 }299 return Result{-1, -1, 0}698 return Result{-1, -1, 0}, nil699}
added:src/util/slab.go+12 added
1package util23type Slab struct {4 I16 []int165 I32 []int326}78func MakeSlab(size16 int, size32 int) *Slab {9 return &Slab{10 I16: make([]int16, size16),11 I32: make([]int32, size32)}12}
modified:src/util/util.go+16 added-8 removed
16 unmodified lines
17 }18 return second19}2021// Max16 returns the largest integer22func Max16(first int16, second int16) int16 {23 if first >= second {24 return first25 }26 return second27}2829// Max32 returns the largest 32-bit integer30func Max32(first int32, second int32) int32 {31 if first > second {32 return first33 }34 return second35}3637// Min returns the smallest integer38func Min(first int, second int) int {39 if first <= second {40 return first
8 unmodified lines
49 }50 return second51}5237// Max32 returns the largest 32-bit integer38func Max32(first int32, second int32) int32 {39 if first > second {40 return first41 }42 return second43}4453// Constrain32 limits the given 32-bit integer with the upper and lower bounds54func Constrain32(val int32, min int32, max int32) int32 {55 if val < min {56 return min
52 unmodified lines
modified:src/chunklist_test.go+1 added-1 removed
7 unmodified lines
8)910func TestChunkList(t *testing.T) {11 // FIXME global12 sortCriteria = []criterion{byMatchLen, byLength}12 sortCriteria = []criterion{byScore, byLength}1314 cl := NewChunkList(func(s []byte, i int) *Item {15 return &Item{text: util.ToChars(s), index: int32(i * 2)}16 })
63 unmodified lines
modified:src/constants.go+8 added-2 removed
6 unmodified lines
7)89const (10 // Current version11 version = "0.13.5"11 version = "0.15.0"1213 // Core14 coordinatorDelayMax time.Duration = 100 * time.Millisecond15 coordinatorDelayStep time.Duration = 10 * time.Millisecond
7 unmodified lines
23 initialDelayTac = 100 * time.Millisecond24 spinnerDuration = 200 * time.Millisecond2526 // Matcher27 numPartitionsMultiplier = 828 maxPartitions = 3227 progressMinDuration = 200 * time.Millisecond29 progressMinDuration = 200 * time.Millisecond3031 // Capacity of each chunk32 chunkSize int = 1003334 // Pre-allocated memory slices to minimize GC35 slab16Size int = 100 * 1024 // 200KB * 32 = 12.8MB36 slab32Size int = 2048 // 8KB * 32 = 256KB3738 // Do not cache results of low selectivity queries39 queryCacheMax int = chunkSize / 54041 // Not to cache mergers with large lists
26 unmodified lines
modified:src/core.go+4 added-3 removed
141 unmodified lines
142 }143 }144 patternBuilder := func(runes []rune) *Pattern {145 return BuildPattern(146 opts.Fuzzy, opts.Extended, opts.Case, forward, opts.Filter == nil,147 opts.Nth, opts.Delimiter, runes)146 opts.Fuzzy, opts.FuzzyAlgo, opts.Extended, opts.Case, forward,147 opts.Filter == nil, opts.Nth, opts.Delimiter, runes)148 }149 matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)150151 // Filtering mode
5 unmodified lines
157 pattern := patternBuilder([]rune(*opts.Filter))158159 found := false160 if streamingFilter {161 slab := util.MakeSlab(slab16Size, slab32Size)162 reader := Reader{163 func(runes []byte) bool {164 item := chunkList.trans(runes, 0)165 if item != nil {165 if result, _ := pattern.MatchItem(item); result != nil {166 if result, _, _ := pattern.MatchItem(item, false, slab); result != nil {167 fmt.Println(item.text.ToString())168 found = true169 }170 }
116 unmodified lines
modified:src/matcher.go+10 added-4 removed
24 unmodified lines
25 tac bool26 eventBox *util.EventBox27 reqBox *util.EventBox28 partitions int29 slab []*util.Slab30 mergerCache map[string]*Merger31}3233const (
3 unmodified lines
3738// NewMatcher returns a new Matcher39func NewMatcher(patternBuilder func([]rune) *Pattern,40 sort bool, tac bool, eventBox *util.EventBox) *Matcher {41 partitions := util.Min(numPartitionsMultiplier*runtime.NumCPU(), maxPartitions)42 return &Matcher{43 patternBuilder: patternBuilder,44 sort: sort,45 tac: tac,46 eventBox: eventBox,47 reqBox: util.NewEventBox(),46 partitions: util.Min(8*runtime.NumCPU(), 32),48 partitions: partitions,49 slab: make([]*util.Slab, partitions),50 mergerCache: make(map[string]*Merger)}51}5253// Loop puts Matcher in action
101 unmodified lines
155 waitGroup := sync.WaitGroup{}156157 for idx, chunks := range slices {158 waitGroup.Add(1)159 if m.slab[idx] == nil {160 m.slab[idx] = util.MakeSlab(slab16Size, slab32Size)161 }156 go func(idx int, chunks []*Chunk) {162 go func(idx int, slab *util.Slab, chunks []*Chunk) {163 defer func() { waitGroup.Done() }()164 count := 0165 allMatches := make([][]*Result, len(chunks))166 for idx, chunk := range chunks {161 matches := request.pattern.Match(chunk)167 matches := request.pattern.Match(chunk, slab)168 allMatches[idx] = matches169 count += len(matches)170 if cancelled.Get() {171 return
11 unmodified lines
183 sort.Sort(ByRelevance(sliceMatches))184 }185 }186 resultChan <- partialResult{idx, sliceMatches}181 }(idx, chunks)187 }(idx, m.slab[idx], chunks)188 }189190 wait := func() bool {191 cancelled.Set(true)
43 unmodified lines
modified:src/options.go+24 added-5 removed
6 unmodified lines
7 "strconv"8 "strings"9 "unicode/utf8"1011 "github.com/junegunn/fzf/src/algo"12 "github.com/junegunn/fzf/src/curses"1314 "github.com/junegunn/go-shellwords"15)
3 unmodified lines
19 Search20 -x, --extended Extended-search mode21 (enabled by default; +x or --no-extended to disable)22 -e, --exact Enable Exact-match23 --algo=TYPE Fuzzy matching algorithm: [v1|v2] (default: v2)24 -i Case-insensitive match (default: smart-case match)25 +i Case-sensitive match26 -n, --nth=N[,..] Comma-separated list of field index expressions27 for limiting search scope. Each can be a non-zero
67 unmodified lines
95// Sort criteria96type criterion int9798const (97 byMatchLen criterion = iota98 byBonus99 byScore criterion = iota100 byLength101 byBegin102 byEnd103)
25 unmodified lines
129130// Options stores the values of command-line options131type Options struct {132 Fuzzy bool133 FuzzyAlgo algo.Algo134 Extended bool135 Case Case136 Nth []Range137 WithNth []Range
35 unmodified lines
173174func defaultOptions() *Options {175 return &Options{176 Fuzzy: true,177 FuzzyAlgo: algo.FuzzyMatchV2,178 Extended: true,179 Case: CaseSmart,180 Nth: make([]Range, 0),181 WithNth: make([]Range, 0),182 Delimiter: Delimiter{},183 Sort: 1000,184 Tac: false,182 Criteria: []criterion{byMatchLen, byBonus, byLength},185 Criteria: []criterion{byScore, byLength},186 Multi: false,187 Ansi: false,188 Mouse: true,189 Theme: curses.EmptyTheme(),
134 unmodified lines
324func isAlphabet(char uint8) bool {325 return char >= 'a' && char <= 'z'326}327328func parseAlgo(str string) algo.Algo {329 switch str {330 case "v1":331 return algo.FuzzyMatchV1332 case "v2":333 return algo.FuzzyMatchV2334 default:335 errorExit("invalid algorithm (expected: v1 or v2)")336 }337 return algo.FuzzyMatchV2338}339340func parseKeyChords(str string, message string) map[int]string {341 if len(str) == 0 {342 errorExit(message)343 }
77 unmodified lines
421 return chords422}423424func parseTiebreak(str string) []criterion {410 criteria := []criterion{byMatchLen, byBonus}425 criteria := []criterion{byScore}426 hasIndex := false427 hasLength := false428 hasBegin := false429 hasEnd := false
418 unmodified lines
848 opts.Query = nextString(allArgs, &i, "query string required")849 case "-f", "--filter":850 filter := nextString(allArgs, &i, "query string required")851 opts.Filter = &filter852 case "--algo":853 opts.FuzzyAlgo = parseAlgo(nextString(allArgs, &i, "algorithm required (v1|v2)"))854 case "--expect":855 opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")856 case "--tiebreak":857 opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
120 unmodified lines
978 opts.Tabstop = nextInt(allArgs, &i, "tab stop required")979 case "--version":980 opts.Version = true981 default:965 if match, value := optString(arg, "-q", "--query="); match {982 if match, value := optString(arg, "--algo="); match {983 opts.FuzzyAlgo = parseAlgo(value)984 } else if match, value := optString(arg, "-q", "--query="); match {985 opts.Query = value986 } else if match, value := optString(arg, "-f", "--filter="); match {987 opts.Filter = &value988 } else if match, value := optString(arg, "-d", "--delimiter="); match {
119 unmodified lines
modified:src/pattern_test.go+39 added-22 removed
6 unmodified lines
7 "github.com/junegunn/fzf/src/algo"8 "github.com/junegunn/fzf/src/util"9)1011var slab *util.Slab1213func init() {14 slab = util.MakeSlab(slab16Size, slab32Size)15}1617func TestParseTermsExtended(t *testing.T) {18 terms := parseTerms(true, CaseSmart,19 "| aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ | ^iii$ ^xxx | 'yyy | | zzz$ | !ZZZ |")20 if len(terms) != 9 ||
53 unmodified lines
7475func TestExact(t *testing.T) {76 defer clearPatternCache()77 clearPatternCache()72 pattern := BuildPattern(true, true, CaseSmart, true, true,78 pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, true, true,79 []Range{}, Delimiter{}, []rune("'abc"))74 res := algo.ExactMatchNaive(75 pattern.caseSensitive, pattern.forward, util.RunesToChars([]rune("aabbcc abc")), pattern.termSets[0][0].text)80 res, pos := algo.ExactMatchNaive(81 pattern.caseSensitive, pattern.forward, util.RunesToChars([]rune("aabbcc abc")), pattern.termSets[0][0].text, true, nil)82 if res.Start != 7 || res.End != 10 {83 t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)84 }85 if pos != nil {86 t.Errorf("pos is expected to be nil")87 }88}8990func TestEqual(t *testing.T) {91 defer clearPatternCache()92 clearPatternCache()84 pattern := BuildPattern(true, true, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("^AbC$"))93 pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("^AbC$"))9495 match := func(str string, sidxExpected int, eidxExpected int) {87 res := algo.EqualMatch(88 pattern.caseSensitive, pattern.forward, util.RunesToChars([]rune(str)), pattern.termSets[0][0].text)96 res, pos := algo.EqualMatch(97 pattern.caseSensitive, pattern.forward, util.RunesToChars([]rune(str)), pattern.termSets[0][0].text, true, nil)98 if res.Start != sidxExpected || res.End != eidxExpected {99 t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)100 }101 if pos != nil {102 t.Errorf("pos is expected to be nil")103 }104 }105 match("ABC", -1, -1)106 match("AbC", 0, 3)107}108109func TestCaseSensitivity(t *testing.T) {110 defer clearPatternCache()111 clearPatternCache()100 pat1 := BuildPattern(true, false, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("abc"))112 pat1 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("abc"))113 clearPatternCache()102 pat2 := BuildPattern(true, false, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("Abc"))114 pat2 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("Abc"))115 clearPatternCache()104 pat3 := BuildPattern(true, false, CaseIgnore, true, true, []Range{}, Delimiter{}, []rune("abc"))116 pat3 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseIgnore, true, true, []Range{}, Delimiter{}, []rune("abc"))117 clearPatternCache()106 pat4 := BuildPattern(true, false, CaseIgnore, true, true, []Range{}, Delimiter{}, []rune("Abc"))118 pat4 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseIgnore, true, true, []Range{}, Delimiter{}, []rune("Abc"))119 clearPatternCache()108 pat5 := BuildPattern(true, false, CaseRespect, true, true, []Range{}, Delimiter{}, []rune("abc"))120 pat5 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseRespect, true, true, []Range{}, Delimiter{}, []rune("abc"))121 clearPatternCache()110 pat6 := BuildPattern(true, false, CaseRespect, true, true, []Range{}, Delimiter{}, []rune("Abc"))122 pat6 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseRespect, true, true, []Range{}, Delimiter{}, []rune("Abc"))123124 if string(pat1.text) != "abc" || pat1.caseSensitive != false ||125 string(pat2.text) != "Abc" || pat2.caseSensitive != true ||126 string(pat3.text) != "abc" || pat3.caseSensitive != false ||
4 unmodified lines
131 }132}133134func TestOrigTextAndTransformed(t *testing.T) {123 pattern := BuildPattern(true, true, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("jg"))135 pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, true, true, []Range{}, Delimiter{}, []rune("jg"))136 tokens := Tokenize(util.RunesToChars([]rune("junegunn")), Delimiter{})137 trans := Transform(tokens, []Range{Range{1, 1}})138139 origBytes := []byte("junegunn.choi")
4 unmodified lines
144 origText: &origBytes,145 transformed: trans},146 }147 pattern.extended = extended136 matches := pattern.matchChunk(&chunk, nil) // No cache137 if matches[0].item.text.ToString() != "junegunn" || string(*matches[0].item.origText) != "junegunn.choi" ||138 !reflect.DeepEqual(matches[0].item.transformed, trans) {148 matches := pattern.matchChunk(&chunk, nil, slab) // No cache149 if !(matches[0].item.text.ToString() == "junegunn" &&150 string(*matches[0].item.origText) == "junegunn.choi" &&151 reflect.DeepEqual(matches[0].item.transformed, trans)) {152 t.Error("Invalid match result", matches)153 }154142 match, offsets := pattern.MatchItem(chunk[0])143 if match.item.text.ToString() != "junegunn" || string(*match.item.origText) != "junegunn.choi" ||144 offsets[0][0] != 0 || offsets[0][1] != 5 ||145 !reflect.DeepEqual(match.item.transformed, trans) {146 t.Error("Invalid match result", match)155 match, offsets, pos := pattern.MatchItem(chunk[0], true, slab)156 if !(match.item.text.ToString() == "junegunn" &&157 string(*match.item.origText) == "junegunn.choi" &&158 offsets[0][0] == 0 && offsets[0][1] == 5 &&159 reflect.DeepEqual(match.item.transformed, trans)) {160 t.Error("Invalid match result", match, offsets, extended)161 }162 if !((*pos)[0] == 4 && (*pos)[1] == 0) {163 t.Error("Invalid pos array", *pos)164 }165 }166}167168func TestCacheKey(t *testing.T) {169 test := func(extended bool, patStr string, expected string, cacheable bool) {153 pat := BuildPattern(true, extended, CaseSmart, true, true, []Range{}, Delimiter{}, []rune(patStr))170 pat := BuildPattern(true, algo.FuzzyMatchV2, extended, CaseSmart, true, true, []Range{}, Delimiter{}, []rune(patStr))171 if pat.CacheKey() != expected {172 t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())173 }174 if pat.cacheable != cacheable {
14 unmodified lines
modified:src/pattern.go+51 added-32 removed
38 unmodified lines
3940// Pattern represents search pattern41type Pattern struct {42 fuzzy bool43 fuzzyAlgo algo.Algo44 extended bool45 caseSensitive bool46 forward bool47 text []rune48 termSets []termSet49 cacheable bool50 delimiter Delimiter51 nth []Range51 procFun map[termType]func(bool, bool, util.Chars, []rune) algo.Result52 procFun map[termType]algo.Algo53}5455var (56 _patternCache map[string]*Pattern
17 unmodified lines
74 _cache = NewChunkCache()75}7677// BuildPattern builds Pattern object from the given arguments77func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,78func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, forward bool,79 cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8081 var asString string82 if extended {
33 unmodified lines
116 }117118 ptr := &Pattern{119 fuzzy: fuzzy,120 fuzzyAlgo: fuzzyAlgo,121 extended: extended,122 caseSensitive: caseSensitive,123 forward: forward,124 text: []rune(asString),125 termSets: termSets,126 cacheable: cacheable,127 nth: nth,128 delimiter: delimiter,127 procFun: make(map[termType]func(bool, bool, util.Chars, []rune) algo.Result)}129 procFun: make(map[termType]algo.Algo)}130129 ptr.procFun[termFuzzy] = algo.FuzzyMatch131 ptr.procFun[termFuzzy] = fuzzyAlgo132 ptr.procFun[termEqual] = algo.EqualMatch133 ptr.procFun[termExact] = algo.ExactMatchNaive134 ptr.procFun[termPrefix] = algo.PrefixMatch135 ptr.procFun[termSuffix] = algo.SuffixMatch
99 unmodified lines
235 return strings.Join(cacheableTerms, " ")236}237238// Match returns the list of matches Items in the given Chunk237func (p *Pattern) Match(chunk *Chunk) []*Result {239func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {240 // ChunkCache: Exact match241 cacheKey := p.CacheKey()242 if p.cacheable {243 if cached, found := _cache.Find(chunk, cacheKey); found {
17 unmodified lines
261 }262 }263 }264263 matches := p.matchChunk(chunk, space)265 matches := p.matchChunk(chunk, space, slab)266267 if p.cacheable {268 _cache.Add(chunk, cacheKey, matches)269 }270 return matches271}272271func (p *Pattern) matchChunk(chunk *Chunk, space []*Result) []*Result {273func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {274 matches := []*Result{}275276 if space == nil {277 for _, item := range *chunk {276 if match, _ := p.MatchItem(item); match != nil {278 if match, _, _ := p.MatchItem(item, false, slab); match != nil {279 matches = append(matches, match)280 }281 }282 } else {283 for _, result := range space {282 if match, _ := p.MatchItem(result.item); match != nil {284 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {285 matches = append(matches, match)286 }287 }288 }289 return matches290}291292// MatchItem returns true if the Item is a match291func (p *Pattern) MatchItem(item *Item) (*Result, []Offset) {293func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {294 if p.extended {293 if offsets, bonus, trimLen := p.extendedMatch(item); len(offsets) == len(p.termSets) {294 return buildResult(item, offsets, bonus, trimLen), offsets295 if offsets, bonus, trimLen, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {296 return buildResult(item, offsets, bonus, trimLen), offsets, pos297 }296 return nil, nil298 return nil, nil, nil299 }298 offset, bonus, trimLen := p.basicMatch(item)300 offset, bonus, trimLen, pos := p.basicMatch(item, withPos, slab)301 if sidx := offset[0]; sidx >= 0 {302 offsets := []Offset{offset}301 return buildResult(item, offsets, bonus, trimLen), offsets303 return buildResult(item, offsets, bonus, trimLen), offsets, pos304 }303 return nil, nil305 return nil, nil, nil306}307306func (p *Pattern) basicMatch(item *Item) (Offset, int, int) {308func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {309 input := p.prepareInput(item)310 if p.fuzzy {309 return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)311 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.forward, p.text, withPos, slab)312 }311 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)313 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text, withPos, slab)314}315314func (p *Pattern) extendedMatch(item *Item) ([]Offset, int, int) {316func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, int, *[]int) {317 input := p.prepareInput(item)318 offsets := []Offset{}317 var totalBonus int319 var totalScore int320 var totalTrimLen int321 var allPos *[]int322 if withPos {323 allPos = &[]int{}324 }325 for _, termSet := range p.termSets {326 var offset Offset321 var bonus int327 var currentScore int328 var trimLen int329 matched := false330 for _, term := range termSet {331 pfun := p.procFun[term.typ]326 off, pen, tLen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)332 off, score, tLen, pos := p.iter(pfun, input, term.caseSensitive, p.forward, term.text, withPos, slab)333 if sidx := off[0]; sidx >= 0 {334 if term.inv {335 continue336 }331 offset, bonus, trimLen = off, pen, tLen337 offset, currentScore, trimLen = off, score, tLen338 matched = true339 if withPos {340 if pos != nil {341 *allPos = append(*allPos, *pos...)342 } else {343 for idx := off[0]; idx < off[1]; idx++ {344 *allPos = append(*allPos, int(idx))345 }346 }347 }348 break349 } else if term.inv {335 offset, bonus, trimLen = Offset{0, 0}, 0, 0350 offset, currentScore, trimLen = Offset{0, 0}, 0, 0351 matched = true352 continue353 }354 }355 if matched {356 offsets = append(offsets, offset)342 totalBonus += bonus357 totalScore += currentScore358 totalTrimLen += trimLen359 }360 }346 return offsets, totalBonus, totalTrimLen361 return offsets, totalScore, totalTrimLen, allPos362}363364func (p *Pattern) prepareInput(item *Item) []Token {365 if item.transformed != nil {
10 unmodified lines
376 item.transformed = ret377 return ret378}379365func (p *Pattern) iter(pfun func(bool, bool, util.Chars, []rune) algo.Result,366 tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int, int) {380func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {381 for _, part := range tokens {368 if res := pfun(caseSensitive, forward, *part.text, pattern); res.Start >= 0 {382 if res, pos := pfun(caseSensitive, forward, *part.text, pattern, withPos, slab); res.Start >= 0 {383 sidx := int32(res.Start) + part.prefixLength384 eidx := int32(res.End) + part.prefixLength371 return Offset{sidx, eidx}, res.Bonus, int(part.trimLength)385 if pos != nil {386 for idx := range *pos {387 (*pos)[idx] += int(part.prefixLength)388 }389 }390 return Offset{sidx, eidx}, res.Score, int(part.trimLength), pos391 }392 }374 return Offset{-1, -1}, 0, -1393 return Offset{-1, -1}, 0, -1, nil394}
modified:src/README.md+17 added
59 unmodified lines
60# Build executables and tarballs for Linux using Docker61make linux62```6364Test65----6667Unit tests can be run with `make test`. Integration tests are written in Ruby68script that should be run on tmux.6970```sh71# Unit tests72make test7374# Install the executable to ../bin directory75make install7677# Integration tests78ruby ../test/test_go.rb79```8081Third-party libraries used82--------------------------8384- [ncurses][ncurses]
16 unmodified lines
modified:src/result_test.go+15 added-11 removed
24 unmodified lines
2526func TestRankComparison(t *testing.T) {27 rank := func(vals ...uint16) rank {28 return rank{29 points: [5]uint16{vals[0], 0, vals[1], vals[2], vals[3]},29 points: [4]uint16{vals[0], vals[1], vals[2], vals[3]},30 index: int32(vals[4])}31 }32 if compareRanks(rank(3, 0, 0, 0, 5), rank(2, 0, 0, 0, 7), false) ||33 !compareRanks(rank(3, 0, 0, 0, 5), rank(3, 0, 0, 0, 6), false) ||
12 unmodified lines
4647// Match length, string length, index48func TestResultRank(t *testing.T) {49 // FIXME global50 sortCriteria = []criterion{byMatchLen, byBonus, byLength}50 sortCriteria = []criterion{byScore, byLength}5152 strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}53 item1 := buildResult(&Item{text: util.RunesToChars(strs[0]), index: 1}, []Offset{}, 2, 3)54 if item1.rank.points[0] != math.MaxUint16 || item1.rank.points[1] != math.MaxUint16-2 || item1.rank.points[2] != 3 || item1.item.index != 1 {54 if item1.rank.points[0] != math.MaxUint16-2 || // Bonus55 item1.rank.points[1] != 3 || // Length56 item1.rank.points[2] != 0 || // Unused57 item1.rank.points[3] != 0 || // Unused58 item1.item.index != 1 {59 t.Error(item1.rank)60 }61 // Only differ in index62 item2 := buildResult(&Item{text: util.RunesToChars(strs[0])}, []Offset{}, 2, 3)
11 unmodified lines
74 t.Error(items, item1, item1.item.index, item2, item2.item.index)75 }7677 // Sort by relevance74 item3 := buildResult(&Item{index: 2}, []Offset{Offset{1, 3}, Offset{5, 7}}, 0, 0)75 item4 := buildResult(&Item{index: 2}, []Offset{Offset{1, 2}, Offset{6, 7}}, 0, 0)76 item5 := buildResult(&Item{index: 2}, []Offset{Offset{1, 3}, Offset{5, 7}}, 0, 0)77 item6 := buildResult(&Item{index: 2}, []Offset{Offset{1, 2}, Offset{6, 7}}, 0, 0)78 item3 := buildResult(&Item{index: 2}, []Offset{Offset{1, 3}, Offset{5, 7}}, 3, 0)79 item4 := buildResult(&Item{index: 2}, []Offset{Offset{1, 2}, Offset{6, 7}}, 4, 0)80 item5 := buildResult(&Item{index: 2}, []Offset{Offset{1, 3}, Offset{5, 7}}, 5, 0)81 item6 := buildResult(&Item{index: 2}, []Offset{Offset{1, 2}, Offset{6, 7}}, 6, 0)82 items = []*Result{item1, item2, item3, item4, item5, item6}83 sort.Sort(ByRelevance(items))80 if items[0] != item6 || items[1] != item4 ||81 items[2] != item5 || items[3] != item3 ||82 items[4] != item2 || items[5] != item1 {83 t.Error(items)84 if !(items[0] == item6 && items[1] == item5 &&85 items[2] == item4 && items[3] == item3 &&86 items[4] == item2 && items[5] == item1) {87 t.Error(items, item1, item2, item3, item4, item5, item6)88 }89}9091func TestColorOffset(t *testing.T) {
28 unmodified lines
modified:src/result.go+26 added-44 removed
17 unmodified lines
18 index int3219}2021type rank struct {22 // byMatchLen, byBonus, ...23 points [5]uint1622 points [4]uint1623 index int3224}2526type Result struct {27 item *Item28 rank rank29}3032func buildResult(item *Item, offsets []Offset, bonus int, trimLen int) *Result {31func buildResult(item *Item, offsets []Offset, score int, trimLen int) *Result {32 if len(offsets) > 1 {33 sort.Sort(ByOrder(offsets))34 }3536 result := Result{item: item, rank: rank{index: item.index}}3839 matchlen := 040 prevEnd := 041 minBegin := math.MaxInt3237 numChars := item.text.Length()38 minBegin := math.MaxUint1639 maxEnd := 040 validOffsetFound := false41 for _, offset := range offsets {44 begin := int(offset[0])45 end := int(offset[1])46 if prevEnd > begin {47 begin = prevEnd42 b, e := int(offset[0]), int(offset[1])43 if b < e {44 minBegin = util.Min(b, minBegin)45 maxEnd = util.Max(e, maxEnd)46 validOffsetFound = true47 }49 if end > prevEnd {50 prevEnd = end51 }52 if end > begin {53 if begin < minBegin {54 minBegin = begin55 }56 matchlen += end - begin57 }48 }4950 for idx, criterion := range sortCriteria {61 var val uint1651 val := uint16(math.MaxUint16)52 switch criterion {63 case byMatchLen:64 if matchlen == 0 {65 val = math.MaxUint1666 } else {67 val = util.AsUint16(matchlen)68 }69 case byBonus:53 case byScore:54 // Higher is better71 val = math.MaxUint16 - util.AsUint16(bonus)55 val = math.MaxUint16 - util.AsUint16(score)56 case byLength:57 // If offsets is empty, trimLen will be 0, but we don't care58 val = util.AsUint16(trimLen)59 case byBegin:76 // We can't just look at item.offsets[0][0] because it can be an inverse term77 whitePrefixLen := 078 for idx := 0; idx < numChars; idx++ {79 r := item.text.Get(idx)80 whitePrefixLen = idx81 if idx == minBegin || r != ' ' && r != '\t' {82 break60 if validOffsetFound {61 whitePrefixLen := 062 for idx := 0; idx < numChars; idx++ {63 r := item.text.Get(idx)64 whitePrefixLen = idx65 if idx == minBegin || r != ' ' && r != '\t' {66 break67 }68 }69 val = util.AsUint16(minBegin - whitePrefixLen)70 }85 val = util.AsUint16(minBegin - whitePrefixLen)71 case byEnd:87 if prevEnd > 0 {88 val = util.AsUint16(1 + numChars - prevEnd)89 } else {90 // Empty offsets due to inverse terms.91 val = 172 if validOffsetFound {73 val = util.AsUint16(1 + numChars - maxEnd)74 }75 }76 result.rank.points[idx] = val77 }
9 unmodified lines
87 return result.item.index88}8990func minRank() rank {109 return rank{index: 0, points: [5]uint16{0, math.MaxUint16, 0, 0, 0}}91 return rank{index: 0, points: [4]uint16{math.MaxUint16, 0, 0, 0}}92}9394func (result *Result) colorOffsets(matchOffsets []Offset, color int, bold bool, current bool) []colorOffset {95 itemColors := result.item.Colors()
130 unmodified lines
226 return compareRanks((*a[i]).rank, (*a[j]).rank, true)227}228229func compareRanks(irank rank, jrank rank, tac bool) bool {248 for idx := 0; idx < 5; idx++ {230 for idx := 0; idx < 4; idx++ {231 left := irank.points[idx]232 right := jrank.points[idx]233 if left < right {234 return true
6 unmodified lines
modified:src/terminal.go+20 added-3 removed
16 unmodified lines
1718 "github.com/junegunn/go-runewidth"19)2021// import "github.com/pkg/profile"2223type jumpMode int2425const (26 jumpDisabled jumpMode = iota
47 unmodified lines
74 mutex sync.Mutex75 initFunc func()76 suppress bool77 startChan chan bool78 slab *util.Slab79}8081type selectedItem struct {82 at time.Time
195 unmodified lines
278 previewBox: previewBox,279 eventBox: eventBox,280 mutex: sync.Mutex{},281 suppress: true,282 slab: util.MakeSlab(slab16Size, slab32Size),283 startChan: make(chan bool, 1),284 initFunc: func() {285 C.Init(opts.Theme, opts.Black, opts.Mouse)286 }}
390 unmodified lines
677 // Overflow678 text := make([]rune, item.text.Length())679 copy(text, item.text.ToRunes())680 matchOffsets := []Offset{}681 var pos *[]int682 if t.merger.pattern != nil {678 _, matchOffsets = t.merger.pattern.MatchItem(item)683 _, matchOffsets, pos = t.merger.pattern.MatchItem(item, true, t.slab)684 }685 charOffsets := matchOffsets686 if pos != nil {687 charOffsets = make([]Offset, len(*pos))688 for idx, p := range *pos {689 offset := Offset{int32(p), int32(p + 1)}690 charOffsets[idx] = offset691 }692 sort.Sort(ByOrder(charOffsets))693 }694 var maxe int681 for _, offset := range matchOffsets {695 for _, offset := range charOffsets {696 maxe = util.Max(maxe, int(offset[1]))697 }698684 offsets := result.colorOffsets(matchOffsets, col2, bold, current)699 offsets := result.colorOffsets(charOffsets, col2, bold, current)700 maxWidth := t.window.Width - 3701 maxe = util.Constrain(maxe+util.Min(maxWidth/2-2, t.hscrollOff), 0, len(text))702 if overflow(text, maxWidth) {703 if t.hscroll {
186 unmodified lines
890}891892// Loop is called to start Terminal I/O893func (t *Terminal) Loop() {894 // prof := profile.Start(profile.ProfilePath("/tmp/"))895 <-t.startChan896 { // Late initialization897 intChan := make(chan os.Signal, 1)898 signal.Notify(intChan, os.Interrupt, os.Kill, syscall.SIGTERM)
69 unmodified lines
968 exit := func(code int) {969 if code <= exitNoMatch && t.history != nil {970 t.history.append(string(t.input))971 }972 // prof.Stop()973 os.Exit(code)974 }975976 go func() {
434 unmodified lines
modified:test/test_go.rb+70 added-152 removed
515 unmodified lines
516517 assert_equal input, `#{FZF} -f"!z" -x --tiebreak end < #{tempname}`.split($/)518 end519520 # Since 0.11.2521 def test_tiebreak_list522 input = %w[523 f-o-o-b-a-r524 foobar----525 --foobar526 ----foobar527 foobar--528 --foobar--529 foobar520 def test_tiebreak_index_begin521 writelines tempname, [522 'xoxxxxxoxx',523 'xoxxxxxox',524 'xxoxxxoxx',525 'xxxoxoxxx',526 'xxxxoxox',527 ' xxoxoxxx',528 ]531 writelines tempname, input529533 assert_equal %w[534 foobar----535 --foobar536 ----foobar537 foobar--538 --foobar--539 foobar540 f-o-o-b-a-r541 ], `#{FZF} -ffb --tiebreak=index < #{tempname}`.split($/)530 assert_equal [531 'xxxxoxox',532 ' xxoxoxxx',533 'xxxoxoxxx',534 'xxoxxxoxx',535 'xoxxxxxox',536 'xoxxxxxoxx',537 ], `#{FZF} -foo < #{tempname}`.split($/)538543 by_length = %w[544 foobar545 --foobar546 foobar--547 foobar----548 ----foobar549 --foobar--550 f-o-o-b-a-r551 ]552 assert_equal by_length, `#{FZF} -ffb < #{tempname}`.split($/)553 assert_equal by_length, `#{FZF} -ffb --tiebreak=length < #{tempname}`.split($/)539 assert_equal [540 'xxxoxoxxx',541 'xxxxoxox',542 ' xxoxoxxx',543 'xxoxxxoxx',544 'xoxxxxxoxx',545 'xoxxxxxox',546 ], `#{FZF} -foo --tiebreak=index < #{tempname}`.split($/)547555 assert_equal %w[556 foobar557 foobar--558 --foobar559 foobar----560 --foobar--561 ----foobar562 f-o-o-b-a-r563 ], `#{FZF} -ffb --tiebreak=length,begin < #{tempname}`.split($/)548 # Note that --tiebreak=begin is now based on the first occurrence of the549 # first character on the pattern550 assert_equal [551 ' xxoxoxxx',552 'xxxoxoxxx',553 'xxxxoxox',554 'xxoxxxoxx',555 'xoxxxxxoxx',556 'xoxxxxxox',557 ], `#{FZF} -foo --tiebreak=begin < #{tempname}`.split($/)558565 assert_equal %w[566 foobar567 --foobar568 foobar--569 ----foobar570 --foobar--571 foobar----572 f-o-o-b-a-r573 ], `#{FZF} -ffb --tiebreak=length,end < #{tempname}`.split($/)574575 assert_equal %w[576 foobar----577 foobar--578 foobar579 --foobar580 --foobar--581 ----foobar582 f-o-o-b-a-r583 ], `#{FZF} -ffb --tiebreak=begin < #{tempname}`.split($/)584585 by_begin_end = %w[586 foobar587 foobar--588 foobar----589 --foobar590 --foobar--591 ----foobar592 f-o-o-b-a-r593 ]594 assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=begin,length < #{tempname}`.split($/)595 assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=begin,end < #{tempname}`.split($/)596597 assert_equal %w[598 --foobar599 ----foobar600 foobar601 foobar--602 --foobar--603 foobar----604 f-o-o-b-a-r605 ], `#{FZF} -ffb --tiebreak=end < #{tempname}`.split($/)606607 by_begin_end = %w[608 foobar609 --foobar610 ----foobar611 foobar--612 --foobar--613 foobar----614 f-o-o-b-a-r615 ]616 assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=end,begin < #{tempname}`.split($/)617 assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=end,length < #{tempname}`.split($/)559 assert_equal [560 ' xxoxoxxx',561 'xxxoxoxxx',562 'xxxxoxox',563 'xxoxxxoxx',564 'xoxxxxxox',565 'xoxxxxxoxx',566 ], `#{FZF} -foo --tiebreak=begin,length < #{tempname}`.split($/)567 end568620 def test_tiebreak_white_prefix569 def test_tiebreak_end570 writelines tempname, [622 'f o o b a r',623 ' foo bar',624 ' foobar',625 '----foo bar',626 '----foobar',627 ' foo bar',628 ' foobar--',629 ' foobar',630 '--foo bar',631 '--foobar',632 'foobar',571 'xoxxxxxxxx',572 'xxoxxxxxxx',573 'xxxoxxxxxx',574 'xxxxoxxxx',575 'xxxxxoxxx',576 ' xxxxoxxx',577 ]578579 assert_equal [636 ' foobar',637 ' foobar',638 'foobar',639 ' foobar--',640 '--foobar',641 '----foobar',642 ' foo bar',643 ' foo bar',644 '--foo bar',645 '----foo bar',646 'f o o b a r',647 ], `#{FZF} -ffb < #{tempname}`.split($/)580 ' xxxxoxxx',581 'xxxxoxxxx',582 'xxxxxoxxx',583 'xoxxxxxxxx',584 'xxoxxxxxxx',585 'xxxoxxxxxx',586 ], `#{FZF} -fo < #{tempname}`.split($/)587588 assert_equal [650 ' foobar',651 ' foobar--',652 ' foobar',653 'foobar',654 '--foobar',655 '----foobar',656 ' foo bar',657 ' foo bar',658 '--foo bar',659 '----foo bar',660 'f o o b a r',661 ], `#{FZF} -ffb --tiebreak=begin < #{tempname}`.split($/)589 'xxxxxoxxx',590 ' xxxxoxxx',591 'xxxxoxxxx',592 'xxxoxxxxxx',593 'xxoxxxxxxx',594 'xoxxxxxxxx',595 ], `#{FZF} -fo --tiebreak=end < #{tempname}`.split($/)596597 assert_equal [664 ' foobar',665 ' foobar',666 'foobar',667 ' foobar--',668 '--foobar',669 '----foobar',670 ' foo bar',671 ' foo bar',672 '--foo bar',673 '----foo bar',674 'f o o b a r',675 ], `#{FZF} -ffb --tiebreak=begin,length < #{tempname}`.split($/)598 ' xxxxoxxx',599 'xxxxxoxxx',600 'xxxxoxxxx',601 'xxxoxxxxxx',602 'xxoxxxxxxx',603 'xoxxxxxxxx',604 ], `#{FZF} -fo --tiebreak=end,length,begin < #{tempname}`.split($/)605 end606607 def test_tiebreak_length_with_nth608 input = %w[
67 unmodified lines
676 assert_equal output, `#{FZF} -fi -n2 < #{tempname}`.split($/)677 assert_equal output, `#{FZF} -fi -n2,1..2 < #{tempname}`.split($/)678 end679751 def test_tiebreak_end_backward_scan752 input = %w[753 foobar-fb754 fubar755 ]756 writelines tempname, input757758 assert_equal input.reverse, `#{FZF} -f fb < #{tempname}`.split($/)759 assert_equal input, `#{FZF} -f fb --tiebreak=end < #{tempname}`.split($/)760 end761680 def test_invalid_cache681 tmux.send_keys "(echo d; echo D; echo x) | #{fzf '-q d'}", :Enter682 tmux.until { |lines| lines[-2].include? '2/3' }683 tmux.send_keys :BSpace
863 unmodified lines
modified:CHANGELOG.md+7 added
1CHANGELOG2=========340.15.05------6- Improved fuzzy search algorithm7 - Added `--algo=[v1|v2]` option so one can still choose the old algorithm8 which values the search performance over the quality of the result9- Advanced scoring criteria10110.13.512------13- Memory and performance optimization14 - Up to 2x performance with half the amount of memory
432 unmodified lines
modified:install+2 added-2 removed
1#!/usr/bin/env bash23set -u45[[ "$@" =~ --pre ]] && version=0.13.5 pre=1 ||6 version=0.13.5 pre=05[[ "$@" =~ --pre ]] && version=0.15.0 pre=1 ||6 version=0.15.0 pre=078auto_completion=9key_bindings=10update_config=2
398 unmodified lines