bash with vim editing mode

This post is a brief introduction on how to set-up vim editing mode in bash. It is intended to be a reference and a starting point, not a tutorial.

bashrc

vim $HOME/.bashrc

# Add the following line then:
set -o vi

Side effects

  • You will lose the ability to C-a, C-e, C-d and C-k (to move to the beginning and to the end of the current line, respectively, and to delete a character and kill-line). To "fix" that in insert mode:
# vim $HOME/.bashrc:
bind -m vi-insert "\C-a":beginning-of-line
bind -m vi-insert "\C-d":delete-char
bind -m vi-insert "\C-e":end-of-line
bind -m vi-insert "\C-k":kill-line

You might also want to fix these in normal mode (except C-k, which is already bound):

# vim $HOME/.bashrc:
# vi, vi-command, vi-move
bind -m vi-command "\C-a":beginning-of-line
bind -m vi-command "\C-d":delete-char
bind -m vi-command "\C-e":end-of-line
  • C-u, C-_, C-w, M-b will still work (why??? They are emacs keybindings!!! At least they are handy enough)
  • C-l (clear the screen) will only work in normal mode (<ESC> C-l) [1], but you can force it work on insert mode too:
# vim $HOME/.bashrc:
bind -m vi-insert "\C-l":clear-screen

It is also always a good idea to set your EDITOR and VISUAL variables:

# $HOME/.bashrc
# Set VISUAL if vim is in the system PATH.
command -v vim &>/dev/null && export VISUAL=vim
# Set EDITOR if $VISUAL is in the system PATH.
command -v "$VISUAL" &>/dev/null && export EDITOR="$VISUAL"

To edit the current command-line in your EDITOR [2], use:

  • C-x C-e if you are in emacs mode; or
  • v if you are in vi mode.

List all keybindings

Finally, one of the most useful commands for discoverability purposes:

bind -P

will list all current keybindings.

[1] https://unix.stackexchange.com/questions/104094/is-there-any-way-to-enable-ctrll-to-clear-screen-when-set-o-vi-is-set
[2] https://stackoverflow.com/questions/23230990/bashs-vim-mode-not-vi

Comments

Comments powered by Disqus