6

With evil-mode, I found myself pressing escape very often, but it's a bit far to reach. Also, it seems semantic wise, keyboard-quit is similar to evil-force-normal-state, so I would like to use C-g for both of them with the following conditional logic that Only when cursor is a buffer with evil-mode's insert state, then C-g should execute evil-force-normal-state, other it should execute its normal binding of keyboard-quit

I guess that there might be a sub-key-map for evil with insert state?

If you have ready example, I'd appreciate your sharing.

In the meantime, I'll check the possibility of customizing the key-binding with evil's input state. I'm studying this link now:

I tried the following, but it didn't work:

(evil-define-key 'insert evil-insert-state-map (kbd "C-g") 'evil-normal-state)

and

(evil-define-key 'insert evil-insert-state-map (kbd "C-g") 'evil-force-normal-state)

C-g still executes keyboard-quit

I found that I can use key-chord to execute evil-force-normal-state:

(key-chord-define evil-normal-state-map ",," 'evil-force-normal-state)
(key-chord-define evil-visual-state-map ",," 'evil-change-to-previous-state)
(key-chord-define evil-insert-state-map ",," 'evil-normal-state)
(key-chord-define evil-replace-state-map ",," 'evil-normal-state)

Thanks,

Yu Shen
  • 451
  • 4
  • 15

1 Answers1

6

If you'd like a command that detects your evil state and behaves contextually, you can use an if:

(defun quit-it ()
  "If in evil insert state, force normal state, else run
`keyboard-quit'."
  (interactive)
  (if (and evil-mode (eq evil-state 'insert))
      (evil-force-normal-state)
    (keyboard-quit)))

Of course, you may want to be able to do that when you get into some of the other evil keymaps, and there's no particular harm that I can see to forcing normal state elsewhere, so you could probably say:

(defun evil-keyboard-quit ()
  "Keyboard quit and force normal state."
  (interactive)
  (and evil-mode (evil-force-normal-state))
  (keyboard-quit))

Now go ahead and bind it in the relevant maps:

(define-key evil-normal-state-map   (kbd "C-g") #'evil-keyboard-quit) 
(define-key evil-motion-state-map   (kbd "C-g") #'evil-keyboard-quit) 
(define-key evil-insert-state-map   (kbd "C-g") #'evil-keyboard-quit) 
(define-key evil-window-map         (kbd "C-g") #'evil-keyboard-quit) 
(define-key evil-operator-state-map (kbd "C-g") #'evil-keyboard-quit) 
Dan
  • 32,584
  • 6
  • 98
  • 168
  • Thanks for showing the example. I'll give it a try to confirm. – Yu Shen Jul 13 '15 at 04:06
  • evil-window-state-map could not be found with my emacs "24.5.1". It didn't bother me so far. Anyway, your suggestion works beautifully. C-g seems a good binding. – Yu Shen Jul 13 '15 at 04:22
  • 1
    @YuShen: sorry, my mistake: it should have been `evil-window-map`. The answer is now corrected. – Dan Jul 13 '15 at 09:47