Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


share|improve this question

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.

share|improve this answer
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 '13 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. ;) – Martín Canaval Feb 7 '13 at 21:13

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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