Browse Source

ob-python: Insert blank line when sending code to interpreter

* lisp/ob-python.el (org-bable-python-evaluate-session):

Syntax error occurs when evaluating the following code block:

\#+begin_src python :session
if True:
    1
2
\#+end_src

A blank line is required for top level module code to end an indented block, such as a for loop, try/except, or if statement.

https://www.python.org/dev/peps/pep-0008/#blank-line

TINYCHANGE
Gong Qijian 2 years ago
parent
commit
1966d58b25
2 changed files with 29 additions and 1 deletions
  1. 13 1
      lisp/ob-python.el
  2. 16 0
      testing/lisp/test-ob-python.el

+ 13 - 1
lisp/ob-python.el

@@ -308,8 +308,20 @@ last statement in BODY, as elisp."
 	       (list (format "open('%s', 'w').write(str(_))"
 			     (org-babel-process-file-name tmp-file
                                                           'noquote)))))))
+	 (last-indent 0)
 	 (input-body (lambda (body)
-		       (mapc (lambda (line) (insert line) (funcall send-wait))
+		       (mapc (lambda (line)
+			       ;; Insert a blank line to end an indent block.
+			       (let ((curr-indent (string-match "[^\s]" line)))
+				 (if curr-indent
+				     (progn
+				       (when (< curr-indent last-indent)
+					 (insert "")
+					 (funcall send-wait))
+				       (setq last-indent curr-indent))
+				   (setq last-indent 0)))
+			       (insert line)
+			       (funcall send-wait))
 			     (split-string body "[\r\n]"))
 		       (funcall send-wait)))
          (results

+ 16 - 0
testing/lisp/test-ob-python.el

@@ -118,6 +118,22 @@ return x
    (org-babel-next-src-block)
    (should (equal "20" (org-babel-execute-src-block)))))
 
+(ert-deftest test-ob-python/insert-necessary-blank-line-when-sending-code-to-interpreter ()
+  (org-test-with-temp-text "#+begin_src python :session :results value
+if True:
+    1
+2
+#+end_src"
+    ;; Previously, while adding `:session' to a normal code block, also need to add extra blank lines
+    ;; to end indent block or indicate logical sections. Now, the `org-babel-python-evaluate-session'
+    ;; can do it automatically:
+    ;; >>> if True:
+    ;; >>>     1
+    ;; >>> <insert_blank_line_here>
+    ;; >>> 2
+    (org-babel-execute-maybe)
+    (should (equal 2 (org-babel-execute-src-block)))))
+
 (provide 'test-ob-python)
 
 ;;; test-ob-python.el ends here