Skip to content
Myr

Make --accept-nth and --with-nth support templates

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 378137d · Browse files · 9 files+158 added−48 removed
This commit

State

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

Diff stats

9 files+158 added−48 removed

  • tests:+16 added−0 removed
  • other:+142 added−48 removed

9 files+158 added−48 removed

modified:man/man1/fzf.1+25 added-4 removed
115 unmodified lines
116transformed lines (unlike in \fB\-\-preview\fR where fields are extracted from117the original lines) because fzf doesn't allow searching against the hidden118fields.119.TP120.BI "\-\-with\-nth=" "N[,..]"121Transform the presentation of each line using field index expressions120.BI "\-\-with\-nth=" "N[,..] or TEMPLATE"121Transform the presentation of each line using the field index expressions.122For advanced transformation, you can provide a template containing field index123expressions in curly braces.124125.RS126e.g.127 # Single expression: drop the first field128 echo foo bar baz | fzf --with-nth 2..129130 # Use template to rearrange fields131 echo foo,bar,baz | fzf --delimiter , --with-nth '{1},{3},{2},{1..2}'132.RE133.TP123.BI "\-\-accept\-nth=" "N[,..]"134.BI "\-\-accept\-nth=" "N[,..] or TEMPLATE"135Define which fields to print on accept. The last delimiter is stripped from the125output.136output. For advanced transformation, you can provide a template containing137field index expressions in curly braces.138139.RS140e.g.141 # Single expression142 echo foo bar baz | fzf --accept-nth 2143144 # Template145 echo foo bar baz | fzf --accept-nth '1st: {1}, 2nd: {2}, 3rd: {3}'146.RE147.TP148.B "+s, \-\-no\-sort"149Do not sort the result150.TP
1733 unmodified lines
modified:src/util/chars.go-5 removed
182 unmodified lines
183 }184 return whitespaces185}186187func (chars *Chars) TrimTrailingWhitespaces() {188 whitespaces := chars.TrailingWhitespaces()189 chars.slice = chars.slice[0 : len(chars.slice)-whitespaces]190}191187func (chars *Chars) TrimSuffix(runes []rune) {188 lastIdx := len(chars.slice)189 firstIdx := lastIdx - len(runes)190 if firstIdx < 0 {
136 unmodified lines
modified:src/core.go+3 added-4 removed
94 unmodified lines
95 cache := NewChunkCache()96 var chunkList *ChunkList97 var itemIndex int3298 header := make([]string, 0, opts.HeaderLines)99 if len(opts.WithNth) == 0 {99 if opts.WithNth == nil {100 chunkList = NewChunkList(cache, func(item *Item, data []byte) bool {101 if len(header) < opts.HeaderLines {102 header = append(header, byteString(data))103 eventBox.Set(EvtHeader, header)
4 unmodified lines
108 itemIndex++109 return true110 })111 } else {112 nthTransformer := opts.WithNth(opts.Delimiter)113 chunkList = NewChunkList(cache, func(item *Item, data []byte) bool {114 tokens := Tokenize(byteString(data), opts.Delimiter)115 if opts.Ansi && opts.Theme.Colored && len(tokens) > 1 {116 var ansiState *ansiState
10 unmodified lines
127 token.text.Prepend("\x1b[m")128 }129 }130 }130 trans := Transform(tokens, opts.WithNth)131 transformed := JoinTokens(trans)131 transformed := nthTransformer(tokens)132 if len(header) < opts.HeaderLines {133 header = append(header, transformed)134 eventBox.Set(EvtHeader, header)135 return false136 }137 item.text, item.colors = ansiProcessor(stringBytes(transformed))138 item.text.TrimTrailingWhitespaces()138 item.text.Index = itemIndex139 item.origText = &data140 itemIndex++141 return true
367 unmodified lines
modified:src/options.go+60 added-6 removed
542 unmodified lines
543 Inputless bool544 Case Case545 Normalize bool546 Nth []Range547 WithNth []Range548 AcceptNth []Range547 WithNth func(Delimiter) func([]Token) string548 AcceptNth func(Delimiter) func([]Token) string549 Delimiter Delimiter550 Sort int551 Track trackOption552 Tac bool
113 unmodified lines
666 Inputless: false,667 Case: CaseSmart,668 Normalize: true,669 Nth: make([]Range, 0),670 WithNth: make([]Range, 0),671 AcceptNth: make([]Range, 0),670 Delimiter: Delimiter{},671 Sort: 1000,672 Track: trackDisabled,673 Tac: false,
94 unmodified lines
768 }769 return ranges, nil770}771772func nthTransformer(str string) (func(Delimiter) func([]Token) string, error) {773 // ^[0-9,-.]+$"774 if match, _ := regexp.MatchString("^[0-9,-.]+$", str); match {775 nth, err := splitNth(str)776 if err != nil {777 return nil, err778 }779 return func(Delimiter) func([]Token) string {780 return func(tokens []Token) string {781 return JoinTokens(Transform(tokens, nth))782 }783 }, nil784 }785786 // {...} {...} ...787 placeholder := regexp.MustCompile("{[0-9,-.]+}")788 indexes := placeholder.FindAllStringIndex(str, -1)789 if indexes == nil {790 return nil, errors.New("template should include at least 1 placeholder: " + str)791 }792793 type NthParts struct {794 str string795 nth []Range796 }797798 parts := make([]NthParts, len(indexes))799 idx := 0800 for _, index := range indexes {801 if idx < index[0] {802 parts = append(parts, NthParts{str: str[idx:index[0]]})803 }804 if nth, err := splitNth(str[index[0]+1 : index[1]-1]); err == nil {805 parts = append(parts, NthParts{nth: nth})806 }807 idx = index[1]808 }809 if idx < len(str) {810 parts = append(parts, NthParts{str: str[idx:]})811 }812813 return func(delimiter Delimiter) func([]Token) string {814 return func(tokens []Token) string {815 str := ""816 for _, holder := range parts {817 if holder.nth != nil {818 str += StripLastDelimiter(JoinTokens(Transform(tokens, holder.nth)), delimiter)819 } else {820 str += holder.str821 }822 }823 return str824 }825 }, nil826}827828func delimiterRegexp(str string) Delimiter {829 // Special handling of \t830 str = strings.ReplaceAll(str, "\\t", "\t")831
1608 unmodified lines
2440 str, err := nextString("nth expression required")2441 if err != nil {2442 return err2443 }2390 if opts.WithNth, err = splitNth(str); err != nil {2444 if opts.WithNth, err = nthTransformer(str); err != nil {2445 return err2446 }2447 case "--accept-nth":2448 str, err := nextString("nth expression required")2449 if err != nil {2450 return err2451 }2398 if opts.AcceptNth, err = splitNth(str); err != nil {2452 if opts.AcceptNth, err = nthTransformer(str); err != nil {2453 return err2454 }2455 case "-s", "--sort":2456 if opts.Sort, err = optionalNumeric(1); err != nil {
1013 unmodified lines
modified:src/terminal.go+8 added-4 removed
303 unmodified lines
304 ansi bool305 nthAttr tui.Attr306 nth []Range307 nthCurrent []Range308 acceptNth []Range308 acceptNth func([]Token) string309 tabstop int310 margin [4]sizeSpec311 padding [4]sizeSpec312 unicode bool
605 unmodified lines
918 ansi: opts.Ansi,919 nthAttr: opts.Theme.Nth.Attr,920 nth: opts.Nth,921 nthCurrent: opts.Nth,922 acceptNth: opts.AcceptNth,922 tabstop: opts.Tabstop,923 hasStartActions: false,924 hasResultActions: false,925 hasFocusActions: false,
33 unmodified lines
959 executing: util.NewAtomicBool(false),960 lastAction: actStart,961 lastFocus: minItem.Index(),962 numLinesCache: make(map[int32]numLinesCacheValue)}963 if opts.AcceptNth != nil {964 t.acceptNth = opts.AcceptNth(t.delimiter)965 }966967 // This should be called before accessing tui.Color*968 tui.InitTheme(opts.Theme, renderer.DefaultTheme(), opts.Black, opts.InputBorderShape.Visible(), opts.HeaderBorderShape.Visible())969
601 unmodified lines
1571 }1572 transform := func(item *Item) string {1573 return item.AsString(t.ansi)1574 }1573 if len(t.acceptNth) > 0 {1575 if t.acceptNth != nil {1576 transform = func(item *Item) string {1575 return JoinTokens(StripLastDelimiter(Transform(Tokenize(item.AsString(t.ansi), t.delimiter), t.acceptNth), t.delimiter))1577 tokens := Tokenize(item.AsString(t.ansi), t.delimiter)1578 transformed := t.acceptNth(tokens)1579 return StripLastDelimiter(transformed, t.delimiter)1580 }1581 }1582 found := len(t.selected) > 01583 if !found {
4693 unmodified lines
modified:src/tokenizer.go+11 added-24 removed
4 unmodified lines
5 "fmt"6 "regexp"7 "strconv"8 "strings"9 "unicode"1011 "github.com/junegunn/fzf/src/util"12)13
197 unmodified lines
211 }212 return withPrefixLengths(tokens, 0)213}214214// StripLastDelimiter removes the trailing delimiter and whitespaces from the215// last token.216func StripLastDelimiter(tokens []Token, delimiter Delimiter) []Token {217 if len(tokens) == 0 {218 return tokens219 }220221 lastToken := tokens[len(tokens)-1]222223 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 }215// StripLastDelimiter removes the trailing delimiter and whitespaces216func StripLastDelimiter(str string, delimiter Delimiter) string {217 if delimiter.str != nil {218 str = strings.TrimSuffix(str, *delimiter.str)219 } else if delimiter.regex != nil {220 locs := delimiter.regex.FindAllStringIndex(str, -1)221 if len(locs) > 0 {222 lastLoc := locs[len(locs)-1]223 str = str[:lastLoc[0]]224 }236 lastToken.text.TrimTrailingWhitespaces()225 }238239 return tokens226 return strings.TrimRightFunc(str, unicode.IsSpace)227}228229// JoinTokens concatenates the tokens into a single string230func JoinTokens(tokens []Token) string {
81 unmodified lines
modified:test/test_core.rb+9 added
1770 unmodified lines
1771 # Last delimiter and the whitespaces are removed1772 assert_equal ['bar,bar,foo :,:bazfoo'], File.readlines(tempname, chomp: true)1773 end1774 end17751776 def test_accept_nth_template1777 tmux.send_keys %(echo "foo ,bar,baz" | #{FZF} -d, --accept-nth '1st: {1}, 3rd: {3}, 2nd: {2}' --sync --bind start:accept > #{tempname}), :Enter1778 wait do1779 assert_path_exists tempname1780 # Last delimiter and the whitespaces are removed1781 assert_equal ['1st: foo, 3rd: baz, 2nd: bar'], File.readlines(tempname, chomp: true)1782 end1783 end1784end
modified:test/test_filter.rb+7 added
57 unmodified lines
58 'hello world ',59 `#{FZF} -f"^he hehe" -x -n 2.. --with-nth 2,1,1 < #{tempname}`.chomp60 end6162 def test_with_nth_template63 writelines(['hello world ', 'byebye'])64 assert_equal \65 'hello world ',66 `#{FZF} -f"^he he.he." -x -n 2.. --with-nth '{2} {1}. {1}.' < #{tempname}`.chomp67 end6869 def test_with_nth_ansi70 writelines(["\x1b[33mhello \x1b[34;1mworld\x1b[m ", 'byebye'])71 assert_equal \72 'hello world ',
237 unmodified lines
modified:CHANGELOG.md+35 added-1 removed
1CHANGELOG2=========340.60.05------67- Added `--accept-nth` for choosing output fields8 ```sh9 ps -ef | fzf --multi --header-lines 1 | awk '{print $2}'10 # Becomes11 ps -ef | fzf --multi --header-lines 1 --accept-nth 21213 git branch | fzf | cut -c3-14 # Can be rewritten as15 git branch | fzf --accept-nth -116 ```17- `--accept-nth` and `--with-nth` now support a template that includes multiple field index expressions in curly braces18 ```sh19 echo foo,bar,baz | fzf --delimiter , --accept-nth '{1}, {3}, {2}'20 # foo, baz, bar2122 echo foo,bar,baz | fzf --delimiter , --with-nth '{1},{3},{2},{1..2}'23 # foo,baz,bar,foo,bar24 ```25- Added `exclude` and `exclude-multi` actions for dynamically excluding items26 ```sh27 seq 100 | fzf --bind 'ctrl-x:exclude'2829 # 'exclude-multi' will exclude the selected items or the current item30 seq 100 | fzf --multi --bind 'ctrl-x:exclude-multi'31 ```32- Preview window now prints wrap indicator when wrapping is enabled33 ```sh34 seq 100 | xargs | fzf --wrap --preview 'echo {}' --preview-window wrap35 ```36- Bug fixes and improvements37380.59.039------40_Release highlights: https://junegunn.github.io/fzf/releases/0.59.0/_41
356 unmodified lines
398- Added `offset-middle` action to place the current item is in the middle of the screen399- fzf will not start the initial reader when `reload` or `reload-sync` is bound to `start` event. `fzf < /dev/null` or `: | fzf` are no longer required and extraneous `load` event will not fire due to the empty list.400 ```sh401 # Now this will work as expected. Previously, this would print an invalid header line.368 # `fzf < /dev/null` or `: | fzf` would fix the problem, but then an extraneous 402 # `fzf < /dev/null` or `: | fzf` would fix the problem, but then an extraneous403 # `load` event would fire and the header would be prematurely updated.404 fzf --header 'Loading ...' --header-lines 1 \405 --bind 'start:reload:sleep 1; ps -ef' \406 --bind 'load:change-header:Loaded!'
2158 unmodified lines