Skip to content

Commit 5773717

Browse files
committed
Handle triple quotes in Python code when :dir is specified
closes #561 * jupyter-python.el (org-babel-jupyter-transform-code): Do it. * test/jupyter-test.el (org-babel-jupyter-:dir-header-arg): New test.
1 parent e966c5d commit 5773717

File tree

2 files changed

+52
-3
lines changed

2 files changed

+52
-3
lines changed

jupyter-python.el

+38-2
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,41 @@ buffer."
9191
(re-search-forward "^[\t ]*File.+line \\([0-9]+\\)$" nil t))
9292
(string-to-number (match-string 1))))
9393

94+
(defun jupyter-python-raw-string (code)
95+
"Construct a Python raw string from CODE.
96+
Return valid Python code that can be interpreted by Python as if
97+
CODE was a raw string in Python."
98+
(mapconcat
99+
(lambda (s)
100+
(let ((begin (if (string-prefix-p "\"" s)
101+
(if (string-prefix-p "\"\"" s)
102+
2
103+
1)
104+
0))
105+
(end (if (string-suffix-p "\"" s)
106+
(if (string-suffix-p "\"\"" s)
107+
-2
108+
-1)
109+
nil)))
110+
(setq s (substring s begin end))
111+
(let ((slashes (when (string-match "\\(\\\\+\\)$" s)
112+
(prog1 (match-string 1 s)
113+
(setq s (substring s 0 (match-beginning 1)))))))
114+
(concat (cond
115+
((= begin 2) "'\"\"' + ")
116+
((= begin 1) "'\"' + ")
117+
(t ""))
118+
"r\"\"\"" s "\"\"\""
119+
(if slashes
120+
(concat " + '" (concat slashes slashes) "'")
121+
"")
122+
(cond
123+
((null end) "")
124+
((= end -2) " + '\"\"'")
125+
((= end -1) " + '\"'"))))))
126+
(split-string code "\"\\{3\\}")
127+
" + '\"\"\"' + "))
128+
94129
(cl-defmethod org-babel-jupyter-transform-code (code changelist &context (jupyter-lang python))
95130
(when (plist-get changelist :dir)
96131
(setq code
@@ -99,10 +134,11 @@ import os
99134
__JUPY_saved_dir = os.getcwd()
100135
os.chdir(\"%s\")
101136
try:
102-
get_ipython().run_cell(r\"\"\"%s\"\"\")
137+
get_ipython().run_cell(%s)
103138
finally:
104139
os.chdir(__JUPY_saved_dir)"
105-
(plist-get changelist :dir) code)))
140+
(plist-get changelist :dir)
141+
(jupyter-python-raw-string code))))
106142
code)
107143

108144
(provide 'jupyter-python)

test/jupyter-test.el

+14-1
Original file line numberDiff line numberDiff line change
@@ -2879,7 +2879,20 @@ os.path.abspath(os.getcwd())"
28792879
;; See #302
28802880
(jupyter-org-test-src-block
28812881
"print(r\"\\r\")"
2882-
": \\r\n"))
2882+
": \\r\n")
2883+
;; See #561
2884+
(jupyter-org-test-src-block
2885+
"\"\"\"foo\"\"\""
2886+
": foo\n"
2887+
:dir dir)
2888+
(jupyter-org-test-src-block
2889+
"\"test\""
2890+
": test\n"
2891+
:dir dir))
2892+
(jupyter-org-test-src-block
2893+
"\"test\\\"\""
2894+
": test\"\n"
2895+
:dir dir)
28832896
(ert-info ("Relative directory")
28842897
;; See #302
28852898
(let* ((temporary-file-directory jupyter-test-temporary-directory)

0 commit comments

Comments
 (0)