Last Updated: October 26, 2017
·
26.76K
· w0ng

zsh: Better history searching with arrow keys

Desired behaviour:

Search through history for previous commands matching everything up to current cursor position. Move the cursor to the end of line after each match.

Example:

[] indicates the current cursor position. With the partial command:

$ rbenv exec[]

We want up arrow keypresses to result in:

$ rbenv exec rake generate[]
$ rbenv exec rake preview[]
....

and down arrow keypresses to result in:

....
$ rbenv exec rake preview[]
$ rbenv exec rake generate[]
$ rbenv exec[]

Solution:

Add to ~/.zshrc:

autoload -U up-line-or-beginning-search
autoload -U down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey "^[[A" up-line-or-beginning-search # Up
bindkey "^[[B" down-line-or-beginning-search # Down

More info:

  • man zshzle. Search for "History Control".
  • man zshcontrib. Search for "up-line-or-beginning-search".

2 Responses
Add your response

Thanks for this. I was struggling to find the same solution myself. However, the "^[[A" and "^[[B" did not register as Up and Down in my terminal for some reason. [1] has an interesting lookup pattern that sets $key_info["Up"} = "$terminfo[kcuu1]"</code>--similarly for other special keys--and with that the Up and Down keys worked.

[1] https://raw.githubusercontent.com/sorin-ionescu/prezto/28a20b48e652a01216a6c3dd76e6324d76c12def/modules/editor/init.zsh

over 1 year ago ·

Thanks a lot for this tip.

I wanted to set this behavior to match my tcsh configuration:

bindkey -k up history-search-backward
bindkey -k down history-search-forward
over 1 year ago ·