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.

(when (fboundp 'go-mode)

  (defun my-golang-config ()
    "For use in `go-mode-hook'."
    (local-set-key (kbd "C-c C-c") 'gofmt)
    ;; more stuff here
    )

  (add-hook 'go-mode-hook 'my-golang-config)

  (add-hook 'before-save-hook 'gofmt-before-save)
  )

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

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