I have mapped alt-k and alt-j for browsing history, but I would like to switch vicmd automatically whenever I call up a history entry, because most of the time I need to move the cursor to a certain position and make some changes.

Here is my current settings in .zshrc, what should I do to reach the goal mentioned above?

    bindkey '^[k' up-line-or-history
    bindkey '^[j' down-line-or-history

1 Answer 1


What you want can be accomplished by just pressing Esc after or Alt+j or Alt+k but if you want to save that 1 keystroke, then adding the following to your .zshrc can help you.

vi-cmd-up-line-history() { 
  zle vi-cmd-mode
  zle up-line-or-history 
zle -N vi-cmd-up-line-history 
bindkey -M vicmd '^[k' vi-cmd-up-line-history
bindkey -M viins '^[k' vi-cmd-up-line-history

vi-cmd-down-line-history() { 
  zle vi-cmd-mode
  zle down-line-or-history 
zle -N vi-cmd-down-line-history
bindkey -M vicmd '^[j' vi-cmd-down-line-history
bindkey -M viins '^[j' vi-cmd-down-line-history

What it does is bind new widgets called vi-cmd-down-line-history and vi-cmd-up-line-history to Alt+j and Alt+k. These widgets change the mode to cmd by calling the widget vi-cmd-mode and then fire the down-line-or-history and up-line-or-history respectively.

  • This doesn't work at all, when alt+k were pressed the first time, it turned up the most recent command, but then nothing happened in response to alt+k again.
    – qed
    Feb 7, 2013 at 18:52
  • How about adding -M vicmd like bindkey -M vicmd '^[k' vi-cmd-up-line-history I added that as an edit, so try again. ;)
    – lmcanavals
    Feb 7, 2013 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.