Elisp: Create Keymap (keybinding)
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) ;; )
- Copy and paste the above code into a buffer.
- Then, Alt+x
eval-buffer
. - Then, open a new buffer. Alt+x
xx-mode
to activate it. - Then, Alt+x
describe-mode
.
You'll see this:
How Does it Work?
To have keybinding for a major mode, the 2 essential steps are:
- Define a keymap.
- 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:
Reference
Emacs lisp, writing a major mode. Essentials
- Elisp: Write a Major Mode for Syntax Coloring
- Elisp: Font Lock Mode
- Elisp: Syntax Color Comments
- Elisp: Write Comment/Uncomment Command
- Elisp: Keyword Completion
- Elisp: Create Keymap (keybinding)
- Elisp: Create Function Templates
- Emacs: Command to Search Web 🚀
- Elisp: Create a Hook
- Elisp: Major Mode Names
- Elisp: provide, require, features
- Elisp: load, load-file, autoload
- Elisp: Syntax Table