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

  1. How to Define Keys
  2. Change Major Mode Keys
  3. Change Minor Mode Keys
  4. Fix Minor Mode Key Priority
  5. Define Key Sequence
  6. How to Bind Super Hyper Keys
  7. How to Define Menu Key
  8. Remapping Keys Using key-translation-map
  9. How to Set Mouse Buttons

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy a nice keyboard: Best Keyboards for Emacs

Emacs

Emacs Lisp

Misc