I'd like to bind C-x C-e to python-shell-send-region when I am in python major-mode.

In my config file, I have an add-hook for python mode, but I'd like this keybinding override to be removed/restored when I exit python major-mode.

The use-case for this is that I want to be able to switch my *scratch* buffer between modes and for things to continue making sense.

Is there an idiomatic way to achieve this?

1 Answer 1


Not too sure what you're asking. But it sounds like the answer is to bind your key in the major mode's keymap, not in the global-map.

For example, if the keymap for your Python mode is python-mode-map then do this:

(define-key python-mode-map (kbd "C-x C-e") 'python-shell-send-region)
  • Ahh, that's exactly it. In the process of running around for a solution, I wasn't seeing the forest for the trees. (and to explain, I was asking for a hook for when python-mode is exited so that I could restore what was previously bound - quite convoluted and unecessary) Thanks for the quick answer.
    – MB.
    Nov 7, 2019 at 4:14
  • 1
    More information here: gnu.org/software/emacs/manual/html_node/eintr/…
    – aartist
    Nov 7, 2019 at 12:54

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.