Skip to content
Myr

Add bind action for executing arbitrary command (#265)

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

e.g. fzf --bind "ctrl-m:execute(less {})" fzf --bind "ctrl-t:execute[tmux new-window -d 'vim {}']"

authored by Junegunn Choi · committed by Junegunn Choi · parent fe5b190 · Browse files · 5 files+113 added−22 removed
This commit

State

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

Diff stats

5 files+113 added−22 removed

  • tests:+21 added−0 removed
  • other:+92 added−22 removed

5 files+113 added−22 removed

modified:src/item.go+7 added-2 removed
84 unmodified lines
85}8687// AsString returns the original string88func (i *Item) AsString() string {89 return *i.StringPtr()90}9192// StringPtr returns the pointer to the original string93func (i *Item) StringPtr() *string {94 if i.origText != nil {90 return *i.origText95 return i.origText96 }92 return *i.text97 return i.text98}99100func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {101 if len(item.colors) == 0 {
151 unmodified lines
modified:src/options_test.go+22 added-4 removed
134 unmodified lines
135 if action != expected {136 t.Errorf("%d != %d", action, expected)137 }138 }139 checkString := func(action string, expected string) {140 if action != expected {141 t.Errorf("%d != %d", action, expected)142 }143 }144 keymap := defaultKeymap()145 execmap := make(map[int]string)146 check(actBeginningOfLine, keymap[curses.CtrlA])141 keymap, toggleSort :=142 parseKeymap(keymap, false,143 "ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down")147 keymap, execmap, toggleSort :=148 parseKeymap(keymap, execmap, false,149 "ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+150 "f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute:less {}:,"+151 "alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};")152 if !toggleSort {153 t.Errorf("toggleSort not set")154 }155 check(actKillLine, keymap[curses.CtrlA])156 check(actToggleSort, keymap[curses.CtrlB])157 check(actPageUp, keymap[curses.AltZ+'c'])158 check(actPageDown, keymap[curses.AltZ])159 check(actExecute, keymap[curses.F1])160 check(actExecute, keymap[curses.F2])161 check(actExecute, keymap[curses.F3])162 check(actExecute, keymap[curses.F4])163 checkString("ls {}", execmap[curses.F1])164 checkString("echo {}, {}, {}", execmap[curses.F2])165 checkString("echo '({})'", execmap[curses.F3])166 checkString("less {}", execmap[curses.F4])167 checkString("echo (,),[,],/,:,;,%,{}", execmap[curses.AltA])168 checkString("echo (,),[,],/,:,@,%,{}", execmap[curses.AltB])169152 keymap, toggleSort = parseKeymap(keymap, false, "f1:abort")170 keymap, execmap, toggleSort = parseKeymap(keymap, execmap, false, "f1:abort")171 if toggleSort {172 t.Errorf("toggleSort set")173 }174 check(actAbort, keymap[curses.F1])
47 unmodified lines
modified:src/options.go+39 added-7 removed
115 unmodified lines
116 Filter *string117 ToggleSort bool118 Expect []int119 Keymap map[int]actionType120 Execmap map[int]string121 PrintQuery bool122 ReadZero bool123 Sync bool124 History *History
32 unmodified lines
157 Filter: nil,158 ToggleSort: false,159 Expect: []int{},160 Keymap: defaultKeymap(),161 Execmap: make(map[int]string),162 PrintQuery: false,163 ReadZero: false,164 Sync: false,165 History: nil,
210 unmodified lines
376 }377 return theme378}379378func parseKeymap(keymap map[int]actionType, toggleSort bool, str string) (map[int]actionType, bool) {379 for _, pairStr := range strings.Split(str, ",") {380func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort bool, str string) (map[int]actionType, map[int]string, bool) {381 rx := regexp.MustCompile(382 ":execute(\\([^)]*\\)|\\[[^\\]]*\\]|/[^/]*/|:[^:]*:|;[^;]*;|@[^@]*@|~[^~]*~|%[^%]*%|\\?[^?]*\\?)")383 masked := rx.ReplaceAllStringFunc(str, func(src string) string {384 return ":execute(" + strings.Repeat(" ", len(src)-10) + ")"385 })386387 idx := 0388 for _, pairStr := range strings.Split(masked, ",") {389 pairStr = str[idx : idx+len(pairStr)]390 idx += len(pairStr) + 1391392 fail := func() {393 errorExit("invalid key binding: " + pairStr)394 }383 pair := strings.Split(pairStr, ":")395 pair := strings.SplitN(pairStr, ":", 2)396 if len(pair) != 2 {397 fail()398 }399 keys := parseKeyChords(pair[0], "key name required")
66 unmodified lines
466 case "toggle-sort":467 keymap[key] = actToggleSort468 toggleSort = true469 default:470 if isExecuteAction(act) {471 keymap[key] = actExecute472 execmap[key] = pair[1][8 : len(act)-1]473 } else {458 errorExit("unknown action: " + act)474 errorExit("unknown action: " + act)475 }476 }477 }461 return keymap, toggleSort478 return keymap, execmap, toggleSort479}480481func isExecuteAction(str string) bool {482 if !strings.HasPrefix(str, "execute") || len(str) < 9 {483 return false484 }485 b := str[7]486 e := str[len(str)-1]487 if b == e && strings.ContainsAny(string(b), "/:;@~%?") ||488 b == '(' && e == ')' || b == '[' && e == ']' {489 return true490 }491 return false492}493494func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {495 keys := parseKeyChords(str, "key name required")496 if len(keys) != 1 {497 errorExit("multiple keys specified")
46 unmodified lines
544 opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")545 case "--tiebreak":546 opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))547 case "--bind":548 keymap, opts.Execmap, opts.ToggleSort =518 keymap, opts.ToggleSort = parseKeymap(keymap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))549 parseKeymap(keymap, opts.Execmap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))550 case "--color":551 spec := optionalNextString(allArgs, &i)552 if len(spec) == 0 {553 opts.Theme = defaultTheme()
105 unmodified lines
659 opts.Tiebreak = parseTiebreak(value)660 } else if match, value := optString(arg, "--color="); match {661 opts.Theme = parseTheme(opts.Theme, value)662 } else if match, value := optString(arg, "--bind="); match {632 keymap, opts.ToggleSort = parseKeymap(keymap, opts.ToggleSort, value)663 keymap, opts.Execmap, opts.ToggleSort =664 parseKeymap(keymap, opts.Execmap, opts.ToggleSort, value)665 } else if match, value := optString(arg, "--history="); match {666 setHistory(value)667 } else if match, value := optString(arg, "--history-max="); match {668 setHistoryMax(atoi(value))
45 unmodified lines
modified:src/terminal.go+24 added-9 removed
2 unmodified lines
3import (4 "bytes"5 "fmt"6 "os"7 "os/exec"8 "os/signal"9 "regexp"10 "sort"11 "strings"
22 unmodified lines
34 sort bool35 toggleSort bool36 expect []int37 keymap map[int]actionType38 execmap map[int]string39 pressed int40 printQuery bool41 history *History42 count int
77 unmodified lines
120 actPageDown121 actToggleSort122 actPreviousHistory123 actNextHistory124 actExecute125)126127func defaultKeymap() map[int]actionType {128 keymap := make(map[int]actionType)
60 unmodified lines
189 sort: opts.Sort > 0,190 toggleSort: opts.ToggleSort,191 expect: opts.Expect,192 keymap: opts.Keymap,193 execmap: opts.Execmap,194 pressed: 0,195 printQuery: opts.PrintQuery,196 history: opts.History,197 merger: EmptyMerger,
392 unmodified lines
590func keyMatch(key int, event C.Event) bool {591 return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ592}593594func executeCommand(template string, current string) {595 command := strings.Replace(template, "{}", fmt.Sprintf("%q", current), -1)596 cmd := exec.Command("sh", "-c", command)597 cmd.Stdin = os.Stdin598 cmd.Stdout = os.Stdout599 cmd.Stderr = os.Stderr600 C.Endwin()601 cmd.Run()602 C.Refresh()603}604605// Loop is called to start Terminal I/O606func (t *Terminal) Loop() {607 <-t.startChan608 { // Late initialization
82 unmodified lines
691 }692 }693 selectItem := func(item *Item) bool {694 if _, found := t.selected[item.index]; !found {680 var strptr *string681 if item.origText != nil {682 strptr = item.origText683 } else {684 strptr = item.text685 }686 t.selected[item.index] = selectedItem{time.Now(), strptr}695 t.selected[item.index] = selectedItem{time.Now(), item.StringPtr()}696 return true697 }698 return false699 }
17 unmodified lines
717 }718 }719720 action := t.keymap[event.Type]721 mapkey := event.Type722 if event.Type == C.Rune {713 code := int(event.Char) + int(C.AltZ)714 if act, prs := t.keymap[code]; prs {723 mapkey = int(event.Char) + int(C.AltZ)724 if act, prs := t.keymap[mapkey]; prs {725 action = act726 }727 }728 switch action {729 case actIgnore:730 case actExecute:731 if t.cy >= 0 && t.cy < t.merger.Length() {732 item := t.merger.Get(t.cy)733 executeCommand(t.execmap[mapkey], item.AsString())734 }735 case actInvalid:736 t.mutex.Unlock()737 continue738 case actToggleSort:
225 unmodified lines
modified:test/test_go.rb+21 added
592 unmodified lines
593 ensure594 File.unlink history_file595 end596597 def test_execute598 output = '/tmp/fzf-test-execute'599 opts = %[--bind \\"alt-a:execute(echo '[{}]' >> #{output}),alt-b:execute[echo '({}), ({})' >> #{output}],C:execute:echo '({}), [{}], @{}@' >> #{output}:\\"]600 tmux.send_keys "seq 100 | #{fzf opts}", :Enter601 tmux.until { |lines| lines[-2].include? '100/100' }602 tmux.send_keys :Escape, :a, :Escape, :a603 tmux.send_keys :Up604 tmux.send_keys :Escape, :b, :Escape, :b605 tmux.send_keys :Up606 tmux.send_keys :C607 tmux.send_keys 'foobar'608 tmux.until { |lines| lines[-2].include? '0/100' }609 tmux.send_keys :Escape, :a, :Escape, :b, :Escape, :c610 tmux.send_keys :Enter611 readonce612 assert_equal ['["1"]', '["1"]', '("2"), ("2")', '("2"), ("2")', '("3"), ["3"], @"3"@'],613 File.readlines(output).map(&:chomp)614 ensure615 File.unlink output rescue nil616 end617618private619 def writelines path, lines620 File.unlink path while File.exists? path621 File.open(path, 'w') { |f| f << lines.join($/) }
208 unmodified lines