5

I sometimes find myself using a command repeatedly (using M-x) but I do not want to bind it to a key in my init-file, because I only use it in certain sessions. How would I bind a command to a key interactively?

Let's say I want to bind bury-buffer to C-c q. I could use M-: (bind-key "C-c q" 'bury-buffer) (I'm using use-package), but that's a lot of typing. What I want is to complete from a list of all interactive commands, and then input a kbd-string to which the chosen command should be bound.

1
  • Not what you asked for, but consider using M-p and M-n to move through the history of commands you invoked with M-x.
    – user12563
    Feb 24, 2017 at 16:36

2 Answers 2

6

M-x global-set-key RET prompts you to hit a key sequence and then to say what command to bind globally to that key sequence.

E.g.:

M-x global-set-key RET C-c q bury-buffer

The key binding remains in effect only for the current session, and only until you change or delete the binding for that key.

Completion is available for the command name. For the key, you just hit the key you want - no need to fiddle with any key description (e.g. kbd).

Unlike define-key, global-set-key is a command, not just a (non-interactive) function. There is also command local-set-key, for binding a key in the local keymap of the current buffer, that is, (typically) the keymap of the buffer's major mode.

1
  • Thank you! I didn't know about global-set-key. Nice that its available in subr.el, so it is possible to make alternate versions of it easily. Feb 19, 2017 at 21:43
1

If you use a macro, you get 2 advantages :

  1. Inbuilt, idiomatic way in Emacs to assign a key binding to a series of actions - even though in your case the series of actions is just a single action. So you don't have to look for methods that are likely to break with new packages, Emacs releases etc.

  2. If ever you want to repeat more than one commands, you have a well practised skill in your head to make your life easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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