I am using doom emacs and would like to create a keybinding to run the following line so that I don't need to write it every time I want to run a block of code of python

:w !python

The above line runs python code highlighted in visual mode in the terminal.


The cleanest way is to not reuse Evil-specific commands or keystrokes unless absolutely necessary. Looking at the definition of :w, which happens to be the evil-write command, one can see that it parses the file name argument and calls shell-command-on-region if it starts with a bang. Here's the equivalent specialized command:

(defun my-evil-run-python-region (beg end)
  (interactive "r")
  (if (region-active-p)
      (shell-command-on-region beg end "python")
    (shell-command-on-region (point-min) (point-max) "python")))

(global-set-key (kbd "<F5>") 'my-evil-run-python-region)
| improve this answer | |
  • I am new to emacs so I spent hours trying to figure this out but with no success.I figured there must be something I am doing wrong so i wrote my question. I tried your code and it worked. I don't have enough points to vote for your answer now but should do when I have. Thank YOU!! – Moh Jul 30 at 9:03
  • Thanks. I think you should be able to mark it as preferred answer though, so that the question shows up as solved. – wasamasa Jul 30 at 9:09
  • Done. Thank You!! – Moh Jul 30 at 9:39

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.