Emacs Keys: Change Minor Mode Keys

By Xah Lee. Date: . Last updated: .

General Steps to Change Minor Mode Keybinding

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

  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 is the feature symbol for the mode.
  4. In your emacs init file, start with (require 'xx) (if the mode has a feature symbol), then use keymap-set (emacs 29) or define-key to bind the key.

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

(progn
  ;; 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 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.

(progn
  ;; "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)
)

Reference

Emacs, Change Keys