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 ;; by convention, variable names for keymap should end in -map ;; by convention, major mode's keys should begin with the form C-c C-‹key› (defvar-keymap eww-textarea-map :doc "Keymap for `xx mode'" "C-c C-a" 'xx-mode-cmd1 "C-c C-b" 'xx-mode-cmd2) ;; ---------------------------------------- ;; 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-modeto 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:
;; by convention, variable names for keymap should end in -map ;; by convention, major mode's keys should begin with the form C-c C-‹key› (defvar-keymap eww-textarea-map :doc "Keymap for `xx mode'" "C-c C-a" 'xx-mode-cmd1 "C-c C-b" 'xx-mode-cmd2)
Keybinding Syntax
For key syntax and related question about keys, see:
Reference
Elisp, 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 Lookup Doc or Search Web 📜
- Elisp: Create a Hook
- Elisp: Major Mode Names
- Elisp: provide, require, features
- Elisp: load, load-file, autoload
- Elisp: Syntax Table
Emacs, Change Keys
- Emacs Keys: Define Key
- Emacs Keys: Keybinding Functions, Emacs 29 Change
- Emacs Keys: Syntax
- Emacs Keys: Good and Bad Key Choices
- Emacs Keys: Swap CapsLock Control
- Emacs Keys: Meta Key
- Emacs Keys: Change Major Mode Keys
- Emacs Keys: Change Minor Mode Keys
- Emacs Keys: Minor Modes Key Priority
- Emacs Keys: Change Minibuffer Keys
- Elisp: Create Keymap (keybinding)