I am using org-mode and want to override the local binding of C-c C-x C-z, bound to org-resolve-clocks by default. The manual says

As described in Local Keymaps, major modes and minor modes can define local keymaps. ... If you wish to change one of these keymaps, you must use the mode hook (see Hooks).

So I have these lines in my ~/.emacs:

(global-set-key (kbd "C-c C-x C-SPC") 'my-function)

(global-set-key (kbd "C-c C-x C-z") 'my-function)

(add-hook 'org-mode-hook
      (lambda ()
        (local-set-key (kbd "C-c C-x C-z") 'my-function)))

The first line binds an unbound key to the function. The second line binds a key already bound in org-mode to the function. The remaining lines define the hook.

I start Emacs anew and describe the keys. C-c C-x C-SPC is bound to my-function and C-c C-x C-z is bound to the default org-resolve-clocks in an org buffer and to my-function elsewhere. If I run the binding code interactively in an org buffer with M-::

(local-set-key (kbd "C-c C-x C-z") 'my-function)

then the key is bound to my-function and not the default.

I also tried another answer in this thread on setting major-mode specific keybindings in emacs and it failed:

(with-eval-after-load 'org-mode
  '(define-key org-mode-map (kbd "C-c C-x C-SPC") 'my-function)

I am running Emacs 25.3 (9.0).

How can I override a binding in set in a major mode?


You can bind your function in org-mode using define-key:

(define-key org-mode-map (kbd "C-c C-x C-z") 'my-function)

It will override any global bindings and work only in an org-mode buffer.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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