Fizk
Fizk

Reputation: 1114

Which keybind for smart-searching in history with ZSH?

When using the up and down arrow in my terminal (iTerm 2 on Mac OS Catalina), I can browse through my last commands using the up and down arrows.

I use ZSH (Oh-my-zsh to be precise) and if I type e.g. vim then press up, it will browse my history for any commands issued starting with vim.

I think it's annoying to have to move my hand to the arrow keys, so i wanted to bind ctrl-j and ctrl-k for browsing up and down.

I looked at bindkey and bound ^j to down-history and ^k to up-history. This allows me to browse my history, but not with the "smart" functionality (i'm not sure of the right terminology here) - It simply goes up and down in my history, without regards to my input.

I've looked through the standard widgets on the Zsh Line Editor manual, but I cannot find the right command for this.

Which command should I bind ^j and ^k to to get my desired result?

Upvotes: 3

Views: 3567

Answers (1)

Fizk
Fizk

Reputation: 1114

After some further digging, i ended up on the The Z-Shell Line Editor page at the section called "Prefix searching".

It revealed that the widget I was after, is called history-beginning-search-backward. When using that widget, it works almost as I wanted it to, but not jumping to the end of the line.

A quick search lead me to another StackOverflow Question, that states that if you want to jump to the end of the line (as with the up arrow), it should be done as follows;

I had the same question and managed to find the solution with some experimentation.

I added the following to my .inputrc

"\eOA": history-search-backward # Up

"\eOB": history-search-forward  # Down

"\C-P": "\eOA\C-E"              # Ctrl-P

"\C-N": "\eOB\C-E"              # Ctrl-N

This binds two hotkeys to Ctrl-P and Ctrl-N. One for history search, and the other Ctrl-E for end-of-line.

Upvotes: 5

Related Questions