Skip to content

Commit

Permalink
Handle triple quotes in Python code when :dir is specified
Browse files Browse the repository at this point in the history
closes #561

* jupyter-python.el (org-babel-jupyter-transform-code): Do it.

* test/jupyter-test.el (org-babel-jupyter-:dir-header-arg): New test.
  • Loading branch information
nnicandro committed Nov 20, 2024
1 parent e966c5d commit 5773717
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
40 changes: 38 additions & 2 deletions jupyter-python.el
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,41 @@ buffer."
(re-search-forward "^[\t ]*File.+line \\([0-9]+\\)$" nil t))
(string-to-number (match-string 1))))

(defun jupyter-python-raw-string (code)
"Construct a Python raw string from CODE.
Return valid Python code that can be interpreted by Python as if
CODE was a raw string in Python."
(mapconcat
(lambda (s)
(let ((begin (if (string-prefix-p "\"" s)
(if (string-prefix-p "\"\"" s)
2
1)
0))
(end (if (string-suffix-p "\"" s)
(if (string-suffix-p "\"\"" s)
-2
-1)
nil)))
(setq s (substring s begin end))
(let ((slashes (when (string-match "\\(\\\\+\\)$" s)
(prog1 (match-string 1 s)
(setq s (substring s 0 (match-beginning 1)))))))
(concat (cond
((= begin 2) "'\"\"' + ")
((= begin 1) "'\"' + ")
(t ""))
"r\"\"\"" s "\"\"\""
(if slashes
(concat " + '" (concat slashes slashes) "'")
"")
(cond
((null end) "")
((= end -2) " + '\"\"'")
((= end -1) " + '\"'"))))))
(split-string code "\"\\{3\\}")
" + '\"\"\"' + "))

(cl-defmethod org-babel-jupyter-transform-code (code changelist &context (jupyter-lang python))
(when (plist-get changelist :dir)
(setq code
Expand All @@ -99,10 +134,11 @@ import os
__JUPY_saved_dir = os.getcwd()
os.chdir(\"%s\")
try:
get_ipython().run_cell(r\"\"\"%s\"\"\")
get_ipython().run_cell(%s)
finally:
os.chdir(__JUPY_saved_dir)"
(plist-get changelist :dir) code)))
(plist-get changelist :dir)
(jupyter-python-raw-string code))))
code)

(provide 'jupyter-python)
Expand Down
15 changes: 14 additions & 1 deletion test/jupyter-test.el
Original file line number Diff line number Diff line change
Expand Up @@ -2879,7 +2879,20 @@ os.path.abspath(os.getcwd())"
;; See #302
(jupyter-org-test-src-block
"print(r\"\\r\")"
": \\r\n"))
": \\r\n")
;; See #561
(jupyter-org-test-src-block
"\"\"\"foo\"\"\""
": foo\n"
:dir dir)
(jupyter-org-test-src-block
"\"test\""
": test\n"
:dir dir))
(jupyter-org-test-src-block
"\"test\\\"\""
": test\"\n"
:dir dir)
(ert-info ("Relative directory")
;; See #302
(let* ((temporary-file-directory jupyter-test-temporary-directory)
Expand Down

0 comments on commit 5773717

Please sign in to comment.