Emacs: Change Minor Mode Keybinding

By Xah Lee. Date: . Last updated: .

To change Minor Mode keys, you need to change the mode's keymap.

General Steps

  1. Alt+x describe-function, then type the mode activation command name, then click on the link to open its elisp source code file.
  2. in the mode's source code, search for “-map” to find its keymap name. Let's say it's xx-map.
  3. in the mode's source code, go all the way to bottom to find (provide 'xx) if it exists. The 'xx would be the feature symbol for the mode.
  4. In your emacs init file, start with (require 'xx) (if the mode has a feature symbol), then (define-key xx-map (kbd "keyCode") 'commandName)

Not all mode defines a keymap in its source file. Some inherit from other modes, some use keymaps from other elisp file that are not modes, some don't have keymaps.

When you redefine a key in a mode's keymap, be sure to make key for the command your new key shadowed, if you still want a key for it.

Example: Modify Isearch Keys

  ;; change isearch's keys to use arrows to repeat
  (define-key isearch-mode-map (kbd "<left>") 'isearch-repeat-backward)
  (define-key isearch-mode-map (kbd "<right>") 'isearch-repeat-forward)
  (define-key isearch-mode-map (kbd "<up>") 'isearch-ring-retreat)
  (define-key isearch-mode-map (kbd "<down>") 'isearch-ring-advance))

Example: Modify Shell Keys

shell and shell-command 【Alt+!】 have many special keys. Suppose you want to change them. They both use a keymap named comint-mode-map. The following is a example of redefining some of its keys.

  ;; "change keybindings for shell related modes."
   (define-key comint-mode-map (kbd "M-p") 'recenter) ; was comint-previous-input
   (define-key comint-mode-map (kbd "M-n") 'nil) ; was comint-next-input
   (define-key comint-mode-map (kbd "M-r") 'kill-word) ; was comint-previous-matching-input
   (define-key comint-mode-map (kbd "M-s") 'other-window) ; was comint-next-matching-input

   ;; rebind displaced commands that i still want a key
   (define-key comint-mode-map (kbd "<f11>") 'comint-previous-input)
   (define-key comint-mode-map (kbd "<f12>") 'comint-next-input)
   (define-key comint-mode-map (kbd "S-<f11>") 'comint-previous-matching-input)
   (define-key comint-mode-map (kbd "S-<f12>") 'comint-next-matching-input)


Emacs, Change Keys