Search code examples
emacspython-mode

switch buffer settings using python-mode in emacs?


I have been using emacs for a while but not so familiar with lisp programming. Its been just couple of days I started coding Python on emacs. I found python-mode to be quite useful and I want to explore it further. I found a few emacs lips functions on internet, tewaked them a bit to make the interface userfriendly. I am trying to achieve following actions

I usually start emacs with 2 vertical windows, one with python source and other is a shell. I should be able to do following using keyboard bindings

  • switch between buffers (working)
  • execute a region (working) but replaces the source buffer with shell buffer. I want to execute selected region in original shell buffer.
  • execute a line (working) but same issue as above. when i pres say , the line should be executed in python shell without replacing any buffers. so copy the line, switch to python shell, execute line, switch back to python source buffer.

I am not able to achieve switching action above. Following is my code from my init.el file

(defun goto-python-shell ()
  "Go to the python command window (start it if needed)"
  (interactive)
  (setq current-python-script-buffer (current-buffer))
  (if (boundp 'current-python-shell-buffer)
    (switch-to-buffer-other-window current-python-shell-buffer)
    (py-shell))
  (end-of-buffer)
 )

 (defun goto-python-source ()
   "switch back to source window"
   (interactive)
  (setq current-python-shell-buffer (current-buffer))
   (switch-to-buffer-other-window current-python-script-buffer)
 )

 (defun py-execute-statement-and-step ()
   "select a statement, submit as a region and then step forward"
   (interactive)
   (beginning-of-line 1)
   (let ((beg (point)))
     (py-next-statement 1)
     ; if last statement.
        (if (= (point) beg) (end-of-buffer ))
 ; (switch-to-buffer-other-window current-python-shell-buffer)
   (py-execute-region beg (point))
   (switch-to-buffer-other-window current-python-script-buffer)
   )
 )

 ; some key bindings
 (define-key python-mode-map (quote [f9]) 'py-execute-statement-and-step)
 ;(define-key python-mode-map (quote [f10]) `py-execute-region)
 ;py-shell-switch-buffers-on-execute
 (define-key python-mode-map (quote [f10]) `py-shell-switch-buffers-on-execute)
 (define-key python-mode-map (quote [f11]) `py-execute-buffer)
 (define-key python-mode-map (quote [f12]) `goto-python-shell)
 (define-key py-shell-map (quote [f12]) `goto-python-source)

Please advice.

Also since i am new to python-mode, can someone share nice initializations for using python-mode similar to above?

thanks much for your help.

Regards, AJ


Solution

  • You should take a look at the first answer to this question and customize the py-shell-switch-buffers-on-execute variable.

    This way you won't need all your custom functions to make python-mode work like you want (i.e. keeping the source buffer active)