Emacs Keys: Change Major Mode Keys

By Xah Lee. Date: . Last updated: .

General Steps to Change Major Mode Keys

To change or add keys to a Major Mode , add a function to the major mode's Hook.

  1. Find the major mode's name. 〔see Emacs: Find Major Mode Name
  2. Find the mode's hook name. 〔see Emacs: List All Hooks
  3. Add a function to the Hook .
  4. The function should contain code to change key, e.g. keymap-local-set, keymap-set.

Example: Add Key for Go-Mode

(defun my-config-go-mode ()
  "For use in `go-mode-hook'."

  ;; emacs 29 syntax
  (keymap-local-set "C-c C-c" #'gofmt)

  ;; before emacs 29 syntax
  ;; (local-set-key (kbd "C-c C-c") #'gofmt)

  ;; more here
  )

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

Example: Create Leader Key Sequence for Org Mode

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)

    ;; emacs 29 syntax
    (keymap-set dired-mode-map "C-o" #'find-file)

    ;; emacs 28 syntax
    (define-key dired-mode-map (kbd "C-o") #'find-file)
    ;;
    ))

Emacs, Change Keys