Implement --expect option to support simple key bindings (#163)
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 9cfecf7 · Browse files · 9 files·+171 added−4 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+171 added−4 removed
- tests:+27 added−0 removed
- other:+144 added−4 removed
Provenance
- Commit
2a167aa- Tree
69b994e- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
9cfecf7
9 files changed+171 added−4 removed
modified:man/man1/fzf.1+11 added
106 unmodified lines107 .TP108 .B "--print-query"109 Print query as the first line110 .TP111+.BI "--expect=" "KEY[,..]"112+Comma-separated list of keys (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,113+or a single character) that can be used to complete fzf in addition to the114+default enter key. When this option is set, fzf will print the name of the key115+pressed as the first line of its output (or as the second line if116+\fB--print-query\fR is also used). The line will be empty if fzf is completed117+with the default enter key.118+.RS119+e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR120+.RE121+.TP122 .B "--sync"123 Synchronous search for multi-staged filtering124 .RS125 e.g. \fBfzf --multi | fzf --sync\fR72 unmodified linesmodified:src/curses/curses.go+23 added-2 removed
59 unmodified lines60 Del61 PgUp62 PgDn63 64+ F165+ F266+ F367+ F468+69+ AltBS70+ AltA71 AltB65- AltF72+ AltC73 AltD67- AltBS74+ AltE75+ AltF76+77+ AltZ = AltA + 'z' - 'a'78 )79 80 // Pallete81 const (251 unmodified lines333 case 70:334 return Event{CtrlE, 0, nil}335 case 77:336 return mouseSequence(sz)337+ case 80:338+ return Event{F1, 0, nil}339+ case 81:340+ return Event{F2, 0, nil}341+ case 82:342+ return Event{F3, 0, nil}343+ case 83:344+ return Event{F4, 0, nil}345 case 49, 50, 51, 52, 53, 54:346 if len(_buf) < 4 {347 return Event{Invalid, 0, nil}348 }37 unmodified lines386 } // _buf[3]387 } // _buf[2]388 } // _buf[2]389 } // _buf[1]390+ if _buf[1] >= 'a' && _buf[1] <= 'z' {391+ return Event{AltA + int(_buf[1]) - 'a', 0, nil}392+ }393 return Event{Invalid, 0, nil}394 }395 396 func GetChar() Event {73 unmodified linesmodified:src/util/util.go+4 added
59 unmodified lines60 }61 return val62 }63 64+func Between(val int, min int, max int) bool {65+ return val >= min && val <= max66+}67+68 // IsTty returns true is stdin is a terminal69 func IsTty() bool {70 return int(C.isatty(C.int(os.Stdin.Fd()))) != 071 }modified:src/options_test.go+24 added-1 removed
1 package fzf2 3-import "testing"3+import (4+ "testing"5 6+ "github.com/junegunn/fzf/src/curses"7+)8+9 func TestDelimiterRegex(t *testing.T) {10 rx := delimiterRegexp("*")11 tokens := rx.FindAllString("-*--*---**---", -1)12 if tokens[0] != "-*" || tokens[1] != "--*" || tokens[2] != "---*" ||55 unmodified lines68 }69 }70 }71 }72+73+func TestExpectKeys(t *testing.T) {74+ keys := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g")75+ check := func(key int, expected int) {76+ if key != expected {77+ t.Errorf("%d != %d", key, expected)78+ }79+ }80+ check(len(keys), 9)81+ check(keys[0], curses.CtrlZ)82+ check(keys[1], curses.AltZ)83+ check(keys[2], curses.F2)84+ check(keys[3], curses.AltZ+'@')85+ check(keys[4], curses.AltA)86+ check(keys[5], curses.AltZ+'!')87+ check(keys[6], curses.CtrlA+'g'-'a')88+ check(keys[7], curses.AltZ+'J')89+ check(keys[8], curses.AltZ+'g')90+}modified:src/options.go+33 added
3 unmodified lines4 "fmt"5 "os"6 "regexp"7 "strings"8+ "unicode/utf8"9 10+ "github.com/junegunn/fzf/src/curses"11+12 "github.com/junegunn/go-shellwords"13 )14 15 const usage = `usage: fzf [options]29 unmodified lines45 -1, --select-1 Automatically select the only match46 -0, --exit-0 Exit immediately when there's no match47 -f, --filter=STR Filter mode. Do not start interactive finder.48 --print-query Print query as the first line49+ --expect=KEYS Comma-separated list of keys to complete fzf50 --sync Synchronous search for multi-staged filtering51 (e.g. 'fzf --multi | fzf --sync')52 53 Environment variables42 unmodified lines96 Query string97 Select1 bool98 Exit0 bool99 Filter *string100+ Expect []int101 PrintQuery bool102 Sync bool103 Version bool104 }18 unmodified lines123 Query: "",124 Select1: false,125 Exit0: false,126 Filter: nil,127+ Expect: []int{},128 PrintQuery: false,129 Sync: false,130 Version: false}131 }64 unmodified lines196 }197 return rx198 }199 200+func isAlphabet(char uint8) bool {201+ return char >= 'a' && char <= 'z'202+}203+204+func parseKeyChords(str string) []int {205+ var chords []int206+ for _, key := range strings.Split(str, ",") {207+ lkey := strings.ToLower(key)208+ if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {209+ chords = append(chords, curses.CtrlA+int(lkey[5])-'a')210+ } else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {211+ chords = append(chords, curses.AltA+int(lkey[4])-'a')212+ } else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {213+ chords = append(chords, curses.F1+int(key[1])-'1')214+ } else if utf8.RuneCountInString(key) == 1 {215+ chords = append(chords, curses.AltZ+int([]rune(key)[0]))216+ } else {217+ errorExit("unsupported key: " + key)218+ }219+ }220+ return chords221+}222+223 func parseOptions(opts *Options, allArgs []string) {224 for i := 0; i < len(allArgs); i++ {225 arg := allArgs[i]226 switch arg {9 unmodified lines236 opts.Query = nextString(allArgs, &i, "query string required")237 case "-f", "--filter":238 filter := nextString(allArgs, &i, "query string required")239 opts.Filter = &filter240+ case "--expect":241+ opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"))242 case "-d", "--delimiter":243 opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))244 case "-n", "--nth":245 opts.Nth = splitNth(nextString(allArgs, &i, "nth expression required"))69 unmodified lines315 } else if match, value := optString(arg, "--with-nth="); match {316 opts.WithNth = splitNth(value)317 } else if match, _ := optString(arg, "-s|--sort="); match {318 opts.Sort = 1 // Don't care319+ } else if match, value := optString(arg, "--expect="); match {320+ opts.Expect = parseKeyChords(value)321 } else {322 errorExit("unknown option: " + arg)323 }324 }26 unmodified linesmodified:src/terminal.go+24 added
26 unmodified lines27 offset int28 yanked []rune29 input []rune30 multi bool31+ expect []int32+ pressed int33 printQuery bool34 count int35 progress int36 reading bool55 unmodified lines92 offset: 0,93 yanked: []rune{},94 input: input,95 multi: opts.Multi,96+ expect: opts.Expect,97+ pressed: 0,98 printQuery: opts.PrintQuery,99 merger: EmptyMerger,100 selected: make(map[*string]selectedItem),101 reqBox: util.NewEventBox(),51 unmodified lines153 func (t *Terminal) output() {154 if t.printQuery {155 fmt.Println(string(t.input))156 }157+ if len(t.expect) > 0 {158+ if t.pressed == 0 {159+ fmt.Println()160+ } else if util.Between(t.pressed, C.AltA, C.AltZ) {161+ fmt.Printf("alt-%c\n", t.pressed+'a'-C.AltA)162+ } else if util.Between(t.pressed, C.F1, C.F4) {163+ fmt.Printf("f%c\n", t.pressed+'1'-C.F1)164+ } else if util.Between(t.pressed, C.CtrlA, C.CtrlZ) {165+ fmt.Printf("ctrl-%c\n", t.pressed+'a'-C.CtrlA)166+ } else {167+ fmt.Printf("%c\n", t.pressed-C.AltZ)168+ }169+ }170 if len(t.selected) == 0 {171 cnt := t.merger.Length()172 if cnt > 0 && cnt > t.cy {173 fmt.Println(t.merger.Get(t.cy).AsString())377 unmodified lines551 }552 req(reqInfo)553 }554 }555+ for _, key := range t.expect {556+ if event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ {557+ t.pressed = key558+ req(reqClose)559+ break560+ }561+ }562 switch event.Type {563 case C.Invalid:564 t.mutex.Unlock()565 continue171 unmodified linesmodified:test/test_go.rb+27 added
423 unmodified lines424 tmux.send_keys '00'425 tmux.send_keys :BTab, :BTab, :BTab, :Enter426 assert_equal %w[1000 900 800], readonce.split($/)427 end428+429+ def test_expect430+ test = lambda do |key, feed, expected = key|431+ tmux.send_keys "seq 1 100 | #{fzf :expect, key}", :Enter432+ tmux.until { |lines| lines[-2].include? '100/100' }433+ tmux.send_keys '55'434+ tmux.send_keys *feed435+ assert_equal [expected, '55'], readonce.split($/)436+ end437+ test.call 'ctrl-t', 'C-T'438+ test.call 'ctrl-t', 'Enter', ''439+ test.call 'alt-c', [:Escape, :c]440+ test.call 'f1', 'f1'441+ test.call 'f2', 'f2'442+ test.call 'f3', 'f3'443+ test.call 'f2,f4', 'f2', 'f2'444+ test.call 'f2,f4', 'f4', 'f4'445+ test.call '@', '@'446+ end447+448+ def test_expect_print_query449+ tmux.send_keys "seq 1 100 | #{fzf '--expect=alt-z', :print_query}", :Enter450+ tmux.until { |lines| lines[-2].include? '100/100' }451+ tmux.send_keys '55'452+ tmux.send_keys :Escape, :z453+ assert_equal ['55', 'alt-z', '55'], readonce.split($/)454+ end455 end456 457 module TestShell458 def setup148 unmodified linesmodified:CHANGELOG.md+24 added
1234567891011121314151617181920212223242526272829303177 unmodified linesCHANGELOG=========
0.9.6-----
### New features
#### Added `--expect` option (#163)
If you provide a comma-separated list of keys with `--expect` option, fzf willallow you to select the match and complete the finder when any of the keys ispressed. Additionally, fzf will print the name of the key pressed as the firstline of the output so that your script can decide what to do next based on theinformation.
```shfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@```
The updated vim plugin uses this option to implement[ctrlp](https://github.com/kien/ctrlp.vim)-compatible key bindings.
### Bug fixes
- Fixed to ignore ANSI escape code `\e[K` (#162)
0.9.5-----
### New features77 unmodified linesmodified:install+1 added-1 removed
1 #!/usr/bin/env bash2 3-version=0.9.53+version=0.9.64 5 cd $(dirname $BASH_SOURCE)6 fzf_base=$(pwd)7 261 unmodified lines