@@ -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()
100135os.chdir(\" %s \" )
101136try:
102- get_ipython().run_cell(r \"\"\" %s \"\"\" )
137+ get_ipython().run_cell(%s )
103138finally:
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 )
0 commit comments