Emacs: Change Major Mode Keybinding

By Xah Lee. Date: . Last updated: .

To change or add keys to a Major Mode , add a function to the major mode's Hook. The hook runs your functions whenever that mode is activated.

To unbind a key, set it to nil.

General Steps to Change Major Mode Keys

  1. Find the major mode's name. [see Emacs: Find Major Mode Name]
  2. Find the mode's hook name. [see List of Emacs Hooks]
  3. Add a function to the Hook .
  4. The function should contain a line like this (local-set-key (kbd "C-c C-c") #'gofmt)

Example: Change Major Mode Keybinding for go-mode

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

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

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

Modify Major Mode Keymap Directly

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

(progn
  ;; modify dired keys
  (require 'dired)
  (when (boundp 'dired-mode-map)
    (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)))

Emacs, Change Keys