KISS

Keep It Simple Stupid

Zsh: search with Up/Down keys

| comments

Update on 2015-06-07: I’ve discovered from this stackexchange answer that zsh now provides this function out-of-box, so what you really need, instead of the config below, is:

1
2
3
4
bindkey '^[[A' history-beginning-search-backward
bindkey '^[OA' history-beginning-search-backward
bindkey '^[[B' history-beginning-search-forward
bindkey '^[OB' history-beginning-search-forward

Update on 2015-03-07: see an update about keys at the bottom.

There is an extremely convenient feature in command-line shells (i.e., bash) when you start typing a command, say git s, and then press Up and Down keys to search back/forward commands starting with that text. Here the commands may be git status or git show, whatever there is in your history.

In bash, the following ~/.inputrc lines work:

1
2
3
4
5
# these allow you to start typing a command and
# use the up/down arrow to auto complete from
# commands in your history
"\e[B": history-search-forward
"\e[A": history-search-backward

In zsh, however, that doesn’t work anymore, as it doesn’t use the readline library. I noticed that the feature was on by default in zsh (at least, having oh-my-zsh installed), but it worked rather strangely. It seemed to do the search matching the first word of the command only (which is exactly how it’s supposed to act, according to man zshall). To have the same behavior as in bash, add these lines to your ~/.zshrc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
up-line-or-search-prefix () {
  local CURSOR_before_search=$CURSOR
  zle up-line-or-search "$LBUFFER"
  CURSOR=$CURSOR_before_search
}
zle -N up-line-or-search-prefix

down-line-or-search-prefix () {
  local CURSOR_before_search=$CURSOR
  zle down-line-or-search "$LBUFFER"
  CURSOR=$CURSOR_before_search
}
zle -N down-line-or-search-prefix

bindkey '^[[A' up-line-or-search-prefix
bindkey '^[[B' down-line-or-search-prefix

Update: to find out the actual characters sequences that Up and Down keys are sending, you can run this command: cat - and press those keys. I needed that, because on another Mac they produced ^[OA and ^[OB characters instead. Keep that in mind if the above snippet doesn’t work for you out of the box!

Source: stackexchange

Comments