Add --accept-nth option to transform the output
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This option can be used to replace a sed or awk in the post-processing step. ps -ef | fzf --multi --header-lines 1 | awk '{print $2}' ps -ef | fzf --multi --header-lines 1 --accept-nth 2 This may not be a very "Unix-y" thing to do, so I've always felt that fzf shouldn't have such an option, but I've finally changed my mind because: * fzf can be configured with a custom delimiter that is a fixed string or a regular expression. * In such cases, you'd need to repeat the delimiter again in the post-processing step. * Also, tools like awk or sed may interpret a regular expression differently, causing mismatches. You can still use sed, cut, or awk if you prefer. Close #3987 Close #1323
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+113 added−10 removed
- tests:+26 added−0 removed
- other:+87 added−10 removed
Provenance
- Commit
2b58458- Tree
6a4458b- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
a1994ff
9 files changed+113 added−10 removed
modified:man/man1/fzf.1+4 added
118 unmodified lines119 .TP120 .BI "\-\-with\-nth=" "N[,..]"121 Transform the presentation of each line using field index expressions122 .TP123+.BI "\-\-accept\-nth=" "N[,..]"124+Define which fields to print on accept. The last delimiter is stripped from the125+output.126+.TP127 .B "+s, \-\-no\-sort"128 Do not sort the result129 .TP130 .BI "\-d, \-\-delimiter=" "STR"1730 unmodified linesmodified:src/util/chars.go+21 added
187 unmodified lines188 whitespaces := chars.TrailingWhitespaces()189 chars.slice = chars.slice[0 : len(chars.slice)-whitespaces]190 }191 192+func (chars *Chars) TrimSuffix(runes []rune) {193+ lastIdx := len(chars.slice)194+ firstIdx := lastIdx - len(runes)195+ if firstIdx < 0 {196+ return197+ }198+199+ for i := firstIdx; i < lastIdx; i++ {200+ char := chars.Get(i)201+ if char != runes[i-firstIdx] {202+ return203+ }204+ }205+206+ chars.slice = chars.slice[0:firstIdx]207+}208+209+func (chars *Chars) SliceRight(last int) {210+ chars.slice = chars.slice[:last]211+}212+213 func (chars *Chars) ToString() string {214 if runes := chars.optionalRunes(); runes != nil {215 return string(runes)216 }115 unmodified linesmodified:src/core.go+1 added-1 removed
126 unmodified lines127 }128 }129 }130 trans := Transform(tokens, opts.WithNth)131- transformed := joinTokens(trans)131+ transformed := JoinTokens(trans)132 if len(header) < opts.HeaderLines {133 header = append(header, transformed)134 eventBox.Set(EvtHeader, header)135 return false342 unmodified linesmodified:src/options.go+11 added
39 unmodified lines40 for limiting search scope. Each can be a non-zero41 integer or a range expression ([BEGIN]..[END]).42 --with-nth=N[,..] Transform the presentation of each line using43 field index expressions44+ --accept-nth=N[,..] Define which fields to print on accept45 -d, --delimiter=STR Field delimiter regex (default: AWK-style)46 +s, --no-sort Do not sort the result47 --literal Do not normalize latin script letters48 --tail=NUM Maximum number of items to keep in memory495 unmodified lines544 Case Case545 Normalize bool546 Nth []Range547 WithNth []Range548+ AcceptNth []Range549 Delimiter Delimiter550 Sort int551 Track trackOption552 Tac bool114 unmodified lines667 Case: CaseSmart,668 Normalize: true,669 Nth: make([]Range, 0),670 WithNth: make([]Range, 0),671+ AcceptNth: make([]Range, 0),672 Delimiter: Delimiter{},673 Sort: 1000,674 Track: trackDisabled,675 Tac: false,1709 unmodified lines2385 }2386 if opts.WithNth, err = splitNth(str); err != nil {2387 return err2388 }2389+ case "--accept-nth":2390+ str, err := nextString("nth expression required")2391+ if err != nil {2392+ return err2393+ }2394+ if opts.AcceptNth, err = splitNth(str); err != nil {2395+ return err2396+ }2397 case "-s", "--sort":2398 if opts.Sort, err = optionalNumeric(1); err != nil {2399 return err2400 }1011 unmodified linesmodified:src/pattern.go+2 added
401 unmodified lines402 }403 404 tokens := Tokenize(item.text.ToString(), p.delimiter)405 ret := Transform(tokens, p.nth)406+ // TODO: We could apply StripLastDelimiter to exclude the last delimiter from407+ // the search allowing suffix match with a string or a regex delimiter.408 item.transformed = &transformed{p.revision, ret}409 return ret410 }411 15 unmodified linesmodified:src/terminal.go+14 added-4 removed
303 unmodified lines304 ansi bool305 nthAttr tui.Attr306 nth []Range307 nthCurrent []Range308+ acceptNth []Range309 tabstop int310 margin [4]sizeSpec311 padding [4]sizeSpec312 unicode bool601 unmodified lines914 ansi: opts.Ansi,915 nthAttr: opts.Theme.Nth.Attr,916 nth: opts.Nth,917 nthCurrent: opts.Nth,918+ acceptNth: opts.AcceptNth,919 tabstop: opts.Tabstop,920 hasStartActions: false,921 hasResultActions: false,922 hasFocusActions: false,639 unmodified lines1562 }1563 for _, s := range t.printQueue {1564 t.printer(s)1565 }1566+ transform := func(item *Item) string {1567+ return item.AsString(t.ansi)1568+ }1569+ if len(t.acceptNth) > 0 {1570+ transform = func(item *Item) string {1571+ return JoinTokens(StripLastDelimiter(Transform(Tokenize(item.AsString(t.ansi), t.delimiter), t.acceptNth), t.delimiter))1572+ }1573+ }1574 found := len(t.selected) > 01575 if !found {1576 current := t.currentItem()1577 if current != nil {1568- t.printer(current.AsString(t.ansi))1578+ t.printer(transform(current))1579 found = true1580 }1581 } else {1582 for _, sel := range t.sortSelected() {1573- t.printer(sel.item.AsString(t.ansi))1583+ t.printer(transform(sel.item))1584 }1585 }1586 return found1587 }2268 unmodified lines3856 if nth, err := splitNth(match[3 : len(match)-1]); err == nil {3857 elems, prefixLength := awkTokenizer(params.query)3858 tokens := withPrefixLengths(elems, prefixLength)3859 trans := Transform(tokens, nth)3850- result := joinTokens(trans)3860+ result := JoinTokens(trans)3861 if !flags.preserveSpace {3862 result = strings.TrimSpace(result)3863 }3864 return params.executor.QuoteEntry(result)41 unmodified lines3906 3907 replace = func(item *Item) string {3908 tokens := Tokenize(item.AsString(params.stripAnsi), params.delimiter)3909 trans := Transform(tokens, ranges)3900- str := joinTokens(trans)3910+ str := JoinTokens(trans)3911 3912 // trim the last delimiter3913 if params.delimiter.str != nil {3914 str = strings.TrimSuffix(str, *params.delimiter.str)2331 unmodified linesmodified:src/tokenizer_test.go+3 added-3 removed
83 unmodified lines84 tokens := Tokenize(input, Delimiter{})85 {86 ranges, _ := splitNth("1,2,3")87 tx := Transform(tokens, ranges)88- if joinTokens(tx) != "abc: def: ghi: " {88+ if JoinTokens(tx) != "abc: def: ghi: " {89 t.Errorf("%s", tx)90 }91 }92 {93 ranges, _ := splitNth("1..2,3,2..,1")94 tx := Transform(tokens, ranges)95- if string(joinTokens(tx)) != "abc: def: ghi: def: ghi: jklabc: " ||95+ if string(JoinTokens(tx)) != "abc: def: ghi: def: ghi: jklabc: " ||96 len(tx) != 4 ||97 tx[0].text.ToString() != "abc: def: " || tx[0].prefixLength != 2 ||98 tx[1].text.ToString() != "ghi: " || tx[1].prefixLength != 14 ||99 tx[2].text.ToString() != "def: ghi: jkl" || tx[2].prefixLength != 8 ||6 unmodified lines106 tokens := Tokenize(input, delimiterRegexp(":"))107 {108 ranges, _ := splitNth("1..2,3,2..,1")109 tx := Transform(tokens, ranges)110- if joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||110+ if JoinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||111 len(tx) != 4 ||112 tx[0].text.ToString() != " abc: def:" || tx[0].prefixLength != 0 ||113 tx[1].text.ToString() != " ghi:" || tx[1].prefixLength != 12 ||114 tx[2].text.ToString() != " def: ghi: jkl" || tx[2].prefixLength != 6 ||11 unmodified linesmodified:src/tokenizer.go+31 added-2 removed
209 unmodified lines210 }211 return withPrefixLengths(tokens, 0)212 }213 214+// StripLastDelimiter removes the trailing delimiter and whitespaces from the215+// last token.216+func StripLastDelimiter(tokens []Token, delimiter Delimiter) []Token {217+ if len(tokens) == 0 {218+ return tokens219+ }220+221+ lastToken := tokens[len(tokens)-1]222+223+ if delimiter.str == nil && delimiter.regex == nil {224+ lastToken.text.TrimTrailingWhitespaces()225+ } else {226+ if delimiter.str != nil {227+ lastToken.text.TrimSuffix([]rune(*delimiter.str))228+ } else if delimiter.regex != nil {229+ str := lastToken.text.ToString()230+ locs := delimiter.regex.FindAllStringIndex(str, -1)231+ if len(locs) > 0 {232+ lastLoc := locs[len(locs)-1]233+ lastToken.text.SliceRight(lastLoc[0])234+ }235+ }236+ lastToken.text.TrimTrailingWhitespaces()237+ }238+239+ return tokens240+}241+242+// JoinTokens concatenates the tokens into a single string214-func joinTokens(tokens []Token) string {243+func JoinTokens(tokens []Token) string {244 var output bytes.Buffer245 for _, token := range tokens {246 output.WriteString(token.text.ToString())247 }9 unmodified lines257 minIdx := 0258 if r.begin == r.end {259 idx := r.begin260 if idx == rangeEllipsis {232- chars := util.ToChars(stringBytes(joinTokens(tokens)))261+ chars := util.ToChars(stringBytes(JoinTokens(tokens)))262 parts = append(parts, &chars)263 } else {264 if idx < 0 {265 idx += numTokens + 159 unmodified linesmodified:test/test_core.rb+26 added
1663 unmodified lines1664 assert_path_exists tempname1665 assert_equal '', File.read(tempname).chomp1666 end1667 end1668+1669+ def test_accept_nth1670+ tmux.send_keys %((echo "foo bar baz"; echo "bar baz foo") | #{FZF} --multi --accept-nth 2,2 --sync --bind start:select-all+accept > #{tempname}), :Enter1671+ wait do1672+ assert_path_exists tempname1673+ assert_equal ['bar bar', 'baz baz'], File.readlines(tempname, chomp: true)1674+ end1675+ end1676+1677+ def test_accept_nth_string_delimiter1678+ tmux.send_keys %(echo "foo ,bar,baz" | #{FZF} -d, --accept-nth 2,2,1,3,1 --sync --bind start:accept > #{tempname}), :Enter1679+ wait do1680+ assert_path_exists tempname1681+ # Last delimiter and the whitespaces are removed1682+ assert_equal ['bar,bar,foo ,bazfoo'], File.readlines(tempname, chomp: true)1683+ end1684+ end1685+1686+ def test_accept_nth_regex_delimiter1687+ tmux.send_keys %(echo "foo :,:bar,baz" | #{FZF} --delimiter='[:,]+' --accept-nth 2,2,1,3,1 --sync --bind start:accept > #{tempname}), :Enter1688+ wait do1689+ assert_path_exists tempname1690+ # Last delimiter and the whitespaces are removed1691+ assert_equal ['bar,bar,foo :,:bazfoo'], File.readlines(tempname, chomp: true)1692+ end1693+ end1694 end