Subject: bug#21086: 24.5; python.el: python-shell-buffer-substring fails under certain circumstances

From: Yuri D'Elia <[email-masked]>
Date: Sat, 18 Jul 2015 18:13:33 +0200

Assuming some python buffer like:

#....
if 1:
    print 1

where the selected region is "print \"1\"" (mark before "p"),
`python-shell-send-region' would fail with:

File "test.py", line 3
    print 1
        ^
IndentationError: expected an indented block

The reason lies within `python-shell-buffer-substring', which assumes
that a region always starts with the correct indentation.

The attached patch fixes the above behavior: when the region doesn't
start with indentation, but the current block does (looking at
(current-indentation)), we prefix the fillstr with the correct amount of
indent.
--- python.el.Orig	2015-07-18 18:00:49.367517569 +0200
+++ python.el	2015-07-18 18:03:01.203659502 +0200
@@ -2548,18 +2548,22 @@
                      (make-string
                       ;; Subtract 2 because of the coding cookie.
                       (- (line-number-at-pos start) 2) ?\n))))
-         (toplevel-block-p (save-excursion
-                             (goto-char start)
-                             (or (zerop (line-number-at-pos start))
-                                 (progn
-                                   (python-util-forward-comment 1)
-                                   (zerop (current-indentation)))))))
+         (block-param (save-excursion
+                        (goto-char start)
+                        (progn
+                          (python-util-forward-comment 1)
+                          (list (current-indentation)
+                                (/= (point) start)))))
+         (block-indentation (car block-param))
+         (starts-with-indentation-p (cadr block-param)))
     (with-temp-buffer
       (python-mode)
       (if fillstr (insert fillstr))
+      (when (and (> block-indentation 0) (not starts-with-indentation-p))
+        (insert (make-string block-indentation ?\s)))
       (insert substring)
       (goto-char (point-min))
-      (when (not toplevel-block-p)
+      (when (> block-indentation 0)
         (insert "if True:")
         (delete-region (point) (line-end-position)))
       (when nomain