From 88ad28dce8e0111c10ca18db5f58d35924112441 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=B0=2E=20G=C3=B6ktu=C4=9F=20Kayaalp?= Date: Thu, 7 May 2020 03:11:50 +0300 Subject: [PATCH] lisp/ob-python.el: remove spurious indentation before evaluation --- lisp/ob-python.el | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/lisp/ob-python.el b/lisp/ob-python.el index dbcfac08d..42bb47f73 100644 --- a/lisp/ob-python.el +++ b/lisp/ob-python.el @@ -69,6 +69,24 @@ This will typically be either `python' or `python-mode'." :package-version '(Org . "8.0") :type 'symbol) +(defun org-babel-python--clean-spurious-indentation (body) + (let* ((extra-indentation + (save-match-data + (string-match "\\`\\([ \t]+\\)" body) + (match-string 1 body))) + (xlen (length extra-indentation))) + (if (zerop xlen) + body + (mapconcat + (lambda (line) (if (<= (length line) xlen) + line + (if (string= extra-indentation + (substring line 0 xlen)) + (substring line xlen) + line))) + (split-string body "\n") + "\n")))) + (defun org-babel-execute:python (body params) "Execute a block of Python code with Babel. This function is called by `org-babel-execute-src-block'." @@ -84,7 +102,8 @@ This function is called by `org-babel-execute-src-block'." (preamble (cdr (assq :preamble params))) (full-body (org-babel-expand-body:generic - (concat body (if return-val (format "\nreturn %s" return-val) "")) + (concat (org-babel-python--clean-spurious-indentation body) + (if return-val (format "\nreturn %s" return-val) "")) params (org-babel-variable-assignments:python params))) (result (org-babel-python-evaluate session full-body result-type result-params preamble))) -- 2.17.1