ob.el 68 KB

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