I have seen all of the following for defining a keyboard binding. All of these work (at least on MS Windows). I don't know if there is another way to do the same thing.
I am wondering if there is a standard or recommended way to define a keyboard binding and if it is recommended to avoid some of these.

(global-set-key "\M-r" 'some-command)
(global-set-key [(meta r)] 'some-command)
(global-set-key [?\M-r] 'some-command)
(global-set-key (kbd "M-r") 'some-command)
  • 1
    I doubt there is a recommended syntax but I personally like the (global-set-key (kbd "M-r") 'some-command) method because of the consistency in which the key combinations can be defined.. you don't have to remember when or when not to escape stuff. Aug 23 '15 at 22:13

There is no single standard way, because there are different use cases.

If you are writing such code manually, in your init file for example, then you might prefer the (kbd ...) format, because the argument to kbd uses the same notation that Emacs uses when it communicates with you about key bindings (in *Help*, for example).

But if you are creating bindings using Emacs Lisp, then you might prefer the vector notation, in particular [(meta r)] etc., as it is quite a bit easier to manage.

Some people consider the simple string approach to be archaic, but it is handy when the key is simple: "a" is simpler and at least as readable as (kbd "a"). But simple strings are harder to read/use when it comes to modifier keys etc.

(global-set-key [?\M-r] 'some-command)

is the "native" way. All others are built on top of this one, basically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.