help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Evaluating python code blocks in python-mode


From: Yuri D'Elia
Subject: Re: Evaluating python code blocks in python-mode
Date: Thu, 25 Jun 2015 12:25:33 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Icedove/38.0

On 06/21/2015 08:52 PM, Andreas Röhler wrote:
> It might be an option to use existing markers from folding-mode. OTOH 
> don't see a command there how to copy the section. Do you?

So this is what I came up with and I currently use:

http://www.thregr.org/~wavexx/tmp/python-mode-extra.el

Sorry for not inlining the file, but I think it's more readable.

The idea is that "C-c C-c" sends the current fold you're in. If you're in a 
nested fold, subfolds are send too. If you're not in a fold, the buffer (or 
narrowed region) is sent instead.

As an added bonus, I wanted to define a generic block delimiter, which is # --- 
in my case. `python-shell-send-fold-or-section' will send the current fold if 
there's any, up to the closest block delimiter (if any).

So for example, in a file like:

 print "1"
 # ---
 print "2"

"C-c C-c" on either print statement will be limited to that statement. Block 
delimiters can be nested inside folds, and work as you'd expect: if you're in 
the same fold as a delimiter, the delimiter is used. If you're upwards, the 
delimiter is ignored.

This makes it very easy to delimit "computation blocks", as you'd normally do 
in an interactive notebook, without the burden to define folds for each.

To top that, the region being sent is added with a volatile highlight 
(volatile-highlights.el is required) so you see what's being evaluated.

I love it.

It works in Fabián's python-mode, but should work with minimal changes with 
other modes too.

I actually redefine some bindings for python-mode to behave more like ESS 
(which IMHO has a better layout for interactive evaluation), resulting in 
something like:

(add-hook 'python-mode-hook
          (lambda ()
            (local-set-key (kbd "C-c C-j") 'python-shell-send-line)
            (local-set-key (kbd "C-c C-n") 'python-shell-send-line and-step)
            (local-set-key (kbd "C-c C-f") 'python-shell-send-defun)
            (local-set-key (kbd "C-c C-b") 'python-shell-send-buffer)
            (local-set-key (kbd "C-c C-c") 'python-shell-send-fold-or-section)))

`python-shell-send-fold-or-section' is what is defined in python-mode-extra.el, 
which was a little tricker to define than anticipated, but it seems to work 
correctly.

I re-use the markers defined in folding-mode, so if you want to customize the 
markers just use `folding-add-to-marks-list'. folding-mode doesn't need to be 
enabled. I actually don't use folding, I just wanted to re-use the same methods.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]