83

I recently switched to zsh (finally) and am loving it! So far one thing that I am missing is Ctrl+R to do incremental history search.
I have the history set up properly

HISTSIZE=10000
SAVEHIST=10000
HISTFILE=~/.zsh_history

and I used vi key bindings

bindkey -v

But Ctrl+R does not work. It removes the line above the current line, which is not the behavior it should have in vim either.

Any suggestions?

jobin
  • 886
Ali
  • 6,943

3 Answers3

134

If I recall correctly, you need to explicitly set it, even with bindkey -v. Use something like this:

bindkey -v
bindkey '^R' history-incremental-search-backward
Sébastien
  • 967
  • 1
  • 7
  • 11
Chris Down
  • 125,559
  • 25
  • 270
  • 266
  • 5
    perhaps history-incremental-pattern-search-backward is an alternative action to use in that context. – maxschlepzig Jan 27 '12 at 14:18
  • 3
    @maxschlepzig sorry what is the difference between the two? – Ali Jan 27 '12 at 15:34
  • 4
    @Ali, with the -pattern- versions you can use search-patterns (which style, i.e. globbing or regex (?) depends on other parts of your zsh-configuration) - like e.g. you can use the search-pattern fo*bar with grep to match 'fobar', 'foobar', 'fooobar' etc. – maxschlepzig Jan 27 '12 at 21:03
  • 6
    I was getting an error. Wrapping ^R in double quotes did it. bindkey "^R" history-incremental-pattern-search-backward – Ramon Tayag Sep 08 '13 at 06:26
  • 4
    bindkey -v must precede history-incremental-search-backward – Deniz Feb 21 '19 at 07:22
  • Is there a fuzzy search alternative? – creanion May 08 '22 at 09:37
  • In general, and for the OP, It is helpful to set the forward incremental search by adding a second line to ~/.zshrc: bindkey '^s' history-incremental-search-forward; press Ctrl+s a couple times after starting your Ctrl+r backward search, and you'll start going forwards again through the results, preventing you from having to start over if you go past the desired command – Life5ign Sep 13 '23 at 19:08
10

OMZ framework has zsh-history-substring-search plugin pre-packaged. Just enable & use; for example:

plugins=(git zsh-history-substring-search)
Stephen Kitt
  • 434,908
Mohnish
  • 431
9

bindkey -e also works and makes zsh behave more like bash. It restores other things that you may have been using like ctrl-A (beginning of line), ctrl-K (delete everything to the right of the cursor).

KFunk
  • 191
  • 1
    This is a great answer, thanks. It solves a couple of problems at once, in a clean way. – hraban Mar 30 '21 at 10:28
  • 3
    Just adding a comment to explain that this sets so-called "emacs mode" which provides a lot of these settings even to those like me who aren't into emacs. – Steven Lu Nov 26 '21 at 22:34