Keymaps

Keymaps

January 24, 2024 | seedling, permanent

tags :

Emacs feature #

to map keyboard shortcuts to functions globally or in specific mode gnu ref

Global #

Emacs uses keymaps to record which keys call which commands. When you use global-set-key to set the key binding for a single command in all parts of Emacs, you are specifying the key binding in current-global-map.

Specific modes, such as C mode or Text mode, have their own keymaps; the mode-specific keymaps override the global map that is shared by all buffers.

The global-set-key function binds, or rebinds, the global keymap. For example, the following binds the key C-x C-b to the function buffer-menu:

(global-set-key "\C-x\C-b" 'buffer-menu)

Local In modes #

Mode-specific keymaps are bound using the define-key function, which takes a specific keymap as an argument, as well as the key and the command. For example, my .emacs file contains the following expression to bind the texinfo-insert-@group command to C-c C-c g:

(define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@group)

The texinfo-insert-@group function itself is a little extension to Texinfo mode that inserts ‘@group’ into a Texinfo file. I use this command all the time and prefer to type the three strokes C-c C-c g rather than the six strokes @ g r o u p. (‘@group’ and its matching ‘@end group’ are commands that keep all enclosed text together on one page; many multi-line examples in this book are surrounded by ‘@group … @end group’.)

Here is the texinfo-insert-@group function definition:

(defun texinfo-insert-@group ()
  "Insert the string @group in a Texinfo buffer."
  (interactive)
  (beginning-of-line)
  (insert "@group\n"))

(Of course, I could have used Abbrev mode to save typing, rather than write a function to insert a word; but I prefer key strokes consistent with other Texinfo mode key bindings.)

You will see numerous define-key expressions in loaddefs.el as well as in the various mode libraries, such as cc-mode.el and lisp-mode.el.

(add-hook 'python-mode-hook
          (lambda ()
            (local-set-key "\C-ca" 'pytest-all)
            (local-set-key "\C-cm" 'pytest-module)
            (local-set-key "\C-c." 'pytest-one)
            (local-set-key "\C-cc" 'pytest-again)
            (local-set-key "\C-cd" 'pytest-directory)
            (local-set-key "\C-cpa" 'pytest-pdb-all)
            (local-set-key "\C-cpm" 'pytest-pdb-module)
            (local-set-key "\C-cp." 'pytest-pdb-one)))


Links to this note