Add support for search history
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Add `--history` option (e.g. fzf --history ~/.fzf.history) - Add `--history-max` option for limiting the size of the file (default 1000) - Add `previous-history` and `next-history` actions for `--bind` - CTRL-P and CTRL-N are automatically remapped to these actions when `--history` is used Closes #249, #251
authored by Junegunn Choi · committed by Junegunn Choi · parent 2e84b1d · Browse files · 6 files·+163 added−11 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+163 added−11 removed
- tests:+46 added−0 removed
- other:+117 added−11 removed
Provenance
- Commit
3b52811- Tree
5539de2- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
2e84b1d
6 files changed+163 added−11 removed
modified:shell/completion.bash+9 added-2 removed
43 unmodified lines44 -f --filter45 --print-query46 --expect47 --toggle-sort48- --sync"48+ --sync49+ --null50+ --history51+ --history-max"52 53 case "${prev}" in54 --tiebreak)55 COMPREPLY=( $(compgen -W "length begin end index" -- ${cur}) )2 unmodified lines58 --color)59 COMPREPLY=( $(compgen -W "dark light 16 bw" -- ${cur}) )60 return 061 ;;62+ --history)63+ COMPREPLY=()64+ return 065+ ;;66 esac67 68 if [[ ${cur} =~ ^-|\+ ]]; then69 COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )143 unmodified lines213 EOF214 }215 216 # fzf options210-complete -F _fzf_opts_completion fzf217+complete -o default -F _fzf_opts_completion fzf218 219 d_cmds="cd pushd rmdir"220 f_cmds="221 awk cat diff diff350 unmodified linesmodified:src/constants.go+3 added
30 unmodified lines31 queryCacheMax int = chunkSize / 532 33 // Not to cache mergers with large lists34 mergerCacheMax int = 10000035+36+ // History37+ defaultHistoryMax int = 100038 )39 40 // fzf events41 const (7 unmodified linesmodified:src/options.go+77 added-4 removed
40 unmodified lines41 --inline-info Display finder info inline with the query42 --prompt=STR Input prompt (default: '> ')43 --toggle-sort=KEY Key to toggle sort44 --bind=KEYBINDS Custom key bindings. Refer to the man page.45+ --history=FILE History file46+ --history-max=N Maximum number of history entries (default: 1000)47 48 Scripting49 -q, --query=STR Start the finder with the given query50 -1, --select-1 Automatically select the only match68 unmodified lines119 Keymap map[int]actionType120 PrintQuery bool121 ReadZero bool122 Sync bool123+ History *History124 Version bool125 }126 127 func defaultTheme() *curses.ColorTheme {31 unmodified lines159 Keymap: defaultKeymap(),160 PrintQuery: false,161 ReadZero: false,162 Sync: false,163+ History: nil,164 Version: false}165 }166 167 func help(ok int) {31 unmodified lines199 }200 return ""201 }202 203+func atoi(str string) int {204+ num, err := strconv.Atoi(str)205+ if err != nil {206+ errorExit("not a valid integer: " + str)207+ }208+ return num209+}210+211+func nextInt(args []string, i *int, message string) int {212+ if len(args) > *i+1 {213+ *i++214+ } else {215+ errorExit(message)216+ }217+ return atoi(args[*i])218+}219+220 func optionalNumeric(args []string, i *int) int {221 if len(args) > *i+1 {222 if strings.IndexAny(args[*i+1], "0123456789") == 0 {223 *i++220 unmodified lines444 case "page-up":445 keymap[key] = actPageUp446 case "page-down":447 keymap[key] = actPageDown448+ case "previous-history":449+ keymap[key] = actPreviousHistory450+ case "next-history":451+ keymap[key] = actNextHistory452 case "toggle-sort":453 keymap[key] = actToggleSort454 toggleSort = true455 default:12 unmodified lines468 return keymap469 }470 471 func parseOptions(opts *Options, allArgs []string) {472+ keymap := make(map[int]actionType)473+ var historyMax int474+ if opts.History == nil {475+ historyMax = defaultHistoryMax476+ } else {477+ historyMax = opts.History.maxSize478+ }479+ setHistory := func(path string) {480+ h, e := NewHistory(path, historyMax)481+ if e != nil {482+ errorExit(e.Error())483+ }484+ opts.History = h485+ }486+ setHistoryMax := func(max int) {487+ historyMax = max488+ if historyMax < 1 {489+ errorExit("history max must be a positive integer")490+ }491+ if opts.History != nil {492+ opts.History.maxSize = historyMax493+ }494+ }495 for i := 0; i < len(allArgs); i++ {496 arg := allArgs[i]497 switch arg {498 case "-h", "--help":13 unmodified lines512 opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")513 case "--tiebreak":514 opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))515 case "--bind":468- opts.Keymap, opts.ToggleSort = parseKeymap(opts.Keymap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))516+ keymap, opts.ToggleSort = parseKeymap(keymap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))517 case "--color":518 spec := optionalNextString(allArgs, &i)519 if len(spec) == 0 {520 opts.Theme = defaultTheme()521 } else {522 opts.Theme = parseTheme(opts.Theme, spec)523 }524 case "--toggle-sort":477- opts.Keymap = checkToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))525+ keymap = checkToggleSort(keymap, nextString(allArgs, &i, "key name required"))526 opts.ToggleSort = true527 case "-d", "--delimiter":528 opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))529 case "-n", "--nth":63 unmodified lines593 case "--no-sync":594 opts.Sync = false595 case "--async":596 opts.Sync = false597+ case "--no-history":598+ opts.History = nil599+ case "--history":600+ setHistory(nextString(allArgs, &i, "history file path required"))601+ case "--history-max":602+ setHistoryMax(nextInt(allArgs, &i, "history max size required"))603 case "--version":604 opts.Version = true605 default:606 if match, value := optString(arg, "-q|--query="); match {10 unmodified lines617 opts.WithNth = splitNth(value)618 } else if match, _ := optString(arg, "-s|--sort="); match {619 opts.Sort = 1 // Don't care620 } else if match, value := optString(arg, "--toggle-sort="); match {567- opts.Keymap = checkToggleSort(opts.Keymap, value)621+ keymap = checkToggleSort(keymap, value)622 opts.ToggleSort = true623 } else if match, value := optString(arg, "--expect="); match {624 opts.Expect = parseKeyChords(value, "key names required")625 } else if match, value := optString(arg, "--tiebreak="); match {626 opts.Tiebreak = parseTiebreak(value)627 } else if match, value := optString(arg, "--color="); match {628 opts.Theme = parseTheme(opts.Theme, value)629 } else if match, value := optString(arg, "--bind="); match {576- opts.Keymap, opts.ToggleSort = parseKeymap(opts.Keymap, opts.ToggleSort, value)630+ keymap, opts.ToggleSort = parseKeymap(keymap, opts.ToggleSort, value)631+ } else if match, value := optString(arg, "--history="); match {632+ setHistory(value)633+ } else if match, value := optString(arg, "--history-max="); match {634+ setHistoryMax(atoi(value))635 } else {636 errorExit("unknown option: " + arg)637 }638 }639 }640 641+ // Change default actions for CTRL-N / CTRL-P when --history is used642+ if opts.History != nil {643+ if _, prs := keymap[curses.CtrlP]; !prs {644+ keymap[curses.CtrlP] = actPreviousHistory645+ }646+ if _, prs := keymap[curses.CtrlN]; !prs {647+ keymap[curses.CtrlN] = actNextHistory648+ }649+ }650+651+ // Override default key bindings652+ for key, act := range keymap {653+ opts.Keymap[key] = act654+ }655+656 // If we're not using extended search mode, --nth option becomes irrelevant657 // if it contains the whole range658 if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {659 for _, r := range opts.Nth {20 unmodified linesmodified:src/terminal.go+25 added-2 removed
34 unmodified lines35 expect []int36 keymap map[int]actionType37 pressed int38 printQuery bool39+ history *History40 count int41 progress int42 reading bool43 merger *Merger72 unmodified lines116 actUp117 actPageUp118 actPageDown119 actToggleSort120+ actPreviousHistory121+ actNextHistory122 )123 124 func defaultKeymap() map[int]actionType {125 keymap := make(map[int]actionType)62 unmodified lines188 expect: opts.Expect,189 keymap: opts.Keymap,190 pressed: 0,191 printQuery: opts.PrintQuery,192+ history: opts.History,193 merger: EmptyMerger,194 selected: make(map[uint32]selectedItem),195 reqBox: util.NewEventBox(),196 eventBox: eventBox,416 unmodified lines613 }614 }()615 }616 617+ exit := func(code int) {618+ if code == 0 && t.history != nil {619+ t.history.append(string(t.input))620+ }621+ os.Exit(code)622+ }623+624 go func() {625 for {626 t.reqBox.Wait(func(events *util.Events) {627 defer events.Clear()18 unmodified lines646 t.printAll()647 case reqClose:648 C.Close()649 t.output()639- os.Exit(0)650+ exit(0)651 case reqQuit:652 C.Close()642- os.Exit(1)653+ exit(1)654 }655 }656 t.placeCursor()657 t.mutex.Unlock()182 unmodified lines840 case actRune:841 prefix := copySlice(t.input[:t.cx])842 t.input = append(append(prefix, event.Char), t.input[t.cx:]...)843 t.cx++844+ case actPreviousHistory:845+ if t.history != nil {846+ t.history.override(string(t.input))847+ t.input = []rune(t.history.previous())848+ t.cx = len(t.input)849+ }850+ case actNextHistory:851+ if t.history != nil {852+ t.history.override(string(t.input))853+ t.input = []rune(t.history.next())854+ t.cx = len(t.input)855+ }856 case actMouse:857 me := event.MouseEvent858 mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y859 if !t.reverse {89 unmodified linesmodified:test/test_go.rb+46 added
564 unmodified lines565 tmux.send_keys :Enter566 assert_equal %w[2 1 10 20 30 40 50 60 70 80 90 100], readonce.split($/)567 end568 569+ def test_history570+ history_file = '/tmp/fzf-test-history'571+572+ # History with limited number of entries573+ File.unlink history_file rescue nil574+ opts = "--history=#{history_file} --history-max=4"575+ input = %w[00 11 22 33 44].map { |e| e + $/ }576+ input.each do |keys|577+ tmux.send_keys "seq 100 | #{fzf opts}", :Enter578+ tmux.until { |lines| lines[-2].include? '100/100' }579+ tmux.send_keys keys580+ tmux.until { |lines| lines[-2].include? '1/100' }581+ tmux.send_keys :Enter582+ end583+ assert_equal input[1..-1], File.readlines(history_file)584+585+ # Update history entries (not changed on disk)586+ tmux.send_keys "seq 100 | #{fzf opts}", :Enter587+ tmux.until { |lines| lines[-2].include? '100/100' }588+ tmux.send_keys 'C-p'589+ tmux.until { |lines| lines[-1].end_with? '> 44' }590+ tmux.send_keys 'C-p'591+ tmux.until { |lines| lines[-1].end_with? '> 33' }592+ tmux.send_keys :BSpace593+ tmux.until { |lines| lines[-1].end_with? '> 3' }594+ tmux.send_keys 1595+ tmux.until { |lines| lines[-1].end_with? '> 31' }596+ tmux.send_keys 'C-p'597+ tmux.until { |lines| lines[-1].end_with? '> 22' }598+ tmux.send_keys 'C-n'599+ tmux.until { |lines| lines[-1].end_with? '> 31' }600+ tmux.send_keys 0601+ tmux.until { |lines| lines[-1].end_with? '> 310' }602+ tmux.send_keys :Enter603+ assert_equal %w[22 33 44 310].map { |e| e + $/ }, File.readlines(history_file)604+605+ # Respect --bind option606+ tmux.send_keys "seq 100 | #{fzf opts + ' --bind ctrl-p:next-history,ctrl-n:previous-history'}", :Enter607+ tmux.until { |lines| lines[-2].include? '100/100' }608+ tmux.send_keys 'C-n', 'C-n', 'C-n', 'C-n', 'C-p'609+ tmux.until { |lines| lines[-1].end_with?('33') }610+ tmux.send_keys :Enter611+ ensure612+ File.unlink history_file613+ end614+615 private616 def writelines path, lines617 File.unlink path while File.exists? path618 File.open(path, 'w') { |f| f << lines.join($/) }208 unmodified linesmodified:fzf+3 added-3 removed
204 unmodified lines205 argv.shift206 @expect = true207 when /^--expect=(.*)$/208 @expect = true209- when '--toggle-sort', '--tiebreak', '--color', '--bind'209+ when '--toggle-sort', '--tiebreak', '--color', '--bind', '--history', '--history-max'210 argv.shift211 when '--tac', '--no-tac', '--sync', '--no-sync', '--hscroll', '--no-hscroll',212- '--inline-info', '--no-inline-info', /^--bind=(.*)$/,213- /^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/212+ '--inline-info', '--no-inline-info', '--null', /^--bind=(.*)$/,213+ /^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/, /^--history(-max)?=(.*)$/214 # XXX215 else216 usage 1, "illegal option: #{o}"217 end1131 unmodified lines