0

i want a shortcut for the nice little function comment-or-uncomment-region. The thing is, it works fine for me in every mode using M-x comment-or-uncomment-region. And espacially it works differently (# for python and // for C++) so everything is fine here. But as i said i want a shortcut for this. So i wrote the following in my init.el file:

(global-set-key (kbd "C-;") 'comment-or-uncomment-region)

This now works for all my .cpp files, where I'm in c++-mode, but in python-mode it says, this function is not on a key. But i think its global-set, so what am I doing wrong? Or are some other functions able to unset the key (maybe in the initialization) ?

  • A minimal recipe to repro it, starting from emacs -Q (no init file), would help answering. – Drew Apr 2 at 23:32
  • python-mode is probably binding its own command to the key in its keymap. Try binding the key to python-mode-map in python-mode-hook or using something like eval-after-load. – DoMiNeLa10 Apr 3 at 5:34
  • Thank you! A hook has done it. But it somehow doesnt know the comment character anymore, but with (add-hook 'python-mode-hook (local-set-key (kbd "C-;") 'comment-or-uncomment-region))' and '(add-hook 'python-mode-hook (setq comment-start "#")) it works. Im sure this isnt the cleanest way, but it works ! Thank you for that hint! @DoMiNeLa10 – Reddy Apr 3 at 10:07
  • Curious why you don't just use comment-dwim? I think it is bound by default to M-; – Willy Lee Apr 3 at 15:09
  • @Reddy these won't work properly, as add-hook takes a function as the argument. – DoMiNeLa10 Apr 3 at 16:04
1

Major modes have their own keymaps, and python-mode probably overrides the binding from the global one. You can fix this by adding a hook that will set the key in python-mode's map like this:

(add-hook 'python-mode-hook
          (lambda ()
            (define-key python-mode-map (kbd "C-;") #'comment-or-uncomment-region)))
  • That sounds good, but sadly doesn't work for me. I also tried to do it not via the init.el file, with 'M-x global-set-key RET C-; comment-or-uncomment-region' (same with local while in python mode) and it still doesnt change it. So I think it is not overwritten. – Reddy Apr 3 at 20:49

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.