Emacs: Change Major Mode Keys

By Xah Lee. Date: . Last updated: .

How to change/add keys to a major mode?

Use a hook for the mode. A hook will load your code whenever that mode is activated.

;; example of binding keys only when html-mode is active

(defun my-html-mode-config ()
  "For use in `html-mode-hook'."
  (local-set-key (kbd "<C-right>") 'sgml-skip-tag-forward)
  (local-set-key (kbd "<C-left>") 'sgml-skip-tag-backward)
  (local-set-key (kbd "C-c C-p") nil) ;  remove a key

;; add to hook
(add-hook 'html-mode-hook 'my-html-mode-config)

If you know the mode's keymap variable name, you can modify it directly.

  ;; modify dired keys
  (require 'dired )
  (define-key dired-mode-map (kbd "o") 'other-window)
  (define-key dired-mode-map (kbd "2") 'delete-window)
  (define-key dired-mode-map (kbd "3") 'delete-other-windows)
  (define-key dired-mode-map (kbd "4") 'split-window-below)
  (define-key dired-mode-map (kbd "C-o") 'find-file))

What's Hook?

Emacs: What's Hook?

Emacs Keybinding How-To Topic

  1. Emacs: How to Define Keys
  2. Emacs: Change Major Mode Keys
  3. Emacs: Change Minor Mode Keys
  4. Emacs: Fix Minor Mode Key Priority
  5. Emacs: Define Key Sequence
  6. Emacs: How to Bind Super Hyper Keys
  7. Emacs: How to Define Menu Key
  8. Emacs: Remapping Keys Using key-translation-map
  9. Emacs: Bind Number Pad Keys
  10. Emacs: How to Set Mouse Buttons
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.