Emacs: Remapping Keys Using key-translation-map

Master emacs+lisp, benefit for life. Testimonials. Thank you for support.
, , …,

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 "↑"))

You could also use global-set-key, like this:

(global-set-key (kbd "<f8>") (lambda () (interactive) (insert "λ")))

;; or

(global-set-key (kbd "<f8>") "λ") ; macro shortcut. doesn't work as well as using lambda

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

Using key-translation-map doesn't have this problem.

key-translation-map is more low level.

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>"))

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 combination. Using (define-key key-translation-map …) is more versatile. (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)))

Who Need to Use Unicode That Often?

Using proper symbols can decreases ambiguity at syntax level. Examples:

For example, bullet (•), “curly quote”, dash (—), angle bracket for 〈article title〉 and 《book title》 〔☛ Intro to Chinese Punctuation〕, and i use 【lenticular bracket】 to mark keyboard shortuct, 「corner bracket」 to mark computer code, and i use FULLWIDTH AMPERSAND (&) to avoid HTML entity complexity 〔☛ HTML Entities, Ampersand, Unicode, Semantics〕.

Using proper symbols decreases ambiguity at syntax level. For example, the ASCII asterisk (*) can mean lots of things. But a dedicated bullet “•” carries a precise semantics.

For coding, some languages heavily use math symbols (⁖ APL, Mathematica). For functional languages such as Haskell, Scheme Lisp, you can setup for example “λ” to mean “lambda” 〔☛ Emacs: Pretty Lambda λ in Emacs 24.4〕, “≠” to mean “!=”, “⊕” for user-defined operators, etc. You can also use symbols for variable names in emacs lisp, JavaScript, Java (⁖ α = 3 instead of alpha = 3). See:

Like what you read?
Buy Xah Emacs Tutorial
or share some
blog comments powered by Disqus