ob.el 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.01trans
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; See the online documentation for more information
  20. ;;
  21. ;; http://orgmode.org/worg/org-contrib/babel/
  22. ;;; Code:
  23. (eval-when-compile (require 'cl))
  24. (require 'org-macs)
  25. (defvar org-babel-call-process-region-original)
  26. (declare-function show-all "outline" ())
  27. (declare-function tramp-compat-make-temp-file "tramp" (filename &optional dir-flag))
  28. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  29. (declare-function tramp-file-name-user "tramp" (vec))
  30. (declare-function tramp-file-name-host "tramp" (vec))
  31. (declare-function org-icompleting-read "org" (&rest args))
  32. (declare-function org-edit-src-code "org" (context code edit-buffer-name))
  33. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  34. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  35. (declare-function org-narrow-to-subtree "org" ())
  36. (declare-function org-entry-get "org" (pom property &optional inherit))
  37. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  38. (declare-function org-match-string-no-properties "org" (num &optional string))
  39. (declare-function org-do-remove-indentation "org" (&optional n))
  40. (declare-function org-show-context "org" (&optional key))
  41. (declare-function org-at-table-p "org" (&optional table-type))
  42. (declare-function org-cycle "org" (&optional arg))
  43. (declare-function org-uniquify "org" (list))
  44. (declare-function org-table-import "org" (file arg))
  45. (declare-function org-add-hook "org-compat" (hook function &optional append local))
  46. (declare-function org-table-align "org-table" ())
  47. (declare-function org-table-end "org-table" (&optional table-type))
  48. (declare-function orgtbl-to-generic "org-table" (table params))
  49. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  50. (declare-function org-babel-lob-get-info "ob-lob" nil)
  51. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  52. (declare-function org-babel-ref-variables "ob-ref" (params))
  53. (declare-function org-babel-ref-resolve-reference "ob-ref" (ref &optional params))
  54. (declare-function org-babel-lob-execute-maybe "ob-lob" ())
  55. (defgroup org-babel nil
  56. "Code block evaluation and management in `org-mode' documents."
  57. :tag "Babel"
  58. :group 'org)
  59. (defcustom org-confirm-babel-evaluate t
  60. "Confirm before evaluation.
  61. Require confirmation before interactively evaluating code
  62. blocks in Org-mode buffers. The default value of this variable
  63. is t, meaning confirmation is required for any code block
  64. evaluation. This variable can be set to nil to inhibit any
  65. future confirmation requests. This variable can also be set to a
  66. function which takes two arguments the language of the code block
  67. and the body of the code block. Such a function should then
  68. return a non-nil value if the user should be prompted for
  69. execution or nil if no prompt is required.
  70. Warning: Disabling confirmation may result in accidental
  71. evaluation of potentially harmful code. It may be advisable
  72. remove code block execution from C-c C-c as further protection
  73. against accidental code block evaluation. The
  74. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  75. remove code block execution from the C-c C-c keybinding."
  76. :group 'org-babel
  77. :type '(choice boolean function))
  78. ;; don't allow this variable to be changed through file settings
  79. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  80. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  81. "Remove code block evaluation from the C-c C-c key binding."
  82. :group 'org-babel
  83. :type 'boolean)
  84. (defvar org-babel-src-name-regexp
  85. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  86. "Regular expression used to match a source name line.")
  87. (defvar org-babel-src-name-w-name-regexp
  88. (concat org-babel-src-name-regexp
  89. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  90. "Regular expression matching source name lines with a name.")
  91. (defvar org-babel-src-block-regexp
  92. (concat
  93. ;; (1) indentation (2) lang
  94. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  95. ;; (3) switches
  96. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  97. ;; (4) header arguments
  98. "\\([^\n]*\\)\n"
  99. ;; (5) body
  100. "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
  101. "Regexp used to identify code blocks.")
  102. (defvar org-babel-inline-src-block-regexp
  103. (concat
  104. ;; (1) replacement target (2) lang
  105. "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
  106. ;; (3,4) (unused, headers)
  107. "\\(\\|\\[\\(.*?\\)\\]\\)"
  108. ;; (5) body
  109. "{\\([^\f\n\r\v]+?\\)}\\)")
  110. "Regexp used to identify inline src-blocks.")
  111. (defun org-babel-get-src-block-info (&optional header-vars-only)
  112. "Get information on the current source block.
  113. Returns a list
  114. (language body header-arguments-alist switches name function-args indent).
  115. Unless HEADER-VARS-ONLY is non-nil, any variable
  116. references provided in 'function call style' (i.e. in a
  117. parenthesised argument list following the src block name) are
  118. added to the header-arguments-alist."
  119. (let ((case-fold-search t) head info args indent)
  120. (if (setq head (org-babel-where-is-src-block-head))
  121. (save-excursion
  122. (goto-char head)
  123. (setq info (org-babel-parse-src-block-match))
  124. (setq indent (car (last info)))
  125. (setq info (butlast info))
  126. (forward-line -1)
  127. (if (and (looking-at org-babel-src-name-w-name-regexp)
  128. (match-string 2))
  129. (progn
  130. (setq info (append info (list (org-babel-clean-text-properties
  131. (match-string 2)))))
  132. ;; Note that e.g. "name()" and "name( )" result in
  133. ;; ((:var . "")). We maintain that behaviour, and the
  134. ;; resulting non-nil sixth element is relied upon in
  135. ;; org-babel-exp-code to detect a functional-style
  136. ;; block in those cases. However, "name" without any
  137. ;; parentheses would result in the same thing, so we
  138. ;; explicitly avoid that.
  139. (if (setq args (match-string 4))
  140. (setq info
  141. (append info (list
  142. (mapcar
  143. (lambda (ref) (cons :var ref))
  144. (org-babel-ref-split-args args))))))
  145. (unless header-vars-only
  146. (setf (nth 2 info)
  147. (org-babel-merge-params (nth 5 info) (nth 2 info)))))
  148. (setq info (append info (list nil nil))))
  149. (append info (list indent)))
  150. (if (save-excursion ;; inline source block
  151. (re-search-backward "[ \f\t\n\r\v]" nil t)
  152. (looking-at org-babel-inline-src-block-regexp))
  153. (org-babel-parse-inline-src-block-match)
  154. nil))))
  155. (defun org-babel-confirm-evaluate (info)
  156. "Confirm evaluation of the code block INFO.
  157. This behavior can be suppressed by setting the value of
  158. `org-confirm-babel-evaluate' to nil, in which case all future
  159. interactive code block evaluations will proceed without any
  160. confirmation from the user.
  161. Note disabling confirmation may result in accidental evaluation
  162. of potentially harmful code."
  163. (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
  164. (when (assoc :noeval (nth 2 info)) "no")))
  165. (query (or (equal eval "query")
  166. (and (functionp org-confirm-babel-evaluate)
  167. (funcall org-confirm-babel-evaluate
  168. (nth 0 info) (nth 1 info)))
  169. org-confirm-babel-evaluate)))
  170. (if (or (equal eval "never") (equal eval "no")
  171. (and query
  172. (not (yes-or-no-p
  173. (format "Evaluate this%scode on your system? "
  174. (if info (format " %s " (nth 0 info)) " "))))))
  175. (prog1 nil (message "evaluation aborted"))
  176. t)))
  177. ;;;###autoload
  178. (defun org-babel-execute-safely-maybe ()
  179. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  180. (org-babel-execute-maybe)))
  181. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
  182. ;;;###autoload
  183. (defun org-babel-execute-maybe ()
  184. (interactive)
  185. (or (org-babel-execute-src-block-maybe)
  186. (org-babel-lob-execute-maybe)))
  187. (defun org-babel-execute-src-block-maybe ()
  188. "Conditionally execute a source block.
  189. Detect if this is context for a Babel src-block and if so
  190. then run `org-babel-execute-src-block'."
  191. (interactive)
  192. (let ((info (org-babel-get-src-block-info)))
  193. (if info
  194. (progn (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  195. ;;;###autoload
  196. (defun org-babel-expand-src-block-maybe ()
  197. "Conditionally expand a source block.
  198. Detect if this is context for a org-babel src-block and if so
  199. then run `org-babel-expand-src-block'."
  200. (interactive)
  201. (let ((info (org-babel-get-src-block-info)))
  202. (if info
  203. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  204. nil)))
  205. ;;;###autoload
  206. (defun org-babel-load-in-session-maybe ()
  207. "Conditionally load a source block in a session.
  208. Detect if this is context for a org-babel src-block and if so
  209. then run `org-babel-load-in-session'."
  210. (interactive)
  211. (let ((info (org-babel-get-src-block-info)))
  212. (if info
  213. (progn (org-babel-load-in-session current-prefix-arg info) t)
  214. nil)))
  215. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  216. ;;;###autoload
  217. (defun org-babel-pop-to-session-maybe ()
  218. "Conditionally pop to a session.
  219. Detect if this is context for a org-babel src-block and if so
  220. then run `org-babel-pop-to-session'."
  221. (interactive)
  222. (let ((info (org-babel-get-src-block-info)))
  223. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  224. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  225. (defconst org-babel-header-arg-names
  226. '(cache cmdline colnames dir exports file noweb results
  227. session tangle var eval noeval comments)
  228. "Common header arguments used by org-babel.
  229. Note that individual languages may define their own language
  230. specific header arguments as well.")
  231. (defvar org-babel-default-header-args
  232. '((:session . "none") (:results . "replace") (:exports . "code")
  233. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  234. "Default arguments to use when evaluating a source block.")
  235. (defvar org-babel-default-inline-header-args
  236. '((:session . "none") (:results . "silent") (:exports . "results"))
  237. "Default arguments to use when evaluating an inline source block.")
  238. (defvar org-babel-current-buffer-properties)
  239. (make-variable-buffer-local 'org-babel-current-buffer-properties)
  240. (defvar org-babel-result-regexp
  241. "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
  242. "Regular expression used to match result lines.
  243. If the results are associated with a hash key then the hash will
  244. be saved in the second match data.")
  245. (defvar org-babel-result-w-name-regexp
  246. (concat org-babel-result-regexp
  247. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  248. (defvar org-babel-min-lines-for-block-output 10
  249. "The minimum number of lines for block output.
  250. If number of lines of output is equal to or exceeds this
  251. value, the output is placed in a #+begin_example...#+end_example
  252. block. Otherwise the output is marked as literal by inserting
  253. colons at the starts of the lines. This variable only takes
  254. effect if the :results output option is in effect.")
  255. (defvar org-babel-noweb-error-langs nil
  256. "Languages for which Babel will raise literate programming errors.
  257. List of languages for which errors should be raised when the
  258. source code block satisfying a noweb reference in this language
  259. can not be resolved.")
  260. (defvar org-babel-hash-show 4
  261. "Number of initial characters to show of a hidden results hash.")
  262. (defvar org-babel-after-execute-hook nil
  263. "Hook for functions to be called after `org-babel-execute-src-block'")
  264. (defun org-babel-named-src-block-regexp-for-name (name)
  265. "This generates a regexp used to match a src block named NAME."
  266. (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
  267. (substring org-babel-src-block-regexp 1)))
  268. ;;; functions
  269. (defvar call-process-region)
  270. ;;;###autoload
  271. (defun org-babel-execute-src-block (&optional arg info params)
  272. "Execute the current source code block.
  273. Insert the results of execution into the buffer. Source code
  274. execution and the collection and formatting of results can be
  275. controlled through a variety of header arguments.
  276. Optionally supply a value for INFO in the form returned by
  277. `org-babel-get-src-block-info'.
  278. Optionally supply a value for PARAMS which will be merged with
  279. the header arguments specified at the front of the source code
  280. block."
  281. (interactive)
  282. (let ((info (or info (org-babel-get-src-block-info))))
  283. (when (org-babel-confirm-evaluate info)
  284. (let* ((lang (nth 0 info))
  285. (params (setf
  286. (nth 2 info)
  287. (sort (org-babel-merge-params (nth 2 info) params)
  288. (lambda (el1 el2) (string< (symbol-name (car el1))
  289. (symbol-name (car el2)))))))
  290. (new-hash
  291. (if (and (cdr (assoc :cache params))
  292. (string= "yes" (cdr (assoc :cache params))))
  293. (org-babel-sha1-hash info)))
  294. (old-hash (org-babel-result-hash info))
  295. (body (setf (nth 1 info)
  296. (if (and (cdr (assoc :noweb params))
  297. (string= "yes" (cdr (assoc :noweb params))))
  298. (org-babel-expand-noweb-references info)
  299. (nth 1 info))))
  300. (result-params (split-string (or (cdr (assoc :results params)) "")))
  301. (result-type (cond ((member "output" result-params) 'output)
  302. ((member "value" result-params) 'value)
  303. (t 'value)))
  304. (cmd (intern (concat "org-babel-execute:" lang)))
  305. (dir (cdr (assoc :dir params)))
  306. (default-directory
  307. (or (and dir (file-name-as-directory dir)) default-directory))
  308. (org-babel-call-process-region-original
  309. (if (boundp 'org-babel-call-process-region-original)
  310. org-babel-call-process-region-original
  311. (symbol-function 'call-process-region)))
  312. (indent (car (last info)))
  313. result)
  314. (unwind-protect
  315. (flet ((call-process-region (&rest args)
  316. (apply 'org-babel-tramp-handle-call-process-region args)))
  317. (unless (fboundp cmd)
  318. (error "No org-babel-execute function for %s!" lang))
  319. (if (and (not arg) new-hash (equal new-hash old-hash))
  320. (save-excursion ;; return cached result
  321. (goto-char (org-babel-where-is-src-block-result nil info))
  322. (end-of-line 1) (forward-char 1)
  323. (setq result (org-babel-read-result))
  324. (message (replace-regexp-in-string
  325. "%" "%%" (format "%S" result))) result)
  326. (message "executing %s code block%s..."
  327. (capitalize lang)
  328. (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
  329. (setq result (funcall cmd body params))
  330. (if (eq result-type 'value)
  331. (setq result (if (and (or (member "vector" result-params)
  332. (member "table" result-params))
  333. (not (listp result)))
  334. (list (list result))
  335. result)))
  336. (org-babel-insert-result
  337. result result-params info new-hash indent lang)
  338. (run-hooks 'org-babel-after-execute-hook)
  339. result))
  340. (setq call-process-region 'org-babel-call-process-region-original))))))
  341. (defun org-babel-expand-body:generic (body params &optional processed-params)
  342. "Expand BODY with PARAMS.
  343. Expand a block of code with org-babel according to it's header
  344. arguments. This generic implementation of body expansion is
  345. called for languages which have not defined their own specific
  346. org-babel-expand-body:lang function." body)
  347. ;;;###autoload
  348. (defun org-babel-expand-src-block (&optional arg info params)
  349. "Expand the current source code block.
  350. Expand according to the source code block's header
  351. arguments and pop open the results in a preview buffer."
  352. (interactive)
  353. (let* ((info (or info (org-babel-get-src-block-info)))
  354. (lang (nth 0 info))
  355. (params (setf (nth 2 info)
  356. (sort (org-babel-merge-params (nth 2 info) params)
  357. (lambda (el1 el2) (string< (symbol-name (car el1))
  358. (symbol-name (car el2)))))))
  359. (body (setf (nth 1 info)
  360. (if (and (cdr (assoc :noweb params))
  361. (string= "yes" (cdr (assoc :noweb params))))
  362. (org-babel-expand-noweb-references info) (nth 1 info))))
  363. (cmd (intern (concat "org-babel-expand-body:" lang)))
  364. (expanded (funcall (if (fboundp cmd) cmd 'org-babel-expand-body:generic)
  365. body params)))
  366. (org-edit-src-code
  367. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  368. ;;;###autoload
  369. (defun org-babel-load-in-session (&optional arg info)
  370. "Load the body of the current source-code block.
  371. Evaluate the header arguments for the source block before
  372. entering the session. After loading the body this pops open the
  373. session."
  374. (interactive)
  375. (let* ((info (or info (org-babel-get-src-block-info)))
  376. (lang (nth 0 info))
  377. (params (nth 2 info))
  378. (body (setf (nth 1 info)
  379. (if (and (cdr (assoc :noweb params))
  380. (string= "yes" (cdr (assoc :noweb params))))
  381. (org-babel-expand-noweb-references info)
  382. (nth 1 info))))
  383. (session (cdr (assoc :session params)))
  384. (dir (cdr (assoc :dir params)))
  385. (default-directory
  386. (or (and dir (file-name-as-directory dir)) default-directory))
  387. (cmd (intern (concat "org-babel-load-session:" lang))))
  388. (unless (fboundp cmd)
  389. (error "No org-babel-load-session function for %s!" lang))
  390. (pop-to-buffer (funcall cmd session body params))
  391. (end-of-line 1)))
  392. ;;;###autoload
  393. (defun org-babel-initiate-session (&optional arg info)
  394. "Initiate session for current code block.
  395. If called with a prefix argument then evaluate the header arguments
  396. for the code block before entering the session. Copy the body
  397. of the code block to the kill ring."
  398. (interactive "P")
  399. (let* ((info (or info (org-babel-get-src-block-info)))
  400. (lang (nth 0 info))
  401. (body (nth 1 info))
  402. (params (nth 2 info))
  403. (session (cdr (assoc :session params)))
  404. (dir (cdr (assoc :dir params)))
  405. (default-directory
  406. (or (and dir (file-name-as-directory dir)) default-directory))
  407. (cmd (intern (format "org-babel-%s-initiate-session" lang)))
  408. (cmd2 (intern (concat "org-babel-prep-session:" lang))))
  409. (if (and (stringp session) (string= session "none"))
  410. (error "This block is not using a session!"))
  411. (unless (fboundp cmd)
  412. (error "No org-babel-initiate-session function for %s!" lang))
  413. (with-temp-buffer (insert (org-babel-trim body))
  414. (copy-region-as-kill (point-min) (point-max)))
  415. (when arg
  416. (unless (fboundp cmd2)
  417. (error "No org-babel-prep-session function for %s!" lang))
  418. (funcall cmd2 session params))
  419. (funcall cmd session params)))
  420. ;;;###autoload
  421. (defun org-babel-switch-to-session (&optional arg info)
  422. "Switch to the session of the current code block.
  423. Uses `org-babel-initiate-session' to start the session. If called
  424. with a prefix argument then this is passed on to
  425. `org-babel-initiate-session'."
  426. (interactive "P")
  427. (pop-to-buffer (org-babel-initiate-session arg info))
  428. (end-of-line 1))
  429. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  430. ;;;###autoload
  431. (defun org-babel-switch-to-session-with-code (&optional arg info)
  432. "Switch to code buffer and display session."
  433. (interactive "P")
  434. (flet ((swap-windows
  435. ()
  436. (let ((other-window-buffer (window-buffer (next-window))))
  437. (set-window-buffer (next-window) (current-buffer))
  438. (set-window-buffer (selected-window) other-window-buffer))
  439. (other-window 1)))
  440. (let ((info (org-babel-get-src-block-info))
  441. (org-src-window-setup 'reorganize-frame))
  442. (save-excursion
  443. (org-babel-switch-to-session arg info))
  444. (org-edit-src-code))
  445. (swap-windows)))
  446. (defmacro org-babel-do-in-edit-buffer (&rest body)
  447. "Evaluate BODY in edit buffer if there is a code block at point.
  448. Return t if a code block was found at point, nil otherwise."
  449. `(let ((org-src-window-setup 'switch-invisibly))
  450. (when (org-edit-src-code nil nil nil 'quietly)
  451. ,@body
  452. (if (org-bound-and-true-p org-edit-src-from-org-mode)
  453. (org-edit-src-exit))
  454. t)))
  455. (defun org-babel-do-key-sequence-in-edit-buffer (key)
  456. "Read key sequence and execute the command in edit buffer.
  457. Enter a key sequence to be executed in the language major-mode
  458. edit buffer. For example, TAB will alter the contents of the
  459. Org-mode code block according to the effect of TAB in the
  460. language major-mode buffer. For languages that support
  461. interactive sessions, this can be used to send code from the Org
  462. buffer to the session for evaluation using the native major-mode
  463. evaluation mechanisms."
  464. (interactive "kEnter key-sequence to execute in edit buffer: ")
  465. (org-babel-do-in-edit-buffer
  466. (call-interactively
  467. (key-binding (or key (read-key-sequence nil))))))
  468. (defvar org-bracket-link-regexp)
  469. ;;;###autoload
  470. (defun org-babel-open-src-block-result (&optional re-run)
  471. "If `point' is on a src block then open the results of the
  472. source code block, otherwise return nil. With optional prefix
  473. argument RE-RUN the source-code block is evaluated even if
  474. results already exist."
  475. (interactive "P")
  476. (when (org-babel-get-src-block-info)
  477. (save-excursion
  478. ;; go to the results, if there aren't any then run the block
  479. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  480. (progn (org-babel-execute-src-block)
  481. (org-babel-where-is-src-block-result))))
  482. (end-of-line 1)
  483. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  484. ;; open the results
  485. (if (looking-at org-bracket-link-regexp)
  486. ;; file results
  487. (org-open-at-point)
  488. (let ((results (org-babel-read-result)))
  489. (flet ((echo-res (result)
  490. (if (stringp result) result (format "%S" result))))
  491. (pop-to-buffer (get-buffer-create "org-babel-results"))
  492. (delete-region (point-min) (point-max))
  493. (if (listp results)
  494. ;; table result
  495. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  496. ;; scalar result
  497. (insert (echo-res results))))))
  498. t)))
  499. ;;;###autoload
  500. (defun org-babel-execute-buffer (&optional arg)
  501. "Execute source code blocks in a buffer.
  502. Call `org-babel-execute-src-block' on every source block in
  503. the current buffer."
  504. (interactive "P")
  505. (save-excursion
  506. (org-save-outline-visibility t
  507. (goto-char (point-min))
  508. (show-all)
  509. (while (re-search-forward org-babel-src-block-regexp nil t)
  510. (let ((pos-end (match-end 0)))
  511. (goto-char (match-beginning 0))
  512. (org-babel-execute-src-block arg)
  513. (goto-char pos-end))))))
  514. ;;;###autoload
  515. (defun org-babel-execute-subtree (&optional arg)
  516. "Execute source code blocks in a subtree.
  517. Call `org-babel-execute-src-block' on every source block in
  518. the current subtree."
  519. (interactive "P")
  520. (save-restriction
  521. (save-excursion
  522. (org-narrow-to-subtree)
  523. (org-babel-execute-buffer)
  524. (widen))))
  525. ;;;###autoload
  526. (defun org-babel-sha1-hash (&optional info)
  527. "Generate an sha1 hash based on the value of info."
  528. (interactive)
  529. (let* ((info (or info (org-babel-get-src-block-info)))
  530. (hash (sha1 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
  531. (nth 2 info) ":")
  532. (nth 1 info)))))
  533. (when (interactive-p) (message hash))
  534. hash))
  535. (defun org-babel-result-hash (&optional info)
  536. "Return the in-buffer hash associated with INFO."
  537. (org-babel-where-is-src-block-result nil info)
  538. (org-babel-clean-text-properties (match-string 3)))
  539. (defun org-babel-hide-hash ()
  540. "Hide the hash in the current results line.
  541. Only the initial `org-babel-hash-show' characters of the hash
  542. will remain visible."
  543. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  544. (save-excursion
  545. (when (and (re-search-forward org-babel-result-regexp nil t)
  546. (match-string 3))
  547. (let* ((start (match-beginning 3))
  548. (hide-start (+ org-babel-hash-show start))
  549. (end (match-end 3))
  550. (hash (match-string 3))
  551. ov1 ov2)
  552. (setq ov1 (make-overlay start hide-start))
  553. (setq ov2 (make-overlay hide-start end))
  554. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  555. (overlay-put ov1 'babel-hash hash)))))
  556. (defun org-babel-hide-all-hashes ()
  557. "Hide the hash in the current buffer.
  558. Only the initial `org-babel-hash-show' characters of each hash
  559. will remain visible. This function should be called as part of
  560. the `org-mode-hook'."
  561. (save-excursion
  562. (while (re-search-forward org-babel-result-regexp nil t)
  563. (goto-char (match-beginning 0))
  564. (org-babel-hide-hash)
  565. (goto-char (match-end 0)))))
  566. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  567. (defun org-babel-hash-at-point (&optional point)
  568. "Return the value of the hash at POINT.
  569. The hash is also added as the last element of the kill ring.
  570. This can be called with C-c C-c."
  571. (interactive)
  572. (let ((hash (car (delq nil (mapcar
  573. (lambda (ol) (overlay-get ol 'babel-hash))
  574. (overlays-at (or point (point))))))))
  575. (when hash (kill-new hash) (message hash))))
  576. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  577. (defun org-babel-result-hide-spec ()
  578. "Hide portions of results lines.
  579. Add `org-babel-hide-result' as an invisibility spec for hiding
  580. portions of results lines."
  581. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  582. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  583. (defvar org-babel-hide-result-overlays nil
  584. "Overlays hiding results.")
  585. (defun org-babel-result-hide-all ()
  586. "Fold all results in the current buffer."
  587. (interactive)
  588. (org-babel-show-result-all)
  589. (save-excursion
  590. (while (re-search-forward org-babel-result-regexp nil t)
  591. (save-excursion (goto-char (match-beginning 0))
  592. (org-babel-hide-result-toggle-maybe)))))
  593. (defun org-babel-show-result-all ()
  594. "Unfold all results in the current buffer."
  595. (mapc 'delete-overlay org-babel-hide-result-overlays)
  596. (setq org-babel-hide-result-overlays nil))
  597. ;;;###autoload
  598. (defun org-babel-hide-result-toggle-maybe ()
  599. "Toggle visibility of result at point."
  600. (interactive)
  601. (let ((case-fold-search t))
  602. (if (save-excursion
  603. (beginning-of-line 1)
  604. (looking-at org-babel-result-regexp))
  605. (progn (org-babel-hide-result-toggle)
  606. t) ;; to signal that we took action
  607. nil))) ;; to signal that we did not
  608. (defun org-babel-hide-result-toggle (&optional force)
  609. "Toggle the visibility of the current result."
  610. (interactive)
  611. (save-excursion
  612. (beginning-of-line)
  613. (if (re-search-forward org-babel-result-regexp nil t)
  614. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  615. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  616. ov)
  617. (if (memq t (mapcar (lambda (overlay)
  618. (eq (overlay-get overlay 'invisible)
  619. 'org-babel-hide-result))
  620. (overlays-at start)))
  621. (if (or (not force) (eq force 'off))
  622. (mapc (lambda (ov)
  623. (when (member ov org-babel-hide-result-overlays)
  624. (setq org-babel-hide-result-overlays
  625. (delq ov org-babel-hide-result-overlays)))
  626. (when (eq (overlay-get ov 'invisible)
  627. 'org-babel-hide-result)
  628. (delete-overlay ov)))
  629. (overlays-at start)))
  630. (setq ov (make-overlay start end))
  631. (overlay-put ov 'invisible 'org-babel-hide-result)
  632. ;; make the block accessible to isearch
  633. (overlay-put
  634. ov 'isearch-open-invisible
  635. (lambda (ov)
  636. (when (member ov org-babel-hide-result-overlays)
  637. (setq org-babel-hide-result-overlays
  638. (delq ov org-babel-hide-result-overlays)))
  639. (when (eq (overlay-get ov 'invisible)
  640. 'org-babel-hide-result)
  641. (delete-overlay ov))))
  642. (push ov org-babel-hide-result-overlays)))
  643. (error "Not looking at a result line"))))
  644. ;; org-tab-after-check-for-cycling-hook
  645. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  646. ;; Remove overlays when changing major mode
  647. (add-hook 'org-mode-hook
  648. (lambda () (org-add-hook 'change-major-mode-hook
  649. 'org-babel-show-result-all 'append 'local)))
  650. (defmacro org-babel-map-src-blocks (file &rest body)
  651. "Evaluate BODY forms on each source-block in FILE."
  652. (declare (indent 1))
  653. `(let ((visited-p (get-file-buffer (expand-file-name ,file)))
  654. to-be-removed)
  655. (save-window-excursion
  656. (find-file ,file)
  657. (setq to-be-removed (current-buffer))
  658. (goto-char (point-min))
  659. (while (re-search-forward org-babel-src-block-regexp nil t)
  660. (goto-char (match-beginning 0))
  661. (save-match-data ,@body)
  662. (goto-char (match-end 0))))
  663. (unless visited-p
  664. (kill-buffer to-be-removed))))
  665. (defvar org-file-properties)
  666. (defun org-babel-params-from-properties (&optional lang)
  667. "Retrieve parameters specified as properties.
  668. Return an association list of any source block params which
  669. may be specified in the properties of the current outline entry."
  670. (save-match-data
  671. (let (val sym)
  672. (delq nil
  673. (mapcar
  674. (lambda (header-arg)
  675. (and (setq val
  676. (or (condition-case nil
  677. (org-entry-get (point) header-arg t)
  678. (error nil))
  679. (cdr (assoc header-arg org-file-properties))))
  680. (cons (intern (concat ":" header-arg)) val)))
  681. (mapcar
  682. 'symbol-name
  683. (append
  684. org-babel-header-arg-names
  685. (progn
  686. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  687. (and (boundp sym) (eval sym))))))))))
  688. (defun org-babel-params-from-buffer ()
  689. "Retrieve per-buffer parameters.
  690. Return an association list of any source block params which
  691. may be specified at the top of the current buffer."
  692. (or org-babel-current-buffer-properties
  693. (setq org-babel-current-buffer-properties
  694. (save-match-data
  695. (save-excursion
  696. (save-restriction
  697. (widen)
  698. (goto-char (point-min))
  699. (when (re-search-forward
  700. (org-make-options-regexp (list "BABEL")) nil t)
  701. (org-babel-parse-header-arguments
  702. (org-match-string-no-properties 2)))))))))
  703. (defvar org-src-preserve-indentation)
  704. (defun org-babel-parse-src-block-match ()
  705. "Parse the results from a match of the `org-babel-src-block-regexp'."
  706. (let* ((block-indentation (length (match-string 1)))
  707. (lang (org-babel-clean-text-properties (match-string 2)))
  708. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  709. (switches (match-string 3))
  710. (body (org-babel-clean-text-properties (match-string 5)))
  711. (preserve-indentation (or org-src-preserve-indentation
  712. (string-match "-i\\>" switches))))
  713. (list lang
  714. ;; get block body less properties, protective commas, and indentation
  715. (with-temp-buffer
  716. (save-match-data
  717. (insert (org-babel-strip-protective-commas body))
  718. (unless preserve-indentation (org-do-remove-indentation))
  719. (buffer-string)))
  720. (org-babel-merge-params
  721. org-babel-default-header-args
  722. (org-babel-params-from-buffer)
  723. (org-babel-params-from-properties lang)
  724. (if (boundp lang-headers) (eval lang-headers) nil)
  725. (org-babel-parse-header-arguments
  726. (org-babel-clean-text-properties (or (match-string 4) ""))))
  727. switches
  728. block-indentation)))
  729. (defun org-babel-parse-inline-src-block-match ()
  730. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  731. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  732. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  733. (list lang
  734. (org-babel-strip-protective-commas
  735. (org-babel-clean-text-properties (match-string 5)))
  736. (org-babel-merge-params
  737. org-babel-default-inline-header-args
  738. (org-babel-params-from-buffer)
  739. (org-babel-params-from-properties lang)
  740. (if (boundp lang-headers) (eval lang-headers) nil)
  741. (org-babel-parse-header-arguments
  742. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  743. (defun org-babel-parse-header-arguments (arg-string)
  744. "Parse a string of header arguments returning an alist."
  745. (if (> (length arg-string) 0)
  746. (delq nil
  747. (mapcar
  748. (lambda (arg)
  749. (if (string-match
  750. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  751. arg)
  752. (cons (intern (concat ":" (match-string 1 arg)))
  753. (let ((raw (org-babel-chomp (match-string 2 arg))))
  754. (if (org-babel-number-p raw)
  755. raw (org-babel-read raw))))
  756. (cons (intern (concat ":" arg)) nil)))
  757. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  758. (defun org-babel-process-params (params)
  759. "Parse params and resolve references.
  760. Return a list (session vars result-params result-type colnames rownames)."
  761. (let* ((session (cdr (assoc :session params)))
  762. (vars-and-names (org-babel-disassemble-tables
  763. (org-babel-ref-variables params)
  764. (cdr (assoc :hlines params))
  765. (cdr (assoc :colnames params))
  766. (cdr (assoc :rownames params))))
  767. (vars (car vars-and-names))
  768. (colnames (cadr vars-and-names))
  769. (rownames (caddr vars-and-names))
  770. (result-params (split-string (or (cdr (assoc :results params)) "")))
  771. (result-type (cond ((member "output" result-params) 'output)
  772. ((member "value" result-params) 'value)
  773. (t 'value))))
  774. (list session vars result-params result-type colnames rownames)))
  775. ;; row and column names
  776. (defun org-babel-del-hlines (table)
  777. "Remove all 'hlines from TABLE."
  778. (remove 'hline table))
  779. (defun org-babel-get-colnames (table)
  780. "Return the column names of TABLE.
  781. Return a cons cell, the `car' of which contains the TABLE less
  782. colnames, and the `cdr' of which contains a list of the column
  783. names."
  784. (if (equal 'hline (nth 1 table))
  785. (cons (cddr table) (car table))
  786. (cons (cdr table) (car table))))
  787. (defun org-babel-get-rownames (table)
  788. "Return the row names of TABLE.
  789. Return a cons cell, the `car' of which contains the TABLE less
  790. colnames, and the `cdr' of which contains a list of the column
  791. names. Note: this function removes any hlines in TABLE."
  792. (flet ((trans (table) (apply #'mapcar* #'list table)))
  793. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  794. (table (trans (mapcar (lambda (row)
  795. (if (not (equal row 'hline))
  796. row
  797. (setq row '())
  798. (dotimes (n width) (setq row (cons 'hline row)))
  799. row))
  800. table))))
  801. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  802. (trans (cdr table)))
  803. (remove 'hline (car table))))))
  804. (defun org-babel-put-colnames (table colnames)
  805. "Add COLNAMES to TABLE if they exist."
  806. (if colnames (apply 'list colnames 'hline table) table))
  807. (defun org-babel-put-rownames (table rownames)
  808. "Add ROWNAMES to TABLE if they exist."
  809. (if rownames
  810. (mapcar (lambda (row)
  811. (if (listp row)
  812. (cons (or (pop rownames) "") row)
  813. row)) table)
  814. table))
  815. (defun org-babel-pick-name (names selector)
  816. "Select one out of an alist of row or column names.
  817. SELECTOR can be either a list of names in which case those names
  818. will be returned directly, or an index into the list NAMES in
  819. which case the indexed names will be return."
  820. (if (listp selector)
  821. selector
  822. (when names
  823. (if (and selector (symbolp selector) (not (equal t selector)))
  824. (cdr (assoc selector names))
  825. (if (integerp selector)
  826. (nth (- selector 1) names)
  827. (cdr (car (last names))))))))
  828. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  829. "Parse tables for further processing.
  830. Process the variables in VARS according to the HLINES,
  831. ROWNAMES and COLNAMES header arguments. Return a list consisting
  832. of the vars, cnames and rnames."
  833. (let (cnames rnames)
  834. (list
  835. (mapcar
  836. (lambda (var)
  837. (when (listp (cdr var))
  838. (when (and (not (equal colnames "no"))
  839. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  840. (not (member 'hline (cddr (cdr var)))))))
  841. (let ((both (org-babel-get-colnames (cdr var))))
  842. (setq cnames (cons (cons (car var) (cdr both))
  843. cnames))
  844. (setq var (cons (car var) (car both)))))
  845. (when (and rownames (not (equal rownames "no")))
  846. (let ((both (org-babel-get-rownames (cdr var))))
  847. (setq rnames (cons (cons (car var) (cdr both))
  848. rnames))
  849. (setq var (cons (car var) (car both)))))
  850. (when (and hlines (not (equal hlines "yes")))
  851. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  852. var)
  853. vars)
  854. cnames rnames)))
  855. (defun org-babel-reassemble-table (table colnames rownames)
  856. "Add column and row names to a table.
  857. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  858. to the table for reinsertion to org-mode."
  859. (if (listp table)
  860. ((lambda (table)
  861. (if (and colnames (listp (car table)) (= (length (car table))
  862. (length colnames)))
  863. (org-babel-put-colnames table colnames) table))
  864. (if (and rownames (= (length table) (length rownames)))
  865. (org-babel-put-rownames table rownames) table))
  866. table))
  867. (defun org-babel-where-is-src-block-head ()
  868. "Find where the current source block begins.
  869. Return the point at the beginning of the current source
  870. block. Specifically at the beginning of the #+BEGIN_SRC line.
  871. If the point is not on a source block then return nil."
  872. (let ((initial (point)) top bottom)
  873. (or
  874. (save-excursion ;; on a source name line
  875. (beginning-of-line 1)
  876. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  877. (looking-at org-babel-src-block-regexp)
  878. (point)))
  879. (save-excursion ;; on a #+begin_src line
  880. (beginning-of-line 1)
  881. (and (looking-at org-babel-src-block-regexp)
  882. (point)))
  883. (save-excursion ;; inside a src block
  884. (and
  885. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  886. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  887. (< top initial) (< initial bottom)
  888. (progn (goto-char top) (beginning-of-line 1)
  889. (looking-at org-babel-src-block-regexp))
  890. (point))))))
  891. ;;;###autoload
  892. (defun org-babel-goto-named-src-block (name)
  893. "Go to a named source-code block."
  894. (interactive
  895. (let ((completion-ignore-case t))
  896. (list (org-icompleting-read "source-block name: "
  897. (org-babel-src-block-names) nil t))))
  898. (let ((point (org-babel-find-named-block name)))
  899. (if point
  900. ;; taken from `org-open-at-point'
  901. (progn (goto-char point) (org-show-context))
  902. (message "source-code block '%s' not found in this buffer" name))))
  903. (defun org-babel-find-named-block (name)
  904. "Find a named source-code block.
  905. Return the location of the source block identified by source
  906. NAME, or nil if no such block exists. Set match data according to
  907. org-babel-named-src-block-regexp."
  908. (save-excursion
  909. (let ((case-fold-search t)
  910. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  911. (goto-char (point-min))
  912. (when (or (re-search-forward regexp nil t)
  913. (re-search-backward regexp nil t))
  914. (match-beginning 0)))))
  915. (defun org-babel-src-block-names (&optional file)
  916. "Returns the names of source blocks in FILE or the current buffer."
  917. (save-excursion
  918. (when file (find-file file)) (goto-char (point-min))
  919. (let (names)
  920. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  921. (setq names (cons (org-babel-clean-text-properties (match-string 2))
  922. names)))
  923. names)))
  924. ;;;###autoload
  925. (defun org-babel-goto-named-result (name)
  926. "Go to a named result."
  927. (interactive
  928. (let ((completion-ignore-case t))
  929. (list (org-icompleting-read "source-block name: "
  930. (org-babel-result-names) nil t))))
  931. (let ((point (org-babel-find-named-result name)))
  932. (if point
  933. ;; taken from `org-open-at-point'
  934. (progn (goto-char point) (org-show-context))
  935. (message "result '%s' not found in this buffer" name))))
  936. (defun org-babel-find-named-result (name)
  937. "Find a named result.
  938. Return the location of the result named NAME in the current
  939. buffer or nil if no such result exists."
  940. (save-excursion
  941. (goto-char (point-min))
  942. (when (re-search-forward
  943. (concat org-babel-result-regexp
  944. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  945. (beginning-of-line 0) (point))))
  946. (defun org-babel-result-names (&optional file)
  947. "Returns the names of results in FILE or the current buffer."
  948. (save-excursion
  949. (when file (find-file file)) (goto-char (point-min))
  950. (let (names)
  951. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  952. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  953. names)))
  954. names)))
  955. ;;;###autoload
  956. (defun org-babel-next-src-block (&optional arg)
  957. "Jump to the next source block.
  958. With optional prefix argument ARG, jump forward ARG many source blocks."
  959. (interactive "P")
  960. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  961. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  962. (goto-char (match-beginning 0)) (org-show-context))
  963. ;;;###autoload
  964. (defun org-babel-previous-src-block (&optional arg)
  965. "Jump to the previous source block.
  966. With optional prefix argument ARG, jump backward ARG many source blocks."
  967. (interactive "P")
  968. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  969. (goto-char (match-beginning 0)) (org-show-context))
  970. (defvar org-babel-lob-one-liner-regexp)
  971. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  972. "Find where the current source block results begin.
  973. Return the point at the beginning of the result of the current
  974. source block. Specifically at the beginning of the results line.
  975. If no result exists for this block then create a results line
  976. following the source block."
  977. (save-excursion
  978. (let* ((on-lob-line (progn (beginning-of-line 1)
  979. (looking-at org-babel-lob-one-liner-regexp)))
  980. (name (if on-lob-line
  981. (nth 0 (org-babel-lob-get-info))
  982. (nth 4 (or info (org-babel-get-src-block-info)))))
  983. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  984. found beg end)
  985. (when head (goto-char head))
  986. (setq
  987. found ;; was there a result (before we potentially insert one)
  988. (or
  989. (and
  990. ;; named results:
  991. ;; - return t if it is found, else return nil
  992. ;; - if it does not need to be rebuilt, then don't set end
  993. ;; - if it does need to be rebuilt then do set end
  994. name (setq beg (org-babel-find-named-result name))
  995. (prog1 beg
  996. (when (and hash (not (string= hash (match-string 3))))
  997. (goto-char beg) (setq end beg) ;; beginning of result
  998. (forward-line 1)
  999. (delete-region end (org-babel-result-end)) nil)))
  1000. (and
  1001. ;; unnamed results:
  1002. ;; - return t if it is found, else return nil
  1003. ;; - if it is found, and the hash doesn't match, delete and set end
  1004. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1005. (progn (end-of-line 1)
  1006. (if (eobp) (insert "\n") (forward-char 1))
  1007. (setq end (point))
  1008. (or (and (not name)
  1009. (progn ;; unnamed results line already exists
  1010. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1011. (beginning-of-line 1)
  1012. (looking-at
  1013. (concat org-babel-result-regexp "\n")))
  1014. (prog1 (point)
  1015. ;; must remove and rebuild if hash!=old-hash
  1016. (if (and hash (not (string= hash (match-string 3))))
  1017. (prog1 nil
  1018. (forward-line 1)
  1019. (delete-region
  1020. end (org-babel-result-end)))
  1021. (setq end nil)))))))))
  1022. (if (and insert end)
  1023. (progn
  1024. (goto-char end)
  1025. (unless beg
  1026. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1027. (insert (concat
  1028. (if indent
  1029. (mapconcat
  1030. (lambda (el) " ")
  1031. (number-sequence 1 indent) "")
  1032. "")
  1033. "#+results"
  1034. (when hash (concat "["hash"]"))
  1035. ":"
  1036. (when name (concat " " name)) "\n"))
  1037. (unless beg (insert "\n") (backward-char))
  1038. (beginning-of-line 0)
  1039. (if hash (org-babel-hide-hash))
  1040. (point))
  1041. found))))
  1042. (defvar org-block-regexp)
  1043. (defun org-babel-read-result ()
  1044. "Read the result at `point' into emacs-lisp."
  1045. (let ((case-fold-search t) result-string)
  1046. (cond
  1047. ((org-at-table-p) (org-babel-read-table))
  1048. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1049. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1050. ((looking-at "^[ \t]*: ")
  1051. (setq result-string
  1052. (org-babel-trim
  1053. (mapconcat (lambda (line)
  1054. (if (and (> (length line) 1)
  1055. (string-match "^[ \t]*: \\(.+\\)" line))
  1056. (match-string 1 line)
  1057. line))
  1058. (split-string
  1059. (buffer-substring
  1060. (point) (org-babel-result-end)) "[\r\n]+")
  1061. "\n")))
  1062. (or (org-babel-number-p result-string) result-string))
  1063. ((looking-at org-babel-result-regexp)
  1064. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1065. (defun org-babel-read-table ()
  1066. "Read the table at `point' into emacs-lisp."
  1067. (mapcar (lambda (row)
  1068. (if (and (symbolp row) (equal row 'hline)) row
  1069. (mapcar #'org-babel-read row)))
  1070. (org-table-to-lisp)))
  1071. (defvar org-link-types-re)
  1072. (defun org-babel-read-link ()
  1073. "Read the link at `point' into emacs-lisp.
  1074. If the path of the link is a file path it is expanded using
  1075. `expand-file-name'."
  1076. (let* ((case-fold-search t)
  1077. (raw (and (looking-at org-bracket-link-regexp)
  1078. (org-babel-clean-text-properties (match-string 1))))
  1079. (type (and (string-match org-link-types-re raw)
  1080. (match-string 1 raw))))
  1081. (cond
  1082. ((not type) (expand-file-name raw))
  1083. ((string= type "file")
  1084. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1085. (expand-file-name (match-string 2 raw))))
  1086. (t raw))))
  1087. (defun org-babel-insert-result
  1088. (result &optional result-params info hash indent lang)
  1089. "Insert RESULT into the current buffer.
  1090. By default RESULT is inserted after the end of the
  1091. current source block. With optional argument RESULT-PARAMS
  1092. controls insertion of results in the org-mode file.
  1093. RESULT-PARAMS can take the following values...
  1094. replace - (default option) insert results after the source block
  1095. replacing any previously inserted results
  1096. silent -- no results are inserted
  1097. file ---- the results are interpreted as a file path, and are
  1098. inserted into the buffer using the Org-mode file syntax
  1099. raw ----- results are added directly to the org-mode file. This
  1100. is a good option if you code block will output org-mode
  1101. formatted text.
  1102. org ----- similar in effect to raw, only the results are wrapped
  1103. in an org code block. Similar to the raw option, on
  1104. export the results will be interpreted as org-formatted
  1105. text, however by wrapping the results in an org code
  1106. block they can be replaced upon re-execution of the
  1107. code block.
  1108. html ---- results are added inside of a #+BEGIN_HTML block. This
  1109. is a good option if you code block will output html
  1110. formatted text.
  1111. latex --- results are added inside of a #+BEGIN_LATEX block.
  1112. This is a good option if you code block will output
  1113. latex formatted text.
  1114. code ---- the results are extracted in the syntax of the source
  1115. code of the language being evaluated and are added
  1116. inside of a #+BEGIN_SRC block with the source-code
  1117. language set appropriately. Note this relies on the
  1118. optional LANG argument."
  1119. (if (stringp result)
  1120. (progn
  1121. (setq result (org-babel-clean-text-properties result))
  1122. (when (member "file" result-params)
  1123. (setq result (org-babel-result-to-file result))))
  1124. (unless (listp result) (setq result (format "%S" result))))
  1125. (if (= (length result) 0)
  1126. (if (member "value" result-params)
  1127. (message "No result returned by source block")
  1128. (message "Source block produced no output"))
  1129. (if (and result-params (member "silent" result-params))
  1130. (progn
  1131. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1132. result)
  1133. (when (and (stringp result) ;; ensure results end in a newline
  1134. (not (or (string-equal (substring result -1) "\n")
  1135. (string-equal (substring result -1) "\r"))))
  1136. (setq result (concat result "\n")))
  1137. (save-excursion
  1138. (let ((existing-result (org-babel-where-is-src-block-result
  1139. t info hash indent))
  1140. (results-switches
  1141. (cdr (assoc :results_switches (nth 2 info))))
  1142. beg end)
  1143. (if (not existing-result)
  1144. (setq beg (point))
  1145. (goto-char existing-result)
  1146. (save-excursion
  1147. (re-search-forward "#" nil t)
  1148. (setq indent (- (current-column) 1)))
  1149. (forward-line 1)
  1150. (setq beg (point))
  1151. (cond
  1152. ((member "replace" result-params)
  1153. (delete-region (point) (org-babel-result-end)))
  1154. ((member "append" result-params)
  1155. (goto-char (org-babel-result-end)) (setq beg (point)))
  1156. ((member "prepend" result-params) ;; already there
  1157. )))
  1158. (setq results-switches
  1159. (if results-switches (concat " " results-switches) ""))
  1160. (cond
  1161. ;; assume the result is a table if it's not a string
  1162. ((not (stringp result))
  1163. (insert (concat (orgtbl-to-orgtbl
  1164. (if (or (eq 'hline (car result))
  1165. (and (listp (car result))
  1166. (listp (cdr (car result)))))
  1167. result (list result))
  1168. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1169. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1170. ((member "file" result-params)
  1171. (insert result))
  1172. ((member "html" result-params)
  1173. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  1174. results-switches result)))
  1175. ((member "latex" result-params)
  1176. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1177. results-switches result)))
  1178. ((member "code" result-params)
  1179. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1180. (or lang "none") results-switches result)))
  1181. ((member "org" result-params)
  1182. (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
  1183. ((member "raw" result-params)
  1184. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1185. (t
  1186. (org-babel-examplize-region
  1187. (point) (progn (insert result) (point)) results-switches)))
  1188. ;; possibly indent the results to match the #+results line
  1189. (setq end (if (listp result) (org-table-end) (point)))
  1190. (when (and indent (> indent 0)
  1191. ;; in this case `table-align' does the work for us
  1192. (not (and (listp result)
  1193. (member "append" result-params))))
  1194. (indent-rigidly beg end indent))))
  1195. (message "finished"))))
  1196. (defun org-babel-remove-result (&optional info)
  1197. "Remove the result of the current source block."
  1198. (interactive)
  1199. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1200. (when location
  1201. (save-excursion
  1202. (goto-char location) (setq start (point)) (forward-line 1)
  1203. (delete-region start (org-babel-result-end))))))
  1204. (defun org-babel-result-end ()
  1205. "Return the point at the end of the current set of results"
  1206. (save-excursion
  1207. (if (org-at-table-p)
  1208. (progn (goto-char (org-table-end)) (point))
  1209. (let ((case-fold-search t))
  1210. (cond
  1211. ((looking-at "[ \t]*#\\+begin_latex")
  1212. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1213. (forward-line 1))
  1214. ((looking-at "[ \t]*#\\+begin_html")
  1215. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1216. (forward-line 1))
  1217. ((looking-at "[ \t]*#\\+begin_example")
  1218. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1219. (forward-line 1))
  1220. ((looking-at "[ \t]*#\\+begin_src")
  1221. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1222. (forward-line 1))
  1223. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1224. (forward-line 1))))))
  1225. (point))))
  1226. (defun org-babel-result-to-file (result)
  1227. "Convert RESULT into an `org-mode' link.
  1228. If the `default-directory' is different from the containing
  1229. file's directory then expand relative links."
  1230. (format
  1231. "[[file:%s]]"
  1232. (if (and default-directory
  1233. buffer-file-name
  1234. (not (string= (expand-file-name default-directory)
  1235. (expand-file-name
  1236. (file-name-directory buffer-file-name)))))
  1237. (expand-file-name result default-directory)
  1238. result)))
  1239. (defun org-babel-examplize-region (beg end &optional results-switches)
  1240. "Comment out region using the ': ' org example quote."
  1241. (interactive "*r")
  1242. (let ((size (count-lines beg end)))
  1243. (save-excursion
  1244. (cond ((= size 0)
  1245. (error (concat "This should be impossible:"
  1246. "a newline was appended to result if missing")))
  1247. ((< size org-babel-min-lines-for-block-output)
  1248. (goto-char beg)
  1249. (dotimes (n size)
  1250. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1251. (t
  1252. (goto-char beg)
  1253. (insert (if results-switches
  1254. (format "#+begin_example%s\n" results-switches)
  1255. "#+begin_example\n"))
  1256. (forward-char (- end beg))
  1257. (insert "#+end_example\n"))))))
  1258. (defun org-babel-merge-params (&rest plists)
  1259. "Combine all parameter association lists in PLISTS.
  1260. Later elements of PLISTS override the values of previous element.
  1261. This takes into account some special considerations for certain
  1262. parameters when merging lists."
  1263. (let ((results-exclusive-groups
  1264. '(("file" "vector" "table" "scalar" "raw" "org"
  1265. "html" "latex" "code" "pp")
  1266. ("replace" "silent" "append" "prepend")
  1267. ("output" "value")))
  1268. (exports-exclusive-groups
  1269. '(("code" "results" "both" "none")))
  1270. params results exports tangle noweb cache vars var ref shebang comments)
  1271. (flet ((e-merge (exclusive-groups &rest result-params)
  1272. ;; maintain exclusivity of mutually exclusive parameters
  1273. (let (output)
  1274. (mapc (lambda (new-params)
  1275. (mapc (lambda (new-param)
  1276. (mapc (lambda (exclusive-group)
  1277. (when (member new-param exclusive-group)
  1278. (mapcar (lambda (excluded-param)
  1279. (setq output
  1280. (delete
  1281. excluded-param
  1282. output)))
  1283. exclusive-group)))
  1284. exclusive-groups)
  1285. (setq output (org-uniquify
  1286. (cons new-param output))))
  1287. new-params))
  1288. result-params)
  1289. output)))
  1290. (mapc (lambda (plist)
  1291. (mapc (lambda (pair)
  1292. (case (car pair)
  1293. (:var
  1294. ;; we want only one specification per variable
  1295. (when (string-match
  1296. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1297. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1298. ;; TODO: When is this not true?
  1299. (setq var (intern (match-string 1 (cdr pair)))
  1300. ref (match-string 2 (cdr pair))
  1301. vars (cons (cons var ref)
  1302. (assq-delete-all var vars)))))
  1303. (:results
  1304. (setq results
  1305. (e-merge results-exclusive-groups
  1306. results (split-string (cdr pair)))))
  1307. (:file
  1308. (when (cdr pair)
  1309. (setq results (e-merge results-exclusive-groups
  1310. results '("file")))
  1311. (unless (or (member "both" exports)
  1312. (member "none" exports)
  1313. (member "code" exports))
  1314. (setq exports (e-merge exports-exclusive-groups
  1315. exports '("results"))))
  1316. (setq params
  1317. (cons pair
  1318. (assq-delete-all (car pair) params)))))
  1319. (:exports
  1320. (setq exports
  1321. (e-merge exports-exclusive-groups
  1322. exports (split-string (cdr pair)))))
  1323. (:tangle ;; take the latest -- always overwrite
  1324. (setq tangle (or (list (cdr pair)) tangle)))
  1325. (:noweb
  1326. (setq noweb
  1327. (e-merge '(("yes" "no")) noweb
  1328. (split-string (or (cdr pair) "")))))
  1329. (:cache
  1330. (setq cache
  1331. (e-merge '(("yes" "no")) cache
  1332. (split-string (or (cdr pair) "")))))
  1333. (:shebang ;; take the latest -- always overwrite
  1334. (setq shebang (or (list (cdr pair)) shebang)))
  1335. (:comments
  1336. (setq comments
  1337. (e-merge '(("yes" "no")) comments
  1338. (split-string (or (cdr pair) "")))))
  1339. (t ;; replace: this covers e.g. :session
  1340. (setq params
  1341. (cons pair
  1342. (assq-delete-all (car pair) params))))))
  1343. plist))
  1344. plists))
  1345. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1346. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1347. (cons (cons :comments (mapconcat 'identity comments " "))
  1348. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1349. (cons (cons :cache (mapconcat 'identity cache " "))
  1350. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1351. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1352. (cons (cons :exports
  1353. (mapconcat 'identity exports " "))
  1354. (cons
  1355. (cons :results
  1356. (mapconcat 'identity results " "))
  1357. params)))))))))
  1358. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1359. "Expand Noweb references in the body of the current source code block.
  1360. For example the following reference would be replaced with the
  1361. body of the source-code block named 'example-block'.
  1362. <<example-block>>
  1363. Note that any text preceding the <<foo>> construct on a line will
  1364. be interposed between the lines of the replacement text. So for
  1365. example if <<foo>> is placed behind a comment, then the entire
  1366. replacement text will also be commented.
  1367. This function must be called from inside of the buffer containing
  1368. the source-code block which holds BODY.
  1369. In addition the following syntax can be used to insert the
  1370. results of evaluating the source-code block named 'example-block'.
  1371. <<example-block()>>
  1372. Any optional arguments can be passed to example-block by placing
  1373. the arguments inside the parenthesis following the convention
  1374. defined by `org-babel-lob'. For example
  1375. <<example-block(a=9)>>
  1376. would set the value of argument \"a\" equal to \"9\". Note that
  1377. these arguments are not evaluated in the current source-code
  1378. block but are passed literally to the \"example-block\"."
  1379. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1380. (info (or info (org-babel-get-src-block-info)))
  1381. (lang (nth 0 info))
  1382. (body (nth 1 info))
  1383. (new-body "") index source-name evaluate prefix)
  1384. (flet ((nb-add (text)
  1385. (setq new-body (concat new-body text))))
  1386. (with-temp-buffer
  1387. (insert body) (goto-char (point-min))
  1388. (setq index (point))
  1389. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1390. (save-match-data (setf source-name (match-string 1)))
  1391. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1392. (save-match-data
  1393. (setq prefix
  1394. (buffer-substring (match-beginning 0)
  1395. (save-excursion
  1396. (beginning-of-line 1) (point)))))
  1397. ;; add interval to new-body (removing noweb reference)
  1398. (goto-char (match-beginning 0))
  1399. (nb-add (buffer-substring index (point)))
  1400. (goto-char (match-end 0))
  1401. (setq index (point))
  1402. (nb-add (with-current-buffer parent-buffer
  1403. (mapconcat ;; interpose PREFIX between every line
  1404. #'identity
  1405. (split-string
  1406. (if evaluate
  1407. (let ((raw (org-babel-ref-resolve-reference
  1408. source-name nil)))
  1409. (if (stringp raw) raw (format "%S" raw)))
  1410. (save-restriction
  1411. (widen)
  1412. (let ((point (org-babel-find-named-block
  1413. source-name)))
  1414. (if point
  1415. (save-excursion
  1416. (goto-char point)
  1417. (org-babel-trim
  1418. (org-babel-expand-noweb-references
  1419. (org-babel-get-src-block-info))))
  1420. ;; optionally raise an error if named
  1421. ;; source-block doesn't exist
  1422. (if (member lang org-babel-noweb-error-langs)
  1423. (error "%s"
  1424. (concat
  1425. "<<" source-name ">> "
  1426. "could not be resolved (see "
  1427. "`org-babel-noweb-error-langs')"))
  1428. "")))))
  1429. "[\n\r]") (concat "\n" prefix)))))
  1430. (nb-add (buffer-substring index (point-max)))))
  1431. new-body))
  1432. (defun org-babel-clean-text-properties (text)
  1433. "Strip all properties from text return."
  1434. (when text
  1435. (set-text-properties 0 (length text) nil text) text))
  1436. (defun org-babel-strip-protective-commas (body)
  1437. "Strip protective commas from bodies of source blocks."
  1438. (replace-regexp-in-string "^,#" "#" body))
  1439. (defun org-babel-read (cell)
  1440. "Convert the string value of CELL to a number if appropriate.
  1441. Otherwise if cell looks like lisp (meaning it starts with a
  1442. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1443. unmodified as a string.
  1444. This is taken almost directly from `org-read-prop'."
  1445. (if (and (stringp cell) (not (equal cell "")))
  1446. (or (org-babel-number-p cell)
  1447. (if (or (equal "(" (substring cell 0 1))
  1448. (equal "'" (substring cell 0 1))
  1449. (equal "`" (substring cell 0 1)))
  1450. (eval (read cell))
  1451. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1452. cell))
  1453. (defun org-babel-number-p (string)
  1454. "Return t if STRING represents a number."
  1455. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1456. (= (length (substring string (match-beginning 0)
  1457. (match-end 0)))
  1458. (length string)))
  1459. (string-to-number string)))
  1460. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1461. "Read the results located at FILE-NAME into an elisp table.
  1462. If the table is trivial, then return it as a scalar."
  1463. (let (result)
  1464. (save-window-excursion
  1465. (with-temp-buffer
  1466. (condition-case nil
  1467. (progn
  1468. (org-table-import file-name separator)
  1469. (delete-file file-name)
  1470. (setq result (mapcar (lambda (row)
  1471. (mapcar #'org-babel-string-read row))
  1472. (org-table-to-lisp))))
  1473. (error nil)))
  1474. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1475. (if (consp (car result))
  1476. (if (null (cdr (car result)))
  1477. (caar result)
  1478. result)
  1479. (car result))
  1480. result))))
  1481. (defun org-babel-string-read (cell)
  1482. "Strip nested \"s from around strings."
  1483. (org-babel-read (or (and (stringp cell)
  1484. (string-match "\\\"\\(.+\\)\\\"" cell)
  1485. (match-string 1 cell))
  1486. cell)))
  1487. (defun org-babel-reverse-string (string)
  1488. "Return the reverse of STRING."
  1489. (apply 'string (reverse (string-to-list string))))
  1490. (defun org-babel-chomp (string &optional regexp)
  1491. "Strip trailing spaces and carriage returns from STRING.
  1492. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1493. overwritten by specifying a regexp as a second argument."
  1494. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1495. (while (and (> (length string) 0)
  1496. (string-match regexp (substring string -1)))
  1497. (setq string (substring string 0 -1)))
  1498. string))
  1499. (defun org-babel-trim (string &optional regexp)
  1500. "Strip leading and trailing spaces and carriage returns from STRING.
  1501. Like `org-babel-chomp' only it runs on both the front and back
  1502. of the string."
  1503. (org-babel-chomp (org-babel-reverse-string
  1504. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1505. regexp))
  1506. (defvar org-babel-org-babel-call-process-region-original nil)
  1507. (defun org-babel-tramp-handle-call-process-region
  1508. (start end program &optional delete buffer display &rest args)
  1509. "Use tramp to handle call-process-region.
  1510. Fixes a bug in `tramp-handle-call-process-region'."
  1511. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1512. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1513. (write-region start end tmpfile)
  1514. (when delete (delete-region start end))
  1515. (unwind-protect
  1516. ;; (apply 'call-process program tmpfile buffer display args)
  1517. ;; bug in tramp
  1518. (apply 'process-file program tmpfile buffer display args)
  1519. (delete-file tmpfile)))
  1520. ;; org-babel-call-process-region-original is the original emacs definition. It
  1521. ;; is in scope from the let binding in org-babel-execute-src-block
  1522. (apply org-babel-call-process-region-original
  1523. start end program delete buffer display args)))
  1524. (defun org-babel-maybe-remote-file (file)
  1525. "Conditionally parse information on a remote connnection.
  1526. If FILE specifies a remove file, then parse the information on
  1527. the remote connection."
  1528. (if (file-remote-p default-directory)
  1529. (let* ((vec (tramp-dissect-file-name default-directory))
  1530. (user (tramp-file-name-user vec))
  1531. (host (tramp-file-name-host vec)))
  1532. (concat "/" user (when user "@") host ":" file))
  1533. file))
  1534. (defvar org-babel-temporary-directory
  1535. (or (and (boundp 'org-babel-temporary-directory)
  1536. org-babel-temporary-directory)
  1537. (make-temp-file "babel-" t))
  1538. "Directory to hold temporary files created to execute code blocks.
  1539. Used by `org-babel-temp-file'. This directory will be removed on
  1540. Emacs shutdown.")
  1541. (defun org-babel-temp-file (prefix &optional suffix)
  1542. "Create a temporary file in the `org-babel-temporary-directory'.
  1543. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1544. value of `temporary-file-directory' temporarily set to the value
  1545. of `org-babel-temporary-directory'."
  1546. (let ((temporary-file-directory (expand-file-name
  1547. org-babel-temporary-directory
  1548. temporary-file-directory)))
  1549. (make-temp-file prefix nil suffix)))
  1550. (defun org-babel-remove-temporary-directory ()
  1551. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1552. (when (boundp 'org-babel-temporary-directory)
  1553. ;; taken from `delete-directory' in files.el
  1554. (mapc (lambda (file)
  1555. ;; This test is equivalent to
  1556. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1557. ;; but more efficient
  1558. (if (eq t (car (file-attributes file)))
  1559. (delete-directory file)
  1560. (delete-file file nil)))
  1561. ;; We do not want to delete "." and "..".
  1562. (directory-files org-babel-temporary-directory 'full
  1563. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1564. (delete-directory org-babel-temporary-directory)))
  1565. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1566. (provide 'ob)
  1567. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1568. ;;; ob.el ends here