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. 〔see Emacs: Key Macro

for Emacs 29 (Released 2023-07) , the syntax to change key is this

(keymap-global-set key cmd)

before emacs 29, the syntax to change key is this

(global-set-key (kbd key) cmd)

The key is a string of the key syntax. See Emacs Keys: Syntax

The cmd can be a command name (a Symbol), or a string of keyboard macro syntax. 〔see Emacs: Key Macro

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: Ignore Init File.

Example

;; make Ctrl+t call whitespace-mode

;; for emacs 29, use this
(keymap-global-set "C-t" #'whitespace-mode)

;; before emacs 29, use this
(global-set-key (kbd "C-t") #'whitespace-mode)
;; example for emacs 29, make the f6 key do cancel
(keymap-global-set "<f6>" "C-g")

;; example for emacs 29, make the f6 key insert a string. space betweer chars are required
(keymap-global-set  "s o m e t h i n g")

Remove a Keybinding

;; remove a keybinding

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

;; before emacs 29, use this
(global-set-key (kbd "C-t") nil)
;; or
(global-unset-key (kbd "C-t"))

Find the Command Name of a Given Key

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

List Current Major Mode's Keys

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

List 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.

misc

system-wide keybinding setup:

best is a programable keyboard:

Reference

Emacs, Change Keys