Edit your Zsh command line with vi

I have a bad habit of just kind of going with very slightly inconvenient things when developing, because I don't want to lose my focus.

One of those is when I need to edit something in the middle of a long command line. I'll just hold the arrow key until I get there.

When I used OpenBSD and ksh far more often, the solution to this was

set -o vi

stuck into my $HOME/.kshrc file, which transformed my shell into a little vi editor. Now I could hit Esc to hop out of normal mode and use all my favorite vi movement keys!

For some reason, I never tried to do this in my years using Bash when it was the default on macOS.

These days, the default is Zsh. And I still just kind of sucked it up whenever I needed to make a mid-line edit.

Guess how you add vi keys to Zsh? Well, in $HOME/.zshrc

set -o vi

There's more, though. In the years since I used to do a lot more work in OpenBSD shells, I've made quite a lot more use of the control+R and control+S history search keys. These work in the default bindings for ksh and Zsh, but once vi mode is on, both those keys get remapped elsewhere.

You can rebind those keys back again if you like:

bindkey ^R history-incremental-search-backward
bindkey ^S history-incremental-search-forward

Or, you can do what I'm going to try to get used to doing now, which is fully embrace the glorious vi-ness of my shell and use this workflow:

  1. Get out of insert mode with the trusty esc key.
  2. Type a search expression, starting with / (such as /^docker) and hit return.
  3. Move through the results with n (backward) and N (forward).

Beautiful, isn't it? I have this answer on vi Stack Overflow to thank for teaching me this.


You'll only receive email when they publish something new.

More from Mattie B
All posts