Skip to content
Myr

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

9 files+171 added−4 removed

modified:man/man1/fzf.1+11 added
106 unmodified lines
107.TP108.B "--print-query"109Print query as the first line110.TP111.BI "--expect=" "KEY[,..]"112Comma-separated list of keys (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,113or a single character) that can be used to complete fzf in addition to the114default enter key. When this option is set, fzf will print the name of the key115pressed 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 completed117with the default enter key.118.RS119e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR120.RE121.TP122.B "--sync"123Synchronous search for multi-staged filtering124.RS125e.g. \fBfzf --multi | fzf --sync\fR
72 unmodified lines
modified:src/curses/curses.go+23 added-2 removed
59 unmodified lines
60 Del61 PgUp62 PgDn6364 F165 F266 F367 F46869 AltBS70 AltA71 AltB65 AltF72 AltC73 AltD67 AltBS74 AltE75 AltF7677 AltZ = AltA + 'z' - 'a'78)7980// Pallete81const (
251 unmodified lines
333 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 lines
386 } // _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}395396func GetChar() Event {
73 unmodified lines
modified:src/util/util.go+4 added
59 unmodified lines
60 }61 return val62}6364func Between(val int, min int, max int) bool {65 return val >= min && val <= max66}6768// IsTty returns true is stdin is a terminal69func IsTty() bool {70 return int(C.isatty(C.int(os.Stdin.Fd()))) != 071}
modified:src/options_test.go+24 added-1 removed
1package fzf23import "testing"3import (4 "testing"56 "github.com/junegunn/fzf/src/curses"7)89func TestDelimiterRegex(t *testing.T) {10 rx := delimiterRegexp("*")11 tokens := rx.FindAllString("-*--*---**---", -1)12 if tokens[0] != "-*" || tokens[1] != "--*" || tokens[2] != "---*" ||
55 unmodified lines
68 }69 }70 }71}7273func 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 lines
4 "fmt"5 "os"6 "regexp"7 "strings"8 "unicode/utf8"910 "github.com/junegunn/fzf/src/curses"1112 "github.com/junegunn/go-shellwords"13)1415const usage = `usage: fzf [options]
29 unmodified lines
45 -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')5253 Environment variables
42 unmodified lines
96 Query string97 Select1 bool98 Exit0 bool99 Filter *string100 Expect []int101 PrintQuery bool102 Sync bool103 Version bool104}
18 unmodified lines
123 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 lines
196 }197 return rx198}199200func isAlphabet(char uint8) bool {201 return char >= 'a' && char <= 'z'202}203204func 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}222223func parseOptions(opts *Options, allArgs []string) {224 for i := 0; i < len(allArgs); i++ {225 arg := allArgs[i]226 switch arg {
9 unmodified lines
236 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 lines
315 } 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 lines
modified:src/terminal.go+24 added
26 unmodified lines
27 offset int28 yanked []rune29 input []rune30 multi bool31 expect []int32 pressed int33 printQuery bool34 count int35 progress int36 reading bool
55 unmodified lines
92 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 lines
153func (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 lines
551 }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 continue
171 unmodified lines
modified:test/test_go.rb+27 added
423 unmodified lines
424 tmux.send_keys '00'425 tmux.send_keys :BTab, :BTab, :BTab, :Enter426 assert_equal %w[1000 900 800], readonce.split($/)427 end428429 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 end447448 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 end455end456457module TestShell458 def setup
148 unmodified lines
modified:CHANGELOG.md+24 added
modified:install+1 added-1 removed
1#!/usr/bin/env bash23version=0.9.53version=0.9.645cd $(dirname $BASH_SOURCE)6fzf_base=$(pwd)7
261 unmodified lines