Emacs Keys: Define Key ⌨

By Xah Lee. Date: . Last updated: .

How to Assign Key to Command

In emacs, you can create any keyboard shortcut to any command or a Key Macro.

For Emacs 29 (date 2023) , the syntax to change key is this

(keymap-global-set key cmd)

The key is a string of the Key Syntax .

The cmd can be a command name (a Symbol), or a string of Key Macro syntax.

Simply type that code in any buffer, and eval it. The new keybinding is effective immediately. [see Emacs: Evaluate Elisp Code]

Or, you can put the code in Emacs: Init File. If you made some mistake and need to start emacs without loading your init file, see emacs init: Ignore Init File.

Example. Emacs 29 (2023) or later

Define a Key for a Command

(keymap-global-set "C-t" #'backward-char)

Define a Key for Key Macro

;; make the f6 key send control-g
(keymap-global-set "<f6>" "C-g")
;; make the f6 key insert a string. space between chars are required
(keymap-global-set "<f6>" "s o m e t h i n g")

Remove a Keybinding

;; remove a keybinding

;; for emacs 29 or after
(keymap-global-set "C-t" nil)
;; or use
(keymap-global-unset "C-t")

Old keybinding syntax, for emacs 28 (2022) or before

Find the Command Name of a Given Key

Alt+x describe-key, then type the key combination.

Show Current Major Mode Keys

Alt+x describe-mode. [see Emacs: Major Mode]

Show ALL Keybinding

Alt+x describe-bindings.

Each Major Mode or Minor Mode usually add or change some keys. So, key list generated is specific to current buffer.

System-Wide Keybinding Setup

best is a programable keyboard:

Reference

Emacs, Change Keys