1

When I am working on a file in my application in emacs/elpy, I always have to jump back into my main file buffer and do C-u C-c C-c (i.e. ) in order to run and debug it in the python shell. This is rather time consuming, so I was wondering, how can I define a corresponding C-u C-c C-c binding but which always runs my defined main file?

0

By modifying ChillarAnands code, I eventually got a function and a keybinding working to do what I want. Now I can edit any python file, run C-c C-c and the main file will be sent to the shell. This way I don't have to keep jumping back to the main file all the time just to run the program.

(setq my/main-file "/path/to/main/file.py")
(defun my/special-send-region-or-buffer (&optional arg)
  (interactive "P")
  (if (get-file-buffer my/main-file) () (find-file my/main-file))
  (with-current-buffer (get-file-buffer my/main-file)
    (elpy-shell-send-region-or-buffer arg))
  )

(define-key elpy-mode-map (kbd "C-c C-c") 'my/special-send-region-or-buffer)

If I want to run the __name__ == '__main__' part of the program I just run as usual C-u C-c C-c (that's what &optional arg takes care of).

I am horrible with Emacs lisp, so this function has probably got some flaws. Critique is appreciated.

0

I guess, in your project only one file has main and no matter in which file you are currently, pressing C-u C-c C-c should execute that file's main.

Elpy cannot find which file has main function. So you can set path to that main file and define new function which does what you want.

(setq my/main-file "/path/to/main/file.py")

(defun my/special-send-region-or-buffer (&optional arg)
  (interactive "P")
  (if arg
     (with-current-buffer (get-file-buffer my/main-file)
        (elpy-shell-send-region-or-buffer arg))
    (elpy-shell-send-region-or-buffer)))

(define-key elpy-mode-map (kbd "C-c C-c") 'my/special-send-region-or-buffer)

Add this to your config. Now if you run C-c C-c it will act like normal function. But with prefix argument, it will send that particular file with main function.

  • This function doesn't seem to work. When I type eval-expression RET (my/special-send-region-or-buffer t), while in a file that is not the main file, it just runs that file and not the main file. – Perry Sep 27 '15 at 17:15
  • I guess the (elpy-shell-send-region-or-buffer arg) should be nested inside the with-current-buffer (and then the progn is redundant). – npostavs Sep 27 '15 at 20:53
  • @ChillarAnand. This still doesn't work, because get-buffer-create gets or creates a new buffer by a buffer name not a file name. So when you call the function it just creates an empty buffer named "/path/to/main/file.py" and sends no code to the shell. Look at my answer to see how I fixed it. – Perry Sep 28 '15 at 7:34

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.