Just create a keymap normally, using
make-sparse-keymap
, and name itmy-mode-map
--- you're done. No need for:keymap
arg todefine-minor-mode
.Or use the keymap you create using
make-sparse-keymap
as the value of:keymap
, if you like. (But no need to, since it is named as the minor mode expects:my-mode-map
.)But why not just use a global binding, via
global-set-key
? Why do you even need this to be a minor-mode binding?
How to define keymap for minor mode correctly
-
30-06-2022 - |
Question
I'd like to define custom mode for improvements that suits to any program mode. And I need to define key-bindings for all this modes. I choose to use define-minor-mode
with :keymap
to declare key bindings with minimum effort.
I'd like to bind comment-or-uncomment-region
to "C-;"
The kbd macro gave me [67108923]
magic number for this key sequence.
I've wrote sample that doesn't work
(define-minor-mode
my-mode
nil nil
:keymap '(
( [67108923] . comment-or-uncomment-region )
)
)
I've registered mode, toggled it on, but pressing С-;
produces notifications that the key sequence is not defined
After that I've wrote in the scratch buffer and evaluate simple global-set-key
that performed in expected way.
(global-set-key [67108923] 'comment-or-uncomment-region )
Now pressing C-;
produces expected comment-or-oncomment-region
behavior.
I've tried to debug the issue with searching to function info via C-h f
. It produces strange output, comment-or-oncomment-region
is bound twice to different key sequences:
It is bound to C - ;, C-;
First one appears and disappears with the minor mode toggling, other emerge from global-set-key
invocation.
How can it be, if I've used the same key definition for both maps? What details I have missed?
Solution
OTHER TIPS
Don't use the magic number. IOW use [?\C-\;]
, so it can be understood by humans.
And I agree with Drew:
(defvar my-mode-map
(let ((map (make-sparse-keymap)))
(define-key map [?\C-\;] 'comment-or-uncomment-region)
map))
(define-minor-mode my-mode
"blabla"
nil nil nil
<add code, if any>)
Oh, and one more thing: why would you prefer C-;
over the standard M-;
binding?