Zsh History – How to Search History with Text Already Entered at the Prompt

command historysearchzsh

In zsh, I know that I can search history with Ctrl+r. However, oftentimes I start to type a command directly at the prompt, but then realize I should be searching history. When I hit Ctrl+r, it brings up a blank history search prompt like this:

history search prompt not pre-filled

Notice how there is text at my prompt but not at the history search prompt. How do I start the history search with the text already in the prompt, so it looks like this:

history search prompt pre-filled

Best Answer

You can use zle's history-search functionality:

bindkey "^[[A" history-beginning-search-backward
bindkey "^[[B" history-beginning-search-forward

This binds Up and Down (adjust for your own escape sequences) to a history search, backwards and forwards, based upon what has already been entered at the prompt.

So, if you were to enter "vim" and hit Up, zsh will traverse backwards through your history for only those commands commencing with "vim".

You can additionally have the cursor placed at the end of the line once you have selected your desired command from zsh's history by using the history-search-end function (typically located in /usr/share/zsh/functions/Zle/) and appending -end to the end of each line, like so:

autoload -U history-search-end
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end
bindkey "^[[A" history-beginning-search-backward-end
bindkey "^[[B" history-beginning-search-forward-end
Related Question