ob.el 69 KB

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