laudai
laudai

Reputation: 45

How to make zsh keybind between emacs mode and vi mode?

I want to bind a key to toggle emacs mode and vi mode,which I use oh-my-zsh plugins(vi-mode).

I tried Is there a way to switch Bash or zsh from Emacs mode to vi mode with a keystroke?

I also try to bindkey like
bindkey '^[e' 'set -o emacs'
bindkey '^[v' 'set -o vi'

But it's not work for me.

Does any way to toggle vi/emacs or keybind to set keymap?
Thanks a lot !

Upvotes: 2

Views: 2770

Answers (2)

MacMartin
MacMartin

Reputation: 2866

I finally "found out" how to toggle vi and emacs mode with a singel key, e.g. [alt]+[i] in zsh

# in the .zshrc
# toggle vi and emacs mode
vi-mode() { set -o vi; }
emacs-mode() { set -o emacs; }
zle -N vi-mode
zle -N emacs-mode
bindkey '\ei' vi-mode              # switch to vi "insert" mode
bindkey -M viins 'jk' vi-cmd-mode  # (optionally) switch to vi "cmd" mode
bindkey -M viins '\ei' emacs-mode  # switch to emacs mode

now you can toggle from emacs-mode to vi-mode and from vi-mode (both insert or normal mode) to emacs-mode

Upvotes: 0

okapi
okapi

Reputation: 1460

bindkey is used for binding keys to ZLE widgets not any random command. So what you have guessed at is not going to work. You could write a custom ZLE widget to switch keymaps:

select-emacs() { set -o emacs }
zle -N select-emacs
bindkey '^[e' select-emacs

In practical terms, I wouldn't recommend this. If you want a hybrid approach, it is better to select emacs mode but bind a key to vi-cmd-mode. In fact Ctrl-X,Ctrl-V is bound to this by default. You might even bind the escape key to vi-cmd-mode - where emacs key sequences involve an initial escape press, that can mostly be replaced by Alt. If you're used to typing it with the actual escape key, you may be able to replace it by a custom widget in vi command mode.

Upvotes: 3

Related Questions