Emacs: Remapping Keys Using key-translation-map

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

If you want to define a key for inserting a Unicode character such as math symbol λ, the best way is to use key-translation-map.

Example of using define-key with key-translation-map:

(define-key key-translation-map (kbd "<f8>") (kbd "λ")) ; 【F8】 insert λ char

More examples:

;; set keys to type Unicode
(define-key key-translation-map (kbd "<f9> u <down>") (kbd "↓"))
(define-key key-translation-map (kbd "<f9> u <left>") (kbd "←"))
(define-key key-translation-map (kbd "<f9> u <right>") (kbd "→"))
(define-key key-translation-map (kbd "<f9> u <up>") (kbd "↑"))

Swap Keys

You can use it to swap keys.

;; swap keys
(define-key key-translation-map (kbd "<f11>") (kbd "<f12>"))
(define-key key-translation-map (kbd "<f12>") (kbd "<f11>"))

Problem Using global-set-key

You could also use global-set-key, but it has problems. When you do interactive search 【Ctrl+s】, then when you type your key, it'll exit the search instead of inserting the char.

;; using global-set-key to insert unicode arrow. This won't work when in isearch
(global-set-key (kbd "<f8>") (lambda () (interactive) (insert "→")))

keyboard-translate

Note: there's the function keyboard-translate. However, it is designed to translate character only. So, key combination isn't a character and you can't use it for Hyper key combination. (Due to historical reasons, keyboard-translate does work for some Ctrl combination key. (thanks to Stefan Monnier and Deniz Dogan for this tip. (Source groups.google.com)))

Like it? Buy Xah Emacs Tutorial.
blog comments powered by Disqus