I adapted your old patch to the current master branch. I also extended it to work for ":results value" (the original patch only worked for ":results output"). I did this by not writing the last line of the code block to the tmpfile, unless it is indented.
I've never contributed before so would appreciate any comments on this patch, and how to get it accepted. Cheers, Jack.
From a5d553ece9f6ee35cd1e273e554a21a19e80ec3c Mon Sep 17 00:00:00 2001
Date: Sat, 18 Nov 2017 21:47:09 +0000
Subject: [PATCH] fix newline/indentation issues in ob-python :session
---
lisp/ob-python.el | 33 +++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/lisp/ob-python.el b/lisp/ob-python.el
index 60ec5fa47..6623ef5fc 100644
--- a/lisp/ob-python.el
+++ b/lisp/ob-python.el
@@ -303,6 +303,10 @@ last statement in BODY, as elisp."
(mapc (lambda (line) (insert line) (funcall send-wait))
(split-string body "[\r\n]"))
(funcall send-wait)))
+ (indented-p (org-babel-python--indented-p body))
+ (body (if indented-p
+ (org-babel-python--replace-body-tmpfile body)
+ body))
(results
(pcase result-type
(`output
@@ -340,6 +344,35 @@ last statement in BODY, as elisp."
(substring string 1 -1)
string))
+
+(defun org-babel-python--indented-p (input)
+ "Non-nil if any line in INPUT is indented."
+ (string-match-p "^[ \t]" input))
+
+(defun org-babel-python--replace-body-tmpfile (body)
+ "Place body in tmpfile, and return string to exec the tmpfile.
+If last line of body is not indented, place it at end of exec string
+instead of tmpfile, so shell can see the result"
+ (let* ((tmp-file (org-babel-temp-file "python-"))
+ (lines (split-string body "\n" t))
+ (lastline (car (last lines)))
+ (newbody (concat
+ (format "__pyfilename = '%s'; " tmp-file)
+ "__pyfile = open(__pyfilename); "
+ "exec(compile("
+ "__pyfile.read(), __pyfilename, 'exec'"
+ ")); "
+ "__pyfile.close()")))
+ (if (string-match-p "^[ \t]" lastline)
+ (progn
+ (with-temp-file tmp-file (insert body))
+ newbody)
+ (with-temp-file tmp-file
+ (insert (mapconcat 'identity
+ (butlast lines) "\n")))
+ (concat newbody "\n" lastline)))
+ )
+
(provide 'ob-python)
--
2.15.0