Elisp: Create Keymap (keybinding)

By Xah Lee. Date: . Last updated: .

Create Keybinding for a Major Mode

Each major mode typically define many of its own keys for calling the major mode's commands. (by convention, major mode's keys start with Ctrl+c )

Here's how to define the keys for major mode:

;; sample major mode with its own keymap

;; ----------------------------------------
;; commands

(defun xx-mode-cmd1 ()
  "do something"
  (interactive)
  (message "cmd1 called"))

(defun xx-mode-cmd2 ()
  "do something"
  (interactive)
  (message "cmd2 called"))

;; ----------------------------------------
;; keybinding

(defvar xx-mode-map nil "Keymap for `xx-mode'")

;; by convention, variable names for keymap should end in -map

(progn
  (setq xx-mode-map (make-sparse-keymap))
  (define-key xx-mode-map (kbd "C-c C-a") 'xx-mode-cmd1)
  (define-key xx-mode-map (kbd "C-c C-b") 'xx-mode-cmd2)
  ;; by convention, major mode's keys should begin with the form C-c C-‹key›
  )

;; ----------------------------------------
;; define the mode

(define-derived-mode xx-mode prog-mode "xx"
  "xx-mode is a major mode for editing language xx.

\\{xx-mode-map}"

  (use-local-map xx-mode-map)
  ;;
  )
  1. Copy and paste the above code into a buffer.
  2. Then, Alt+x eval-buffer.
  3. Then, open a new buffer. Alt+x xx-mode to activate it.
  4. Then, Alt+x describe-mode.

You'll see this:

sample-mode 2024-05-10
sample-mode 2024-05-10

How Does it Work?

To have keybinding for a major mode, the 2 essential steps are:

  1. Define a keymap.
  2. Use (use-local-map keymap_var_name) in your mode body, so that when the command is called, it sets a local keymap in user's current buffer.

The typical way to define a keymap is this:

(defvar xx-mode-map nil "keymap for `xx-mode-mode'")

(setq xx-mode-map (make-sparse-keymap))

(define-key xx-mode-map (kbd "C-c C-a") 'xx-mode-cmd1)

(define-key xx-mode-map (kbd "C-c C-b") 'xx-mode-cmd2)

;; and more

Keybinding Syntax

For key syntax and related question about keys, see:

Emacs Keys: Define Key

Reference

Emacs lisp, writing a major mode. Essentials