Emacs: Change Major Mode Keys

By Xah Lee. Date: . Last updated: .

To change/add keys to a major mode, Add a function to the major mode's hook. A hook will load your code whenever that mode is activated. [see Emacs: What is Major Mode] [see Emacs: What is Hook]

Here's a example of adding keys to go-mode for Golang .

(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))

To unbind a key, set it to nil.

General Steps

  1. Find the major mode's name. [see Emacs: Find Major Mode Name]
  2. Find the mode's hook name. [see Emacs: What is Hook]
  3. Define a function. (See example abov.)
  4. Add the function to the hook.

Modify Major Mode Keymap Directly

Alternatively, 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))

Major Mode and Minor Mode

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Emacs Keys



Key Tips

Emacs Pinky

Keybinding Design