0

I'm trying to add a keybinding to prog-mode-map, which is supposed to be valid in all programming maps, but I can't be doing it right, cause I have to add lines, like the second one, to have it working in each map

(define-key prog-mode-map (kbd "C-M-w r") 'eglot-rename)

(define-key c++-mode-map (kbd "C-M-w r") 'eglot-rename)

Any pointers as to what I'm doing wrong?;)

1 Answer 1

2

You have to make C-M-w a prefix key first (by default it it bound to append-next-kill):

(setq c-m-w-keymap (make-sparse-keymap))
(define-key prog-mode-map (kbd "C-M-w") c-m-w-keymap)

Then you can add keybindings to it:

(define-key c-m-w-keymap (kbd "r") #'eglot-rename)

Then both prog-mode and its children (e.g. c++-mode) will know about it.

EDIT: ... and since the above hijacks an existing keybinding in order to allow the key to become a prefix key, you might want to add a binding in the new keymap to replace the old binding, e.g.:

(define-key c-m-w-keymap (kbd "a") #'append-next-kill)

Alternatively, as @phils suggests in a comment, you might choose an unused key, e.g. C-M-z is not used in prog-mode-keymap.

I tend to avoid such ad-hoc bindings, primarily because if I don't use them often enough I forget about their existence; instead I tend to define function keys[1] as prefix keys for clusters of related commands. I can remember only a few of those too, but I can add stickers on the rest to remind me for which cluster a particular function key is a prefix, and I can use something like <f5> C-h to find what's hidden behind the <f5> prefix key.


[1] You might want to only use <f5>-<f12> - Emacs defines the first four by default.

5
  • 1
    For the same reason, consider using some other prefix which doesn't conflict.
    – phils
    Commented Nov 15, 2022 at 2:25
  • actually, it worked if I inserted ampersand, cause I already have defined it as a prefix-key, (define-key prog-mode-map (kbd "C-M-w r") #'eglot-rename) Commented Nov 15, 2022 at 10:07
  • I don't understand what you mean: where did you insert ampersand?
    – NickD
    Commented Nov 15, 2022 at 12:36
  • Sorry, I mean to say hash sign. Commented Nov 18, 2022 at 22:37
  • You mean #'eglot-rename instead of 'eglot-rename? If so, that only tells the compiler that it is dealing with a function, so that it can warn you if the function is not defined. See the function special form (for which #' is a shorthand, similar to using ' for the quote special from) in Anonymous Functions. When applied to a symbol, #' does nothing more than what is described above: in particular, it is functionally equivalent to a plain ' in that case.
    – NickD
    Commented Nov 18, 2022 at 23:23

Your Answer

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

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