Use trimmed length when --nth is used with --tiebreak=length
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This change improves sort ordering for aligned tabular input. Given the following input: apple juice 100 apple pie 200 fzf --nth=2 will now prefer the one with pie. Before this change fzf compared "juice " and "pie ", both of which have the same length.
authored by Junegunn Choi · committed by Junegunn Choi · parent 7c7a30c · Browse files · 7 files·+124 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+124 added−28 removed
- tests:+47 added−0 removed
- other:+77 added−28 removed
Provenance
- Commit
92a75c9- Tree
c65a176- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
7c7a30c
7 files changed+124 added−28 removed
modified:src/util/util_test.go+20 added
18 unmodified lines19 if Constrain(5, -1, 3) != 3 {20 t.Error("Expected", 3)21 }22 }23+24+func TestTrimLen(t *testing.T) {25+ check := func(str string, exp int) {26+ trimmed := TrimLen([]rune(str))27+ if trimmed != exp {28+ t.Errorf("Invalid TrimLen result for '%s': %d (expected %d)",29+ str, trimmed, exp)30+ }31+ }32+ check("hello", 5)33+ check("hello ", 5)34+ check("hello ", 5)35+ check(" hello", 5)36+ check(" hello", 5)37+ check(" hello ", 5)38+ check(" hello ", 5)39+ check("h o", 5)40+ check(" h o ", 5)41+ check(" ", 0)42+}modified:src/util/util.go+26 added
73 unmodified lines74 func IsTty() bool {75 return int(C.isatty(C.int(os.Stdin.Fd()))) != 076 }77 78+// TrimRight returns rune array with trailing white spaces cut off79 func TrimRight(runes []rune) []rune {80 var i int81 for i = len(runes) - 1; i >= 0; i-- {82 char := runes[i]3 unmodified lines86 }87 return runes[0 : i+1]88 }89 90+// BytesToRunes converts byte array into rune array91 func BytesToRunes(bytea []byte) []rune {92 runes := make([]rune, 0, len(bytea))93 for i := 0; i < len(bytea); {94 if bytea[i] < utf8.RuneSelf {6 unmodified lines101 }102 }103 return runes104 }105+106+// TrimLen returns the length of trimmed rune array107+func TrimLen(runes []rune) int {108+ var i int109+ for i = len(runes) - 1; i >= 0; i-- {110+ char := runes[i]111+ if char != ' ' && char != '\t' {112+ break113+ }114+ }115+ // Completely empty116+ if i < 0 {117+ return 0118+ }119+120+ var j int121+ for j = 0; j < len(runes); j++ {122+ char := runes[j]123+ if char != ' ' && char != '\t' {124+ break125+ }126+ }127+ return i - j + 1128+}modified:src/item.go+10 added-9 removed
4 unmodified lines5 6 "github.com/junegunn/fzf/src/curses"7 )8 9-// Offset holds two 32-bit integers denoting the offsets of a matched substring10-type Offset [2]int329+// Offset holds three 32-bit integers denoting the offsets of a matched substring10+type Offset [3]int3211 12 type colorOffset struct {13 offset [2]int3214 color int27 unmodified lines42 return item.rank43 }44 matchlen := 045 prevEnd := 046+ lenSum := 047 minBegin := math.MaxUint1648 for _, offset := range item.offsets {49 begin := int(offset[0])50 end := int(offset[1])51+ trimLen := int(offset[2])52+ lenSum += trimLen53 if prevEnd > begin {54 begin = prevEnd55 }56 if end > prevEnd {10 unmodified lines67 switch rankTiebreak {68 case byLength:69 // It is guaranteed that .transformed in not null in normal execution70 if item.transformed != nil {68- lenSum := 069- for _, token := range item.transformed {70- lenSum += len(token.text)71- }71+ // If offsets is empty, lenSum will be 0, but we don't care72 tiebreak = uint16(lenSum)73 } else {74 tiebreak = uint16(len(item.text))75 }39 unmodified lines115 func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {116 if len(item.colors) == 0 {117 var offsets []colorOffset118 for _, off := range item.offsets {119+119- offsets = append(offsets, colorOffset{offset: off, color: color, bold: bold})120+ offsets = append(offsets, colorOffset{offset: [2]int32{off[0], off[1]}, color: color, bold: bold})121 }122 return offsets123 }124 35 unmodified lines160 add := func(idx int) {161 if curr != 0 && idx > start {162 if curr == -1 {163 offsets = append(offsets, colorOffset{163- offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})164+ offset: [2]int32{int32(start), int32(idx)}, color: color, bold: bold})165 } else {166 ansi := item.colors[curr-1]167 fg := ansi.color.fg168 if fg == -1 {11 unmodified lines180 bg = curses.BG181 }182 }183 offsets = append(offsets, colorOffset{183- offset: Offset{int32(start), int32(idx)},184+ offset: [2]int32{int32(start), int32(idx)},185 color: curses.PairFor(fg, bg),186 bold: ansi.color.bold || bold})187 }188 }80 unmodified linesmodified:src/pattern.go+12 added-11 removed
4 unmodified lines5 "sort"6 "strings"7 8 "github.com/junegunn/fzf/src/algo"9+ "github.com/junegunn/fzf/src/util"10 )11 12 // fuzzy13 // 'exact237 unmodified lines251 func (p *Pattern) matchChunk(chunk *Chunk) []*Item {252 matches := []*Item{}253 if p.mode == ModeFuzzy {254 for _, item := range *chunk {254- if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {255+ if sidx, eidx, tlen := p.fuzzyMatch(item); sidx >= 0 {256 matches = append(matches,256- dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))257+ dupItem(item, []Offset{Offset{int32(sidx), int32(eidx), int32(tlen)}}))258 }259 }260 } else {261 for _, item := range *chunk {7 unmodified lines269 270 // MatchItem returns true if the Item is a match271 func (p *Pattern) MatchItem(item *Item) bool {272 if p.mode == ModeFuzzy {272- sidx, _ := p.fuzzyMatch(item)273+ sidx, _, _ := p.fuzzyMatch(item)274 return sidx >= 0275 }276 offsets := p.extendedMatch(item)277 return len(offsets) == len(p.terms)10 unmodified lines288 colors: item.colors,289 rank: Rank{0, 0, item.index}}290 }291 291-func (p *Pattern) fuzzyMatch(item *Item) (int, int) {292+func (p *Pattern) fuzzyMatch(item *Item) (int, int, int) {293 input := p.prepareInput(item)294 return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)295 }296 1 unmodified line298 input := p.prepareInput(item)299 offsets := []Offset{}300 for _, term := range p.terms {301 pfun := p.procFun[term.typ]301- if sidx, eidx := p.iter(pfun, input, term.caseSensitive, p.forward, term.text); sidx >= 0 {302+ if sidx, eidx, tlen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text); sidx >= 0 {303 if term.inv {304 break305 }305- offsets = append(offsets, Offset{int32(sidx), int32(eidx)})306+ offsets = append(offsets, Offset{int32(sidx), int32(eidx), int32(tlen)})307 } else if term.inv {307- offsets = append(offsets, Offset{0, 0})308+ offsets = append(offsets, Offset{0, 0, 0})309 }310 }311 return offsets312 }7 unmodified lines320 if len(p.nth) > 0 {321 tokens := Tokenize(item.text, p.delimiter)322 ret = Transform(tokens, p.nth)323 } else {323- ret = []Token{Token{text: item.text, prefixLength: 0}}324+ ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: util.TrimLen(item.text)}}325 }326 item.transformed = ret327 return ret328 }329 330 func (p *Pattern) iter(pfun func(bool, bool, []rune, []rune) (int, int),330- tokens []Token, caseSensitive bool, forward bool, pattern []rune) (int, int) {331+ tokens []Token, caseSensitive bool, forward bool, pattern []rune) (int, int, int) {332 for _, part := range tokens {333 prefixLength := part.prefixLength334 if sidx, eidx := pfun(caseSensitive, forward, part.text, pattern); sidx >= 0 {334- return sidx + prefixLength, eidx + prefixLength335+ return sidx + prefixLength, eidx + prefixLength, part.trimLength336 }337 }337- return -1, -1338+ return -1, -1, -1 // math.MaxUint16339 }modified:src/tokenizer_test.go+6 added-6 removed
42 unmodified lines43 func TestTokenize(t *testing.T) {44 // AWK-style45 input := " abc: def: ghi "46 tokens := Tokenize([]rune(input), Delimiter{})47- if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {47+ if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 || tokens[0].trimLength != 4 {48 t.Errorf("%s", tokens)49 }50 51 // With delimiter52 tokens = Tokenize([]rune(input), delimiterRegexp(":"))53- if string(tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {53+ if string(tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 || tokens[0].trimLength != 4 {54 t.Errorf("%s", tokens)55 }56 57 // With delimiter regex58 tokens = Tokenize([]rune(input), delimiterRegexp("\\s+"))59- if string(tokens[0].text) != " " || tokens[0].prefixLength != 0 ||60- string(tokens[1].text) != "abc: " || tokens[1].prefixLength != 2 ||61- string(tokens[2].text) != "def: " || tokens[2].prefixLength != 8 ||62- string(tokens[3].text) != "ghi " || tokens[3].prefixLength != 14 {59+ if string(tokens[0].text) != " " || tokens[0].prefixLength != 0 || tokens[0].trimLength != 0 ||60+ string(tokens[1].text) != "abc: " || tokens[1].prefixLength != 2 || tokens[1].trimLength != 4 ||61+ string(tokens[2].text) != "def: " || tokens[2].prefixLength != 8 || tokens[2].trimLength != 4 ||62+ string(tokens[3].text) != "ghi " || tokens[3].prefixLength != 14 || tokens[3].trimLength != 3 {63 t.Errorf("%s", tokens)64 }65 }66 44 unmodified linesmodified:src/tokenizer.go+3 added-2 removed
18 unmodified lines19 // Token contains the tokenized part of the strings and its prefix length20 type Token struct {21 text []rune22 prefixLength int23+ trimLength int24 }25 26 // Delimiter for tokenizing the input27 type Delimiter struct {53 unmodified lines81 prefixLength := begin82 for idx, token := range tokens {83 // Need to define a new local variable instead of the reused token to take84 // the pointer to it84- ret[idx] = Token{text: token, prefixLength: prefixLength}85+ ret[idx] = Token{token, prefixLength, util.TrimLen(token)}86 prefixLength += len(token)87 }88 return ret89 }143 unmodified lines233 prefixLength = tokens[minIdx].prefixLength234 } else {235 prefixLength = 0236 }236- transTokens[idx] = Token{part, prefixLength}237+ transTokens[idx] = Token{part, prefixLength, util.TrimLen(part)}238 }239 return transTokens240 }modified:test/test_go.rb+47 added
525 unmodified lines526 ]527 assert_equal output, `cat #{tempname} | #{FZF} -fh -n2 -d:`.split($/)528 end529 530+ def test_tiebreak_length_with_nth_trim_length531+ input = [532+ "apple juice bottle 1",533+ "apple ui bottle 2",534+ "app ice bottle 3",535+ "app ic bottle 4",536+ ]537+ writelines tempname, input538+539+ # len(1)540+ output = [541+ "app ice bottle 3",542+ "app ic bottle 4",543+ "apple juice bottle 1",544+ "apple ui bottle 2",545+ ]546+ assert_equal output, `cat #{tempname} | #{FZF} -fa -n1`.split($/)547+548+ # len(1 ~ 2)549+ output = [550+ "apple ui bottle 2",551+ "app ic bottle 4",552+ "apple juice bottle 1",553+ "app ice bottle 3",554+ ]555+ assert_equal output, `cat #{tempname} | #{FZF} -fai -n1..2`.split($/)556+557+ # len(1) + len(2)558+ output = [559+ "app ic bottle 4",560+ "app ice bottle 3",561+ "apple ui bottle 2",562+ "apple juice bottle 1",563+ ]564+ assert_equal output, `cat #{tempname} | #{FZF} -x -f"a i" -n1,2`.split($/)565+566+ # len(2)567+ output = [568+ "apple ui bottle 2",569+ "app ic bottle 4",570+ "app ice bottle 3",571+ "apple juice bottle 1",572+ ]573+ assert_equal output, `cat #{tempname} | #{FZF} -fi -n2`.split($/)574+ assert_equal output, `cat #{tempname} | #{FZF} -fi -n2,1..2`.split($/)575+ end576+577 def test_tiebreak_end_backward_scan578 input = %w[579 foobar-fb580 fubar567 unmodified lines