From 28f271314f7bff7c54696defe8e451da69cd2d6c Mon Sep 17 00:00:00 2001 From: Kyle Meyer Date: Fri, 13 Mar 2015 02:45:04 -0400 Subject: [PATCH 1/2] ob-python.el: Allow indented code in sessions * lisp/ob-python.el (org-babel-python-evaluate-session): Recognize indented code in session and treat it differently to avoid syntax errors. For session blocks with results set to 'output', go through an intermediate file when there is indented code to prevent indentation-related errors when sending code to the Python shell. For session blocks with results set to 'value', issue an user-error. These (usually) would have resulted in a syntax error in the shell anyway, and the '_' variable can't be used to get the last value here (as it is for non-indented code) because it isn't set when executing the code through a file. --- lisp/ob-python.el | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lisp/ob-python.el b/lisp/ob-python.el index dd3cc66..8c51679 100644 --- a/lisp/ob-python.el +++ b/lisp/ob-python.el @@ -238,6 +238,14 @@ (defconst org-babel-python-pp-wrapper-method open('%s', 'w').write( pprint.pformat(main()) )") +(defconst org-babel-python-indented-lines-session-method + (concat "fname= '%s'; fh = open(fname); " + "exec(compile(fh.read(), fname, 'exec')); " + "fh.close()") + "Single line to execute indented Python code in session. +%s will be formatted with the file name of the file containing + the code.") + (defun org-babel-python-evaluate (session body &optional result-type result-params preamble) "Evaluate BODY as Python code." @@ -303,6 +311,13 @@ (defun org-babel-python-evaluate-session (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 + (let ((tmp-file (org-babel-temp-file "python-"))) + (with-temp-file tmp-file (insert body)) + (format org-babel-python-indented-lines-session-method + tmp-file)) + body)) (results (case result-type (output @@ -317,6 +332,8 @@ (defun org-babel-python-evaluate-session (funcall send-wait)) 2) "\n")) (value + (when indented-p + (user-error "Value output limited to unindented lines with session")) (let ((tmp-file (org-babel-temp-file "python-"))) (org-babel-comint-with-output (session org-babel-python-eoe-indicator nil body) @@ -339,6 +356,13 @@ (defun org-babel-python-read-string (string) (match-string 1 string) string)) +(defun org-babel-python--indented-p (input) + "Return true if any line in INPUT is indented." + (with-temp-buffer + (insert input) + (goto-char (point-min)) + (re-search-forward "^\\s-" nil t))) + (provide 'ob-python) -- 2.3.1