evil-define-key
Evil provides the macro evil-define-key for adding state bindings to ordinary keymaps. It is quite powerful, and is the preferred method for fine-tuning bindings to activate in specific circumstances.
Emacs Lisp Autofunction: (evil-define-key STATE KEYMAP KEY DEF [BINDINGS...])
Create a `STATE' binding from `KEY' to `DEF' for `KEYMAP'. `STATE' is one of normal, insert, visual, replace, operator, motion, emacs, or a list of one or more of these. Omitting a state by using nil corresponds to a standard Emacs binding using define-key. The remaining arguments are like those of define-key. For example:
(evil-define-key 'normal foo-map "a" 'bar)This creates a binding from a to bar in normal state, which is active whenever foo-map is active. Using nil for the state, the following lead to identical bindings:
(evil-define-key nil foo-map "a" 'bar)
(define-key foo-map "a" 'bar)It is possible to specify multiple states and/or bindings at once:
(evil-define-key '(normal visual) foo-map
"a" 'bar
"b" 'foo)If foo-map has not been initialized yet, this macro adds an entry to after-load-functions, delaying execution as necessary.
`KEYMAP' may also be a quoted symbol. If the symbol is global, the global evil keymap corresponding to the state(s) is used, meaning the following lead to identical bindings:
(evil-define-key 'normal 'global "a" 'bar)
(evil-global-set-key 'normal "a" 'bar)The symbol local may also be used, which corresponds to using evil-local-set-key. If a quoted symbol is used that is not global or local, it is assumed to be the name of a minor mode, in which case evil-define-minor-mode-key is used.
There follows a brief overview of the main functions of this macro.
Define a binding in a given state
emacs-lisp(evil-define-key 'state 'global (kbd "key") 'target)Define a binding in a given state in the current buffer
emacs-lisp(evil-define-key 'state 'local (kbd "key") 'target)Define a binding in a given state under the `foo-mode' major mode.
emacs-lisp(evil-define-key 'state foo-mode-map (kbd "key") 'target)Note that
foo-mode-mapis unquoted, and that this form is safe beforefoo-mode-mapis loaded.Define a binding in a given state under the `bar-mode' minor mode.
emacs-lisp(evil-define-key 'state 'bar-mode (kbd "key") 'target)Note that
bar-modeis quoted, and that this form is safe beforebar-modeis loaded.
The macro evil-define-key can be used to augment existing modes with state bindings, as well as creating packages with custom bindings. For example, the following will create a minor mode foo-mode with normal state bindings for the keys w and e:
(define-minor-mode foo-mode
"Foo mode."
:keymap (make-sparse-keymap))
(evil-define-key 'normal 'foo-mode "w" 'bar)
(evil-define-key 'normal 'foo-mode "e" 'baz)This minor mode can then be enabled in any buffers where the custom bindings are desired:
(add-hook 'text-mode-hook 'foo-mode) ; enable alongside text-mode