Custom key binding support (#238)
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 15099eb · Browse files · 6 files·+306 added−54 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+306 added−54 removed
- tests:+6 added−0 removed
- other:+300 added−54 removed
Provenance
- Commit
1592bed- Tree
65b60ec- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
15099eb
6 files changed+306 added−54 removed
modified:man/man1/fzf.1+40 added
152 unmodified lines153 .BI "--toggle-sort=" "KEY"154 Key to toggle sort (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,155 or any single character)156 .TP157+.BI "--bind=" "KEYBINDS"158+Comma-separated list of custom key bindings. Each key binding expression159+follows the following format: \fBKEY:ACTION\fR160+.RS161+e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR162+.RE163+164+.RS165+.B KEY:166+ \fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR, or any single character167+.RE168+169+.RS170+.B ACTION:171+ abort172+ accept173+ backward-char174+ backward-delete-char175+ backward-kill-word176+ backward-word177+ beginning-of-line178+ clear-screen179+ delete-char180+ down181+ end-of-line182+ forward-char183+ forward-word184+ kill-line185+ kill-word186+ page-down187+ page-up188+ toggle-down189+ toggle-sort190+ toggle-up191+ unix-line-discard192+ unix-word-rubout193+ up194+ yank195+.RE196+.TP197 .B "--sync"198 Synchronous search for multi-staged filtering. If specified, fzf will launch199 ncurses finder only after the input stream is complete.200 .RS73 unmodified linesmodified:src/curses/curses.go+22 added-12 removed
59 unmodified lines60 Del61 PgUp62 PgDn63 64+ Up65+ Down66+ Left67+ Right68+ Home69+ End70+71+ SLeft72+ SRight73+74 F175 F276 F377 F4287 unmodified lines365 }366 *sz = 3367 switch _buf[2] {368 case 68:359- return Event{CtrlB, 0, nil}369+ return Event{Left, 0, nil}370 case 67:361- return Event{CtrlF, 0, nil}371+ return Event{Right, 0, nil}372 case 66:363- return Event{CtrlJ, 0, nil}373+ return Event{Down, 0, nil}374 case 65:365- return Event{CtrlK, 0, nil}375+ return Event{Up, 0, nil}376 case 90:377 return Event{BTab, 0, nil}378 case 72:369- return Event{CtrlA, 0, nil}379+ return Event{Home, 0, nil}380 case 70:371- return Event{CtrlE, 0, nil}381+ return Event{End, 0, nil}382 case 77:383 return mouseSequence(sz)384 case 80:385 return Event{F1, 0, nil}13 unmodified lines399 return Event{Invalid, 0, nil} // INS400 case 51:401 return Event{Del, 0, nil}402 case 52:393- return Event{CtrlE, 0, nil}403+ return Event{End, 0, nil}404 case 53:405 return Event{PgUp, 0, nil}406 case 54:407 return Event{PgDn, 0, nil}408 case 49:409 switch _buf[3] {410 case 126:401- return Event{CtrlA, 0, nil}411+ return Event{Home, 0, nil}412 case 59:413 if len(_buf) != 6 {414 return Event{Invalid, 0, nil}415 }1 unmodified line417 switch _buf[4] {418 case 50:419 switch _buf[5] {420 case 68:411- return Event{CtrlA, 0, nil}421+ return Event{Home, 0, nil}422 case 67:413- return Event{CtrlE, 0, nil}423+ return Event{End, 0, nil}424 }425 case 53:426 switch _buf[5] {427 case 68:418- return Event{AltB, 0, nil}428+ return Event{SLeft, 0, nil}429 case 67:420- return Event{AltF, 0, nil}430+ return Event{SRight, 0, nil}431 }432 } // _buf[4]433 } // _buf[3]434 } // _buf[2]85 unmodified linesmodified:src/options_test.go+26 added
127 unmodified lines128 keys = parseKeyChords(",,,", "")129 check(len(keys), 1)130 check(keys[0], curses.AltZ+',')131 }132+133+func TestBind(t *testing.T) {134+ check := func(action actionType, expected actionType) {135+ if action != expected {136+ t.Errorf("%d != %d", action, expected)137+ }138+ }139+ keymap := defaultKeymap()140+ 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")144+ if !toggleSort {145+ t.Errorf("toggleSort not set")146+ }147+ check(actKillLine, keymap[curses.CtrlA])148+ check(actToggleSort, keymap[curses.CtrlB])149+ check(actPageUp, keymap[curses.AltZ+'c'])150+ check(actPageDown, keymap[curses.AltZ])151+152+ keymap, toggleSort = parseKeymap(keymap, false, "f1:abort")153+ if toggleSort {154+ t.Errorf("toggleSort set")155+ }156+ check(actAbort, keymap[curses.F1])157+}modified:src/options.go+85 added-6 removed
49 unmodified lines50 -f, --filter=STR Filter mode. Do not start interactive finder.51 --print-query Print query as the first line52 --expect=KEYS Comma-separated list of keys to complete fzf53 --toggle-sort=KEY Key to toggle sort54+ --bind=KEYBINDS Custom key bindings. Refer to the man page.55 --sync Synchronous search for multi-staged filtering56 57 Environment variables58 FZF_DEFAULT_COMMAND Default command to use when input is tty53 unmodified lines112 Query string113 Select1 bool114 Exit0 bool115 Filter *string115- ToggleSort int116+ ToggleSort bool117 Expect []int118+ Keymap map[int]actionType119 PrintQuery bool120 Sync bool121 Version bool122 }27 unmodified lines150 Query: "",151 Select1: false,152 Exit0: false,153 Filter: nil,152- ToggleSort: 0,154+ ToggleSort: false,155 Expect: []int{},156+ Keymap: defaultKeymap(),157 PrintQuery: false,158 Sync: false,159 Version: false}160 }131 unmodified lines292 }293 return nil294 }295 293-func checkToggleSort(str string) int {296+func parseKeymap(keymap map[int]actionType, toggleSort bool, str string) (map[int]actionType, bool) {297+ for _, pairStr := range strings.Split(str, ",") {298+ pair := strings.Split(pairStr, ":")299+ if len(pair) != 2 {300+ errorExit("invalid key binding: " + pairStr)301+ }302+ keys := parseKeyChords(pair[0], "key name required")303+ if len(keys) != 1 {304+ errorExit("invalid key binding: " + pairStr)305+ }306+ key := keys[0]307+ act := strings.ToLower(pair[1])308+ switch strings.ToLower(pair[1]) {309+ case "beginning-of-line":310+ keymap[key] = actBeginningOfLine311+ case "abort":312+ keymap[key] = actAbort313+ case "accept":314+ keymap[key] = actAccept315+ case "backward-char":316+ keymap[key] = actBackwardChar317+ case "backward-delete-char":318+ keymap[key] = actBackwardDeleteChar319+ case "backward-word":320+ keymap[key] = actBackwardWord321+ case "clear-screen":322+ keymap[key] = actClearScreen323+ case "delete-char":324+ keymap[key] = actDeleteChar325+ case "end-of-line":326+ keymap[key] = actEndOfLine327+ case "forward-char":328+ keymap[key] = actForwardChar329+ case "forward-word":330+ keymap[key] = actForwardWord331+ case "kill-line":332+ keymap[key] = actKillLine333+ case "kill-word":334+ keymap[key] = actKillWord335+ case "unix-line-discard", "line-discard":336+ keymap[key] = actUnixLineDiscard337+ case "unix-word-rubout", "word-rubout":338+ keymap[key] = actUnixWordRubout339+ case "yank":340+ keymap[key] = actYank341+ case "backward-kill-word":342+ keymap[key] = actBackwardKillWord343+ case "toggle-down":344+ keymap[key] = actToggleDown345+ case "toggle-up":346+ keymap[key] = actToggleUp347+ case "down":348+ keymap[key] = actDown349+ case "up":350+ keymap[key] = actUp351+ case "page-up":352+ keymap[key] = actPageUp353+ case "page-down":354+ keymap[key] = actPageDown355+ case "toggle-sort":356+ keymap[key] = actToggleSort357+ toggleSort = true358+ default:359+ errorExit("unknown action: " + act)360+ }361+ }362+ return keymap, toggleSort363+}364+365+func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {366 keys := parseKeyChords(str, "key name required")367 if len(keys) != 1 {368 errorExit("multiple keys specified")369 }370+ keymap[keys[0]] = actToggleSort298- return keys[0]371+ return keymap372 }373 374 func parseOptions(opts *Options, allArgs []string) {375 for i := 0; i < len(allArgs); i++ {15 unmodified lines391 case "--expect":392 opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")393 case "--tiebreak":394 opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))395+ case "--bind":396+ opts.Keymap, opts.ToggleSort = parseKeymap(opts.Keymap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))397 case "--color":398 opts.Theme = parseTheme(nextString(allArgs, &i, "color scheme name required"))399 case "--toggle-sort":325- opts.ToggleSort = checkToggleSort(nextString(allArgs, &i, "key name required"))400+ opts.Keymap = checkToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))401+ opts.ToggleSort = true402 case "-d", "--delimiter":403 opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))404 case "-n", "--nth":405 opts.Nth = splitNth(nextString(allArgs, &i, "nth expression required"))78 unmodified lines484 opts.WithNth = splitNth(value)485 } else if match, _ := optString(arg, "-s|--sort="); match {486 opts.Sort = 1 // Don't care487 } else if match, value := optString(arg, "--toggle-sort="); match {412- opts.ToggleSort = checkToggleSort(value)488+ opts.Keymap = checkToggleSort(opts.Keymap, value)489+ opts.ToggleSort = true490 } else if match, value := optString(arg, "--expect="); match {491 opts.Expect = parseKeyChords(value, "key names required")492 } else if match, value := optString(arg, "--tiebreak="); match {493 opts.Tiebreak = parseTiebreak(value)494 } else if match, value := optString(arg, "--color="); match {495 opts.Theme = parseTheme(value)496+ } else if match, value := optString(arg, "--bind="); match {497+ opts.Keymap, opts.ToggleSort = parseKeymap(opts.Keymap, opts.ToggleSort, value)498 } else {499 errorExit("unknown option: " + arg)500 }501 }26 unmodified linesmodified:src/terminal.go+127 added-36 removed
29 unmodified lines30 yanked []rune31 input []rune32 multi bool33 sort bool34- toggleSort int34+ toggleSort bool35 expect []int36+ keymap map[int]actionType37 pressed int38 printQuery bool39 count int40 progress int39 unmodified lines80 reqClose81 reqQuit82 )83 84+type actionType int85+86+const (87+ actIgnore actionType = iota88+ actInvalid89+ actRune90+ actMouse91+ actBeginningOfLine92+ actAbort93+ actAccept94+ actBackwardChar95+ actBackwardDeleteChar96+ actBackwardWord97+ actClearScreen98+ actDeleteChar99+ actEndOfLine100+ actForwardChar101+ actForwardWord102+ actKillLine103+ actKillWord104+ actUnixLineDiscard105+ actUnixWordRubout106+ actYank107+ actBackwardKillWord108+ actToggleDown109+ actToggleUp110+ actDown111+ actUp112+ actPageUp113+ actPageDown114+ actToggleSort115+)116+117+func defaultKeymap() map[int]actionType {118+ keymap := make(map[int]actionType)119+ keymap[C.Invalid] = actInvalid120+ keymap[C.CtrlA] = actBeginningOfLine121+ keymap[C.CtrlB] = actBackwardChar122+ keymap[C.CtrlC] = actAbort123+ keymap[C.CtrlG] = actAbort124+ keymap[C.CtrlQ] = actAbort125+ keymap[C.ESC] = actAbort126+ keymap[C.CtrlD] = actDeleteChar127+ keymap[C.CtrlE] = actEndOfLine128+ keymap[C.CtrlF] = actForwardChar129+ keymap[C.CtrlH] = actBackwardDeleteChar130+ keymap[C.Tab] = actToggleDown131+ keymap[C.BTab] = actToggleUp132+ keymap[C.CtrlJ] = actDown133+ keymap[C.CtrlK] = actUp134+ keymap[C.CtrlL] = actClearScreen135+ keymap[C.CtrlM] = actAccept136+ keymap[C.CtrlN] = actDown137+ keymap[C.CtrlP] = actUp138+ keymap[C.CtrlU] = actUnixLineDiscard139+ keymap[C.CtrlW] = actUnixWordRubout140+ keymap[C.CtrlY] = actYank141+142+ keymap[C.AltB] = actBackwardWord143+ keymap[C.SLeft] = actBackwardWord144+ keymap[C.AltF] = actForwardWord145+ keymap[C.SRight] = actForwardWord146+ keymap[C.AltD] = actKillWord147+ keymap[C.AltBS] = actBackwardKillWord148+149+ keymap[C.Up] = actUp150+ keymap[C.Down] = actDown151+ keymap[C.Left] = actBackwardChar152+ keymap[C.Right] = actForwardChar153+154+ keymap[C.Home] = actBeginningOfLine155+ keymap[C.End] = actEndOfLine156+ keymap[C.Del] = actDeleteChar // FIXME Del vs. CTRL-D157+ keymap[C.PgUp] = actPageUp158+ keymap[C.PgDn] = actPageDown159+160+ keymap[C.Rune] = actRune161+ keymap[C.Mouse] = actMouse162+ return keymap163+}164+165 // NewTerminal returns new Terminal object166 func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {167 input := []rune(opts.Query)168 return &Terminal{9 unmodified lines178 multi: opts.Multi,179 sort: opts.Sort > 0,180 toggleSort: opts.ToggleSort,181 expect: opts.Expect,182+ keymap: opts.Keymap,183 pressed: 0,184 printQuery: opts.PrintQuery,185 merger: EmptyMerger,186 selected: make(map[uint32]selectedItem),144 unmodified lines331 t.move(1, 2, false)332 }333 334 output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)252- if t.toggleSort > 0 {335+ if t.toggleSort {336 if t.sort {337 output += "/S"338 } else {339 output += " "343 unmodified lines683 req(reqClose)684 break685 }686 }604- if t.toggleSort > 0 {605- if keyMatch(t.toggleSort, event) {606- t.sort = !t.sort607- t.eventBox.Set(EvtSearchNew, t.sort)608- t.mutex.Unlock()609- continue687+688+ action := t.keymap[event.Type]689+ if event.Type == C.Rune {690+ code := int(event.Char) + int(C.AltZ)691+ if act, prs := t.keymap[code]; prs {692+ action = act693 }694 }612- switch event.Type {613- case C.Invalid:695+ switch action {696+ case actInvalid:697 t.mutex.Unlock()698 continue616- case C.CtrlA:699+ case actToggleSort:700+ t.sort = !t.sort701+ t.eventBox.Set(EvtSearchNew, t.sort)702+ t.mutex.Unlock()703+ continue704+ case actBeginningOfLine:705 t.cx = 0618- case C.CtrlB:706+ case actBackwardChar:707 if t.cx > 0 {708 t.cx--709 }622- case C.CtrlC, C.CtrlG, C.CtrlQ, C.ESC:710+ case actAbort:711 req(reqQuit)624- case C.CtrlD:712+ case actDeleteChar:713 if !t.delChar() && t.cx == 0 {714 req(reqQuit)715 }628- case C.CtrlE:716+ case actEndOfLine:717 t.cx = len(t.input)630- case C.CtrlF:718+ case actForwardChar:719 if t.cx < len(t.input) {720 t.cx++721 }634- case C.CtrlH:722+ case actBackwardDeleteChar:723 if t.cx > 0 {724 t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)725 t.cx--726 }639- case C.Tab:727+ case actToggleDown:728 if t.multi && t.merger.Length() > 0 {729 toggle()730 t.vmove(-1)731 req(reqList)732 }645- case C.BTab:733+ case actToggleUp:734 if t.multi && t.merger.Length() > 0 {735 toggle()736 t.vmove(1)737 req(reqList)738 }651- case C.CtrlJ, C.CtrlN:739+ case actDown:740 t.vmove(-1)741 req(reqList)654- case C.CtrlK, C.CtrlP:742+ case actUp:743 t.vmove(1)744 req(reqList)657- case C.CtrlM:745+ case actAccept:746 req(reqClose)659- case C.CtrlL:747+ case actClearScreen:748 req(reqRedraw)661- case C.CtrlU:749+ case actUnixLineDiscard:750 if t.cx > 0 {751 t.yanked = copySlice(t.input[:t.cx])752 t.input = t.input[t.cx:]753 t.cx = 0754 }667- case C.CtrlW:755+ case actUnixWordRubout:756 if t.cx > 0 {757 t.rubout("\\s\\S")758 }671- case C.AltBS:759+ case actBackwardKillWord:760 if t.cx > 0 {761 t.rubout("[^[:alnum:]][[:alnum:]]")762 }675- case C.CtrlY:763+ case actYank:764 suffix := copySlice(t.input[t.cx:])765 t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)766 t.cx += len(t.yanked)679- case C.Del:680- t.delChar()681- case C.PgUp:767+ case actPageUp:768 t.vmove(t.maxItems() - 1)769 req(reqList)684- case C.PgDn:770+ case actPageDown:771 t.vmove(-(t.maxItems() - 1))772 req(reqList)687- case C.AltB:773+ case actBackwardWord:774 t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1689- case C.AltF:775+ case actForwardWord:776 t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1691- case C.AltD:777+ case actKillWord:778 ncx := t.cx +779 findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1780 if ncx > t.cx {781 t.yanked = copySlice(t.input[t.cx:ncx])782 t.input = append(t.input[:t.cx], t.input[ncx:]...)783 }698- case C.Rune:784+ case actKillLine:785+ if t.cx < len(t.input) {786+ t.yanked = copySlice(t.input[t.cx:])787+ t.input = t.input[:t.cx]788+ }789+ case actRune:790 prefix := copySlice(t.input[:t.cx])791 t.input = append(append(prefix, event.Char), t.input[t.cx:]...)792 t.cx++702- case C.Mouse:793+ case actMouse:794 me := event.MouseEvent795 mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y796 if !t.reverse {797 my = C.MaxY() - my - 188 unmodified linesmodified:test/test_go.rb+6 added
514 unmodified lines515 def test_smart_case_for_each_term516 assert_equal 1, `echo Foo bar | #{FZF} -x -f "foo Fbar" | wc -l`.to_i517 end518 519+ def test_bind520+ tmux.send_keys "seq 1 1000 | #{fzf '-m --bind=ctrl-j:accept,z:up,x:toggle-up'}", :Enter521+ tmux.until { |lines| lines[-2].end_with? '/1000' }522+ tmux.send_keys 'zzz', 'xx', 'C-j'523+ assert_equal %w[4 5], readonce.split($/)524+ end525 private526 def writelines path, lines527 File.unlink path while File.exists? path528 File.open(path, 'w') { |f| f << lines.join($/) }208 unmodified lines