Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define keymap for minor mode correctly

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?

like image 890
ayvango Avatar asked Dec 06 '25 21:12

ayvango


2 Answers

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?

like image 184
Stefan Avatar answered Dec 09 '25 13:12

Stefan


  1. Just create a keymap normally, using make-sparse-keymap, and name it my-mode-map --- you're done. No need for :keymap arg to define-minor-mode.

  2. 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.)

  3. But why not just use a global binding, via global-set-key? Why do you even need this to be a minor-mode binding?

like image 31
Drew Avatar answered Dec 09 '25 12:12

Drew