Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs defadvice on python-mode function

In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising function:

(defadvice py-execute-region                                                
   (after py-execute-region-other-window activate)                          
   """ After execution, return cursor to script buffer """                  
   (other-window 1)                                                         
) 

But this does not do anything at all. I've tried other variants like using 'around' rather than 'after'; setting a variable to the script buffer name and then pop-to-buffer to that buffer and stuff like that. No success! I wonder if the mechanics of this is obvious to someone... Thanks!

like image 348
hatmatrix Avatar asked Sep 13 '09 04:09

hatmatrix


3 Answers

In this case the solution appears to be

(custom-set-variables
 '(py-shell-switch-buffers-on-execute nil))
like image 71
hatmatrix Avatar answered Oct 26 '22 10:10

hatmatrix


Use around-advice to wrap the function in a call to save-window-excursion, which will restore the previous window configuration after the command completes.

(defadvice py-execute-region
   (around preserve-window-configuration activate)
   "After execution, return cursor to script buffer"
   (save-window-excursion ad-do-it))

Keep in mind, though, that if the Python buffer wasn't already shown, it will still be hidden after the command completes. To remedy that, you can add another piece of advice to call switch-to-buffer-other-window at the end:

(defadvice py-execute-region
   (after show-pybuf-other-window activate)
   "After execution, show the python buffer in another window."
   (switch-to-buffer-other-window "[PYTHON BUFFER NAME]"))

Also, make sure you don't use """triple quotes""" in elisp. I don't think they work.

like image 2
Ryan C. Thompson Avatar answered Oct 26 '22 08:10

Ryan C. Thompson


What you have there works fine for me. And it should auto-activate, so a separate activation should be unnecessary. However, you do need to de-active and re-activate advice for changes to take effect:

1) define and activate advice

2) it doesn't do what you want, so change the advice

3) deactivate it: (ad-deactivate 'py-execute-region)

4) reactivate it: (ad-activate 'py-execute-region)

Step 4 should pick up the changes you made in step 2. Alternately, you can change the code in step 2 and then just re-evaluate the code in step 4 (assuming the activate flag is set).

like image 1
Joe Casadonte Avatar answered Oct 26 '22 08:10

Joe Casadonte