ob.el 69 KB

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