ZSH Command History – Search with Up and Down Keys

command historyline-editorzsh

Currently, I have the following in my .zshrc:

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

However, this only seems to match the content of my current input before a space character occurs. For example, sudo ls / will match every line in my history that begins with sudo, while I would like it to only match lines that match my entire input. (i.e. sudo ls /etc would match, but not sudo cat /var/log/messages)

What do I need to change in order to gain the desired behavior?

Here is my entire .zshrc in case it is relevant: https://gist.github.com/919566

Best Answer

This is the documented behavior:

down-line-or-search
Move down a line in the buffer, or if already at the bottom line, search forward in the history for a line beginning with the first word in the buffer.

There doesn't seem to be an existing widget that does exactly what you want, so you'll have to make your own. Here's how to define a widget that behaves like up-line-or-search, but using the beginning of the line (up to the cursor) rather than the first word as search string. Not really tested, especially not on multi-line input.

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

An alternate approach is to use history-beginning-search-backward, but only call it if the cursor is on the first line. Untested.

up-line-or-history-beginning-search () {
  if [[ -n $PREBUFFER ]]; then
    zle up-line-or-history
  else
    zle history-beginning-search-backward
  fi
}
zle -N up-line-or-history-beginning-search
Related Question