ob.el 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  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. If FILE is
  658. nil evaluate BODY forms on source blocks in current buffer."
  659. (declare (indent 1))
  660. `(let ((visited-p (or (null ,file)
  661. (get-file-buffer (expand-file-name ,file))))
  662. (point (point)) to-be-removed)
  663. (save-window-excursion
  664. (if ,file (find-file ,file))
  665. (setq to-be-removed (current-buffer))
  666. (goto-char (point-min))
  667. (while (re-search-forward org-babel-src-block-regexp nil t)
  668. (goto-char (match-beginning 0))
  669. (save-match-data ,@body)
  670. (goto-char (match-end 0))))
  671. (unless visited-p
  672. (kill-buffer to-be-removed))
  673. (goto-char point)))
  674. (defvar org-file-properties)
  675. (defun org-babel-params-from-properties (&optional lang)
  676. "Retrieve parameters specified as properties.
  677. Return an association list of any source block params which
  678. may be specified in the properties of the current outline entry."
  679. (save-match-data
  680. (let (val sym)
  681. (delq nil
  682. (mapcar
  683. (lambda (header-arg)
  684. (and (setq val
  685. (or (condition-case nil
  686. (org-entry-get (point) header-arg t)
  687. (error nil))
  688. (cdr (assoc header-arg org-file-properties))))
  689. (cons (intern (concat ":" header-arg)) val)))
  690. (mapcar
  691. 'symbol-name
  692. (append
  693. org-babel-header-arg-names
  694. (progn
  695. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  696. (and (boundp sym) (eval sym))))))))))
  697. (defun org-babel-params-from-buffer ()
  698. "Retrieve per-buffer parameters.
  699. Return an association list of any source block params which
  700. may be specified at the top of the current buffer."
  701. (or org-babel-current-buffer-properties
  702. (setq org-babel-current-buffer-properties
  703. (save-match-data
  704. (save-excursion
  705. (save-restriction
  706. (widen)
  707. (goto-char (point-min))
  708. (when (re-search-forward
  709. (org-make-options-regexp (list "BABEL")) nil t)
  710. (org-babel-parse-header-arguments
  711. (org-match-string-no-properties 2)))))))))
  712. (defvar org-src-preserve-indentation)
  713. (defun org-babel-parse-src-block-match ()
  714. "Parse the results from a match of the `org-babel-src-block-regexp'."
  715. (let* ((block-indentation (length (match-string 1)))
  716. (lang (org-babel-clean-text-properties (match-string 2)))
  717. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  718. (switches (match-string 3))
  719. (body (org-babel-clean-text-properties (match-string 5)))
  720. (preserve-indentation (or org-src-preserve-indentation
  721. (string-match "-i\\>" switches))))
  722. (list lang
  723. ;; get block body less properties, protective commas, and indentation
  724. (with-temp-buffer
  725. (save-match-data
  726. (insert (org-babel-strip-protective-commas body))
  727. (unless preserve-indentation (org-do-remove-indentation))
  728. (buffer-string)))
  729. (org-babel-merge-params
  730. org-babel-default-header-args
  731. (org-babel-params-from-buffer)
  732. (org-babel-params-from-properties lang)
  733. (if (boundp lang-headers) (eval lang-headers) nil)
  734. (org-babel-parse-header-arguments
  735. (org-babel-clean-text-properties (or (match-string 4) ""))))
  736. switches
  737. block-indentation)))
  738. (defun org-babel-parse-inline-src-block-match ()
  739. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  740. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  741. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  742. (list lang
  743. (org-babel-strip-protective-commas
  744. (org-babel-clean-text-properties (match-string 5)))
  745. (org-babel-merge-params
  746. org-babel-default-inline-header-args
  747. (org-babel-params-from-buffer)
  748. (org-babel-params-from-properties lang)
  749. (if (boundp lang-headers) (eval lang-headers) nil)
  750. (org-babel-parse-header-arguments
  751. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  752. (defun org-babel-parse-header-arguments (arg-string)
  753. "Parse a string of header arguments returning an alist."
  754. (if (> (length arg-string) 0)
  755. (delq nil
  756. (mapcar
  757. (lambda (arg)
  758. (if (string-match
  759. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  760. arg)
  761. (cons (intern (concat ":" (match-string 1 arg)))
  762. (let ((raw (org-babel-chomp (match-string 2 arg))))
  763. (if (org-babel-number-p raw)
  764. raw (org-babel-read raw))))
  765. (cons (intern (concat ":" arg)) nil)))
  766. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  767. (defun org-babel-process-params (params)
  768. "Parse params and resolve references.
  769. Return a list (session vars result-params result-type colnames rownames)."
  770. (let* ((session (cdr (assoc :session params)))
  771. (vars-and-names (org-babel-disassemble-tables
  772. (org-babel-ref-variables params)
  773. (cdr (assoc :hlines params))
  774. (cdr (assoc :colnames params))
  775. (cdr (assoc :rownames params))))
  776. (vars (car vars-and-names))
  777. (colnames (cadr vars-and-names))
  778. (rownames (caddr vars-and-names))
  779. (result-params (split-string (or (cdr (assoc :results params)) "")))
  780. (result-type (cond ((member "output" result-params) 'output)
  781. ((member "value" result-params) 'value)
  782. (t 'value))))
  783. (list session vars result-params result-type colnames rownames)))
  784. ;; row and column names
  785. (defun org-babel-del-hlines (table)
  786. "Remove all 'hlines from TABLE."
  787. (remove 'hline table))
  788. (defun org-babel-get-colnames (table)
  789. "Return the column names of TABLE.
  790. Return a cons cell, the `car' of which contains the TABLE less
  791. colnames, and the `cdr' of which contains a list of the column
  792. names."
  793. (if (equal 'hline (nth 1 table))
  794. (cons (cddr table) (car table))
  795. (cons (cdr table) (car table))))
  796. (defun org-babel-get-rownames (table)
  797. "Return the row names of TABLE.
  798. Return a cons cell, the `car' of which contains the TABLE less
  799. colnames, and the `cdr' of which contains a list of the column
  800. names. Note: this function removes any hlines in TABLE."
  801. (flet ((trans (table) (apply #'mapcar* #'list table)))
  802. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  803. (table (trans (mapcar (lambda (row)
  804. (if (not (equal row 'hline))
  805. row
  806. (setq row '())
  807. (dotimes (n width) (setq row (cons 'hline row)))
  808. row))
  809. table))))
  810. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  811. (trans (cdr table)))
  812. (remove 'hline (car table))))))
  813. (defun org-babel-put-colnames (table colnames)
  814. "Add COLNAMES to TABLE if they exist."
  815. (if colnames (apply 'list colnames 'hline table) table))
  816. (defun org-babel-put-rownames (table rownames)
  817. "Add ROWNAMES to TABLE if they exist."
  818. (if rownames
  819. (mapcar (lambda (row)
  820. (if (listp row)
  821. (cons (or (pop rownames) "") row)
  822. row)) table)
  823. table))
  824. (defun org-babel-pick-name (names selector)
  825. "Select one out of an alist of row or column names.
  826. SELECTOR can be either a list of names in which case those names
  827. will be returned directly, or an index into the list NAMES in
  828. which case the indexed names will be return."
  829. (if (listp selector)
  830. selector
  831. (when names
  832. (if (and selector (symbolp selector) (not (equal t selector)))
  833. (cdr (assoc selector names))
  834. (if (integerp selector)
  835. (nth (- selector 1) names)
  836. (cdr (car (last names))))))))
  837. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  838. "Parse tables for further processing.
  839. Process the variables in VARS according to the HLINES,
  840. ROWNAMES and COLNAMES header arguments. Return a list consisting
  841. of the vars, cnames and rnames."
  842. (let (cnames rnames)
  843. (list
  844. (mapcar
  845. (lambda (var)
  846. (when (listp (cdr var))
  847. (when (and (not (equal colnames "no"))
  848. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  849. (not (member 'hline (cddr (cdr var)))))))
  850. (let ((both (org-babel-get-colnames (cdr var))))
  851. (setq cnames (cons (cons (car var) (cdr both))
  852. cnames))
  853. (setq var (cons (car var) (car both)))))
  854. (when (and rownames (not (equal rownames "no")))
  855. (let ((both (org-babel-get-rownames (cdr var))))
  856. (setq rnames (cons (cons (car var) (cdr both))
  857. rnames))
  858. (setq var (cons (car var) (car both)))))
  859. (when (and hlines (not (equal hlines "yes")))
  860. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  861. var)
  862. vars)
  863. cnames rnames)))
  864. (defun org-babel-reassemble-table (table colnames rownames)
  865. "Add column and row names to a table.
  866. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  867. to the table for reinsertion to org-mode."
  868. (if (listp table)
  869. ((lambda (table)
  870. (if (and colnames (listp (car table)) (= (length (car table))
  871. (length colnames)))
  872. (org-babel-put-colnames table colnames) table))
  873. (if (and rownames (= (length table) (length rownames)))
  874. (org-babel-put-rownames table rownames) table))
  875. table))
  876. (defun org-babel-where-is-src-block-head ()
  877. "Find where the current source block begins.
  878. Return the point at the beginning of the current source
  879. block. Specifically at the beginning of the #+BEGIN_SRC line.
  880. If the point is not on a source block then return nil."
  881. (let ((initial (point)) top bottom)
  882. (or
  883. (save-excursion ;; on a source name line
  884. (beginning-of-line 1)
  885. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  886. (looking-at org-babel-src-block-regexp)
  887. (point)))
  888. (save-excursion ;; on a #+begin_src line
  889. (beginning-of-line 1)
  890. (and (looking-at org-babel-src-block-regexp)
  891. (point)))
  892. (save-excursion ;; inside a src block
  893. (and
  894. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  895. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  896. (< top initial) (< initial bottom)
  897. (progn (goto-char top) (beginning-of-line 1)
  898. (looking-at org-babel-src-block-regexp))
  899. (point))))))
  900. ;;;###autoload
  901. (defun org-babel-goto-named-src-block (name)
  902. "Go to a named source-code block."
  903. (interactive
  904. (let ((completion-ignore-case t))
  905. (list (org-icompleting-read "source-block name: "
  906. (org-babel-src-block-names) nil t))))
  907. (let ((point (org-babel-find-named-block name)))
  908. (if point
  909. ;; taken from `org-open-at-point'
  910. (progn (goto-char point) (org-show-context))
  911. (message "source-code block '%s' not found in this buffer" name))))
  912. (defun org-babel-find-named-block (name)
  913. "Find a named source-code block.
  914. Return the location of the source block identified by source
  915. NAME, or nil if no such block exists. Set match data according to
  916. org-babel-named-src-block-regexp."
  917. (save-excursion
  918. (let ((case-fold-search t)
  919. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  920. (goto-char (point-min))
  921. (when (or (re-search-forward regexp nil t)
  922. (re-search-backward regexp nil t))
  923. (match-beginning 0)))))
  924. (defun org-babel-src-block-names (&optional file)
  925. "Returns the names of source blocks in FILE or the current buffer."
  926. (save-excursion
  927. (when file (find-file file)) (goto-char (point-min))
  928. (let (names)
  929. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  930. (setq names (cons (org-babel-clean-text-properties (match-string 2))
  931. names)))
  932. names)))
  933. ;;;###autoload
  934. (defun org-babel-goto-named-result (name)
  935. "Go to a named result."
  936. (interactive
  937. (let ((completion-ignore-case t))
  938. (list (org-icompleting-read "source-block name: "
  939. (org-babel-result-names) nil t))))
  940. (let ((point (org-babel-find-named-result name)))
  941. (if point
  942. ;; taken from `org-open-at-point'
  943. (progn (goto-char point) (org-show-context))
  944. (message "result '%s' not found in this buffer" name))))
  945. (defun org-babel-find-named-result (name)
  946. "Find a named result.
  947. Return the location of the result named NAME in the current
  948. buffer or nil if no such result exists."
  949. (save-excursion
  950. (goto-char (point-min))
  951. (when (re-search-forward
  952. (concat org-babel-result-regexp
  953. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  954. (beginning-of-line 0) (point))))
  955. (defun org-babel-result-names (&optional file)
  956. "Returns the names of results in FILE or the current buffer."
  957. (save-excursion
  958. (when file (find-file file)) (goto-char (point-min))
  959. (let (names)
  960. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  961. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  962. names)))
  963. names)))
  964. ;;;###autoload
  965. (defun org-babel-next-src-block (&optional arg)
  966. "Jump to the next source block.
  967. With optional prefix argument ARG, jump forward ARG many source blocks."
  968. (interactive "P")
  969. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  970. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  971. (goto-char (match-beginning 0)) (org-show-context))
  972. ;;;###autoload
  973. (defun org-babel-previous-src-block (&optional arg)
  974. "Jump to the previous source block.
  975. With optional prefix argument ARG, jump backward ARG many source blocks."
  976. (interactive "P")
  977. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  978. (goto-char (match-beginning 0)) (org-show-context))
  979. (defvar org-babel-lob-one-liner-regexp)
  980. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  981. "Find where the current source block results begin.
  982. Return the point at the beginning of the result of the current
  983. source block. Specifically at the beginning of the results line.
  984. If no result exists for this block then create a results line
  985. following the source block."
  986. (save-excursion
  987. (let* ((on-lob-line (progn (beginning-of-line 1)
  988. (looking-at org-babel-lob-one-liner-regexp)))
  989. (name (if on-lob-line
  990. (nth 0 (org-babel-lob-get-info))
  991. (nth 4 (or info (org-babel-get-src-block-info)))))
  992. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  993. found beg end)
  994. (when head (goto-char head))
  995. (setq
  996. found ;; was there a result (before we potentially insert one)
  997. (or
  998. (and
  999. ;; named results:
  1000. ;; - return t if it is found, else return nil
  1001. ;; - if it does not need to be rebuilt, then don't set end
  1002. ;; - if it does need to be rebuilt then do set end
  1003. name (setq beg (org-babel-find-named-result name))
  1004. (prog1 beg
  1005. (when (and hash (not (string= hash (match-string 3))))
  1006. (goto-char beg) (setq end beg) ;; beginning of result
  1007. (forward-line 1)
  1008. (delete-region end (org-babel-result-end)) nil)))
  1009. (and
  1010. ;; unnamed results:
  1011. ;; - return t if it is found, else return nil
  1012. ;; - if it is found, and the hash doesn't match, delete and set end
  1013. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1014. (progn (end-of-line 1)
  1015. (if (eobp) (insert "\n") (forward-char 1))
  1016. (setq end (point))
  1017. (or (and (not name)
  1018. (progn ;; unnamed results line already exists
  1019. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1020. (beginning-of-line 1)
  1021. (looking-at
  1022. (concat org-babel-result-regexp "\n")))
  1023. (prog1 (point)
  1024. ;; must remove and rebuild if hash!=old-hash
  1025. (if (and hash (not (string= hash (match-string 3))))
  1026. (prog1 nil
  1027. (forward-line 1)
  1028. (delete-region
  1029. end (org-babel-result-end)))
  1030. (setq end nil)))))))))
  1031. (if (and insert end)
  1032. (progn
  1033. (goto-char end)
  1034. (unless beg
  1035. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1036. (insert (concat
  1037. (if indent
  1038. (mapconcat
  1039. (lambda (el) " ")
  1040. (number-sequence 1 indent) "")
  1041. "")
  1042. "#+results"
  1043. (when hash (concat "["hash"]"))
  1044. ":"
  1045. (when name (concat " " name)) "\n"))
  1046. (unless beg (insert "\n") (backward-char))
  1047. (beginning-of-line 0)
  1048. (if hash (org-babel-hide-hash))
  1049. (point))
  1050. found))))
  1051. (defvar org-block-regexp)
  1052. (defun org-babel-read-result ()
  1053. "Read the result at `point' into emacs-lisp."
  1054. (let ((case-fold-search t) result-string)
  1055. (cond
  1056. ((org-at-table-p) (org-babel-read-table))
  1057. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1058. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1059. ((looking-at "^[ \t]*: ")
  1060. (setq result-string
  1061. (org-babel-trim
  1062. (mapconcat (lambda (line)
  1063. (if (and (> (length line) 1)
  1064. (string-match "^[ \t]*: \\(.+\\)" line))
  1065. (match-string 1 line)
  1066. line))
  1067. (split-string
  1068. (buffer-substring
  1069. (point) (org-babel-result-end)) "[\r\n]+")
  1070. "\n")))
  1071. (or (org-babel-number-p result-string) result-string))
  1072. ((looking-at org-babel-result-regexp)
  1073. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1074. (defun org-babel-read-table ()
  1075. "Read the table at `point' into emacs-lisp."
  1076. (mapcar (lambda (row)
  1077. (if (and (symbolp row) (equal row 'hline)) row
  1078. (mapcar #'org-babel-read row)))
  1079. (org-table-to-lisp)))
  1080. (defvar org-link-types-re)
  1081. (defun org-babel-read-link ()
  1082. "Read the link at `point' into emacs-lisp.
  1083. If the path of the link is a file path it is expanded using
  1084. `expand-file-name'."
  1085. (let* ((case-fold-search t)
  1086. (raw (and (looking-at org-bracket-link-regexp)
  1087. (org-babel-clean-text-properties (match-string 1))))
  1088. (type (and (string-match org-link-types-re raw)
  1089. (match-string 1 raw))))
  1090. (cond
  1091. ((not type) (expand-file-name raw))
  1092. ((string= type "file")
  1093. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1094. (expand-file-name (match-string 2 raw))))
  1095. (t raw))))
  1096. (defun org-babel-insert-result
  1097. (result &optional result-params info hash indent lang)
  1098. "Insert RESULT into the current buffer.
  1099. By default RESULT is inserted after the end of the
  1100. current source block. With optional argument RESULT-PARAMS
  1101. controls insertion of results in the org-mode file.
  1102. RESULT-PARAMS can take the following values...
  1103. replace - (default option) insert results after the source block
  1104. replacing any previously inserted results
  1105. silent -- no results are inserted
  1106. file ---- the results are interpreted as a file path, and are
  1107. inserted into the buffer using the Org-mode file syntax
  1108. raw ----- results are added directly to the org-mode file. This
  1109. is a good option if you code block will output org-mode
  1110. formatted text.
  1111. org ----- similar in effect to raw, only the results are wrapped
  1112. in an org code block. Similar to the raw option, on
  1113. export the results will be interpreted as org-formatted
  1114. text, however by wrapping the results in an org code
  1115. block they can be replaced upon re-execution of the
  1116. code block.
  1117. html ---- results are added inside of a #+BEGIN_HTML block. This
  1118. is a good option if you code block will output html
  1119. formatted text.
  1120. latex --- results are added inside of a #+BEGIN_LATEX block.
  1121. This is a good option if you code block will output
  1122. latex formatted text.
  1123. code ---- the results are extracted in the syntax of the source
  1124. code of the language being evaluated and are added
  1125. inside of a #+BEGIN_SRC block with the source-code
  1126. language set appropriately. Note this relies on the
  1127. optional LANG argument."
  1128. (if (stringp result)
  1129. (progn
  1130. (setq result (org-babel-clean-text-properties result))
  1131. (when (member "file" result-params)
  1132. (setq result (org-babel-result-to-file result))))
  1133. (unless (listp result) (setq result (format "%S" result))))
  1134. (if (= (length result) 0)
  1135. (if (member "value" result-params)
  1136. (message "No result returned by source block")
  1137. (message "Source block produced no output"))
  1138. (if (and result-params (member "silent" result-params))
  1139. (progn
  1140. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1141. result)
  1142. (when (and (stringp result) ;; ensure results end in a newline
  1143. (not (or (string-equal (substring result -1) "\n")
  1144. (string-equal (substring result -1) "\r"))))
  1145. (setq result (concat result "\n")))
  1146. (save-excursion
  1147. (let ((existing-result (org-babel-where-is-src-block-result
  1148. t info hash indent))
  1149. (results-switches
  1150. (cdr (assoc :results_switches (nth 2 info))))
  1151. beg end)
  1152. (if (not existing-result)
  1153. (setq beg (point))
  1154. (goto-char existing-result)
  1155. (save-excursion
  1156. (re-search-forward "#" nil t)
  1157. (setq indent (- (current-column) 1)))
  1158. (forward-line 1)
  1159. (setq beg (point))
  1160. (cond
  1161. ((member "replace" result-params)
  1162. (delete-region (point) (org-babel-result-end)))
  1163. ((member "append" result-params)
  1164. (goto-char (org-babel-result-end)) (setq beg (point)))
  1165. ((member "prepend" result-params) ;; already there
  1166. )))
  1167. (setq results-switches
  1168. (if results-switches (concat " " results-switches) ""))
  1169. (cond
  1170. ;; assume the result is a table if it's not a string
  1171. ((not (stringp result))
  1172. (insert (concat (orgtbl-to-orgtbl
  1173. (if (or (eq 'hline (car result))
  1174. (and (listp (car result))
  1175. (listp (cdr (car result)))))
  1176. result (list result))
  1177. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1178. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1179. ((member "file" result-params)
  1180. (insert result))
  1181. ((member "html" result-params)
  1182. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  1183. results-switches result)))
  1184. ((member "latex" result-params)
  1185. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1186. results-switches result)))
  1187. ((member "code" result-params)
  1188. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1189. (or lang "none") results-switches result)))
  1190. ((member "org" result-params)
  1191. (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
  1192. ((member "raw" result-params)
  1193. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1194. (t
  1195. (org-babel-examplize-region
  1196. (point) (progn (insert result) (point)) results-switches)))
  1197. ;; possibly indent the results to match the #+results line
  1198. (setq end (if (listp result) (org-table-end) (point)))
  1199. (when (and indent (> indent 0)
  1200. ;; in this case `table-align' does the work for us
  1201. (not (and (listp result)
  1202. (member "append" result-params))))
  1203. (indent-rigidly beg end indent))))
  1204. (message "finished"))))
  1205. (defun org-babel-remove-result (&optional info)
  1206. "Remove the result of the current source block."
  1207. (interactive)
  1208. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1209. (when location
  1210. (save-excursion
  1211. (goto-char location) (setq start (point)) (forward-line 1)
  1212. (delete-region start (org-babel-result-end))))))
  1213. (defun org-babel-result-end ()
  1214. "Return the point at the end of the current set of results"
  1215. (save-excursion
  1216. (if (org-at-table-p)
  1217. (progn (goto-char (org-table-end)) (point))
  1218. (let ((case-fold-search t))
  1219. (cond
  1220. ((looking-at "[ \t]*#\\+begin_latex")
  1221. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1222. (forward-line 1))
  1223. ((looking-at "[ \t]*#\\+begin_html")
  1224. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1225. (forward-line 1))
  1226. ((looking-at "[ \t]*#\\+begin_example")
  1227. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1228. (forward-line 1))
  1229. ((looking-at "[ \t]*#\\+begin_src")
  1230. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1231. (forward-line 1))
  1232. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1233. (forward-line 1))))))
  1234. (point))))
  1235. (defun org-babel-result-to-file (result)
  1236. "Convert RESULT into an `org-mode' link.
  1237. If the `default-directory' is different from the containing
  1238. file's directory then expand relative links."
  1239. (format
  1240. "[[file:%s]]"
  1241. (if (and default-directory
  1242. buffer-file-name
  1243. (not (string= (expand-file-name default-directory)
  1244. (expand-file-name
  1245. (file-name-directory buffer-file-name)))))
  1246. (expand-file-name result default-directory)
  1247. result)))
  1248. (defun org-babel-examplize-region (beg end &optional results-switches)
  1249. "Comment out region using the ': ' org example quote."
  1250. (interactive "*r")
  1251. (let ((size (count-lines beg end)))
  1252. (save-excursion
  1253. (cond ((= size 0)
  1254. (error (concat "This should be impossible:"
  1255. "a newline was appended to result if missing")))
  1256. ((< size org-babel-min-lines-for-block-output)
  1257. (goto-char beg)
  1258. (dotimes (n size)
  1259. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1260. (t
  1261. (goto-char beg)
  1262. (insert (if results-switches
  1263. (format "#+begin_example%s\n" results-switches)
  1264. "#+begin_example\n"))
  1265. (forward-char (- end beg))
  1266. (insert "#+end_example\n"))))))
  1267. (defun org-babel-merge-params (&rest plists)
  1268. "Combine all parameter association lists in PLISTS.
  1269. Later elements of PLISTS override the values of previous element.
  1270. This takes into account some special considerations for certain
  1271. parameters when merging lists."
  1272. (let ((results-exclusive-groups
  1273. '(("file" "vector" "table" "scalar" "raw" "org"
  1274. "html" "latex" "code" "pp")
  1275. ("replace" "silent" "append" "prepend")
  1276. ("output" "value")))
  1277. (exports-exclusive-groups
  1278. '(("code" "results" "both" "none")))
  1279. params results exports tangle noweb cache vars var ref shebang comments)
  1280. (flet ((e-merge (exclusive-groups &rest result-params)
  1281. ;; maintain exclusivity of mutually exclusive parameters
  1282. (let (output)
  1283. (mapc (lambda (new-params)
  1284. (mapc (lambda (new-param)
  1285. (mapc (lambda (exclusive-group)
  1286. (when (member new-param exclusive-group)
  1287. (mapcar (lambda (excluded-param)
  1288. (setq output
  1289. (delete
  1290. excluded-param
  1291. output)))
  1292. exclusive-group)))
  1293. exclusive-groups)
  1294. (setq output (org-uniquify
  1295. (cons new-param output))))
  1296. new-params))
  1297. result-params)
  1298. output)))
  1299. (mapc (lambda (plist)
  1300. (mapc (lambda (pair)
  1301. (case (car pair)
  1302. (:var
  1303. ;; we want only one specification per variable
  1304. (when (string-match
  1305. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1306. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1307. ;; TODO: When is this not true?
  1308. (setq var (intern (match-string 1 (cdr pair)))
  1309. ref (match-string 2 (cdr pair))
  1310. vars (cons (cons var ref)
  1311. (assq-delete-all var vars)))))
  1312. (:results
  1313. (setq results
  1314. (e-merge results-exclusive-groups
  1315. results (split-string (cdr pair)))))
  1316. (:file
  1317. (when (cdr pair)
  1318. (setq results (e-merge results-exclusive-groups
  1319. results '("file")))
  1320. (unless (or (member "both" exports)
  1321. (member "none" exports)
  1322. (member "code" exports))
  1323. (setq exports (e-merge exports-exclusive-groups
  1324. exports '("results"))))
  1325. (setq params
  1326. (cons pair
  1327. (assq-delete-all (car pair) params)))))
  1328. (:exports
  1329. (setq exports
  1330. (e-merge exports-exclusive-groups
  1331. exports (split-string (cdr pair)))))
  1332. (:tangle ;; take the latest -- always overwrite
  1333. (setq tangle (or (list (cdr pair)) tangle)))
  1334. (:noweb
  1335. (setq noweb
  1336. (e-merge '(("yes" "no")) noweb
  1337. (split-string (or (cdr pair) "")))))
  1338. (:cache
  1339. (setq cache
  1340. (e-merge '(("yes" "no")) cache
  1341. (split-string (or (cdr pair) "")))))
  1342. (:shebang ;; take the latest -- always overwrite
  1343. (setq shebang (or (list (cdr pair)) shebang)))
  1344. (:comments
  1345. (setq comments
  1346. (e-merge '(("yes" "no")) comments
  1347. (split-string (or (cdr pair) "")))))
  1348. (t ;; replace: this covers e.g. :session
  1349. (setq params
  1350. (cons pair
  1351. (assq-delete-all (car pair) params))))))
  1352. plist))
  1353. plists))
  1354. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1355. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1356. (cons (cons :comments (mapconcat 'identity comments " "))
  1357. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1358. (cons (cons :cache (mapconcat 'identity cache " "))
  1359. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1360. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1361. (cons (cons :exports
  1362. (mapconcat 'identity exports " "))
  1363. (cons
  1364. (cons :results
  1365. (mapconcat 'identity results " "))
  1366. params)))))))))
  1367. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1368. "Expand Noweb references in the body of the current source code block.
  1369. For example the following reference would be replaced with the
  1370. body of the source-code block named 'example-block'.
  1371. <<example-block>>
  1372. Note that any text preceding the <<foo>> construct on a line will
  1373. be interposed between the lines of the replacement text. So for
  1374. example if <<foo>> is placed behind a comment, then the entire
  1375. replacement text will also be commented.
  1376. This function must be called from inside of the buffer containing
  1377. the source-code block which holds BODY.
  1378. In addition the following syntax can be used to insert the
  1379. results of evaluating the source-code block named 'example-block'.
  1380. <<example-block()>>
  1381. Any optional arguments can be passed to example-block by placing
  1382. the arguments inside the parenthesis following the convention
  1383. defined by `org-babel-lob'. For example
  1384. <<example-block(a=9)>>
  1385. would set the value of argument \"a\" equal to \"9\". Note that
  1386. these arguments are not evaluated in the current source-code
  1387. block but are passed literally to the \"example-block\"."
  1388. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1389. (info (or info (org-babel-get-src-block-info)))
  1390. (lang (nth 0 info))
  1391. (body (nth 1 info))
  1392. (new-body "") index source-name evaluate prefix)
  1393. (flet ((nb-add (text)
  1394. (setq new-body (concat new-body text))))
  1395. (with-temp-buffer
  1396. (insert body) (goto-char (point-min))
  1397. (setq index (point))
  1398. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1399. (save-match-data (setf source-name (match-string 1)))
  1400. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1401. (save-match-data
  1402. (setq prefix
  1403. (buffer-substring (match-beginning 0)
  1404. (save-excursion
  1405. (beginning-of-line 1) (point)))))
  1406. ;; add interval to new-body (removing noweb reference)
  1407. (goto-char (match-beginning 0))
  1408. (nb-add (buffer-substring index (point)))
  1409. (goto-char (match-end 0))
  1410. (setq index (point))
  1411. (nb-add (with-current-buffer parent-buffer
  1412. (mapconcat ;; interpose PREFIX between every line
  1413. #'identity
  1414. (split-string
  1415. (if evaluate
  1416. (let ((raw (org-babel-ref-resolve-reference
  1417. source-name nil)))
  1418. (if (stringp raw) raw (format "%S" raw)))
  1419. (save-restriction
  1420. (widen)
  1421. (let ((point (org-babel-find-named-block
  1422. source-name)))
  1423. (if point
  1424. (save-excursion
  1425. (goto-char point)
  1426. (org-babel-trim
  1427. (org-babel-expand-noweb-references
  1428. (org-babel-get-src-block-info))))
  1429. ;; optionally raise an error if named
  1430. ;; source-block doesn't exist
  1431. (if (member lang org-babel-noweb-error-langs)
  1432. (error "%s"
  1433. (concat
  1434. "<<" source-name ">> "
  1435. "could not be resolved (see "
  1436. "`org-babel-noweb-error-langs')"))
  1437. "")))))
  1438. "[\n\r]") (concat "\n" prefix)))))
  1439. (nb-add (buffer-substring index (point-max)))))
  1440. new-body))
  1441. (defun org-babel-clean-text-properties (text)
  1442. "Strip all properties from text return."
  1443. (when text
  1444. (set-text-properties 0 (length text) nil text) text))
  1445. (defun org-babel-strip-protective-commas (body)
  1446. "Strip protective commas from bodies of source blocks."
  1447. (replace-regexp-in-string "^,#" "#" body))
  1448. (defun org-babel-read (cell)
  1449. "Convert the string value of CELL to a number if appropriate.
  1450. Otherwise if cell looks like lisp (meaning it starts with a
  1451. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1452. unmodified as a string.
  1453. This is taken almost directly from `org-read-prop'."
  1454. (if (and (stringp cell) (not (equal cell "")))
  1455. (or (org-babel-number-p cell)
  1456. (if (or (equal "(" (substring cell 0 1))
  1457. (equal "'" (substring cell 0 1))
  1458. (equal "`" (substring cell 0 1)))
  1459. (eval (read cell))
  1460. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1461. cell))
  1462. (defun org-babel-number-p (string)
  1463. "Return t if STRING represents a number."
  1464. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1465. (= (length (substring string (match-beginning 0)
  1466. (match-end 0)))
  1467. (length string)))
  1468. (string-to-number string)))
  1469. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1470. "Read the results located at FILE-NAME into an elisp table.
  1471. If the table is trivial, then return it as a scalar."
  1472. (let (result)
  1473. (save-window-excursion
  1474. (with-temp-buffer
  1475. (condition-case nil
  1476. (progn
  1477. (org-table-import file-name separator)
  1478. (delete-file file-name)
  1479. (setq result (mapcar (lambda (row)
  1480. (mapcar #'org-babel-string-read row))
  1481. (org-table-to-lisp))))
  1482. (error nil)))
  1483. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1484. (if (consp (car result))
  1485. (if (null (cdr (car result)))
  1486. (caar result)
  1487. result)
  1488. (car result))
  1489. result))))
  1490. (defun org-babel-string-read (cell)
  1491. "Strip nested \"s from around strings."
  1492. (org-babel-read (or (and (stringp cell)
  1493. (string-match "\\\"\\(.+\\)\\\"" cell)
  1494. (match-string 1 cell))
  1495. cell)))
  1496. (defun org-babel-reverse-string (string)
  1497. "Return the reverse of STRING."
  1498. (apply 'string (reverse (string-to-list string))))
  1499. (defun org-babel-chomp (string &optional regexp)
  1500. "Strip trailing spaces and carriage returns from STRING.
  1501. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1502. overwritten by specifying a regexp as a second argument."
  1503. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1504. (while (and (> (length string) 0)
  1505. (string-match regexp (substring string -1)))
  1506. (setq string (substring string 0 -1)))
  1507. string))
  1508. (defun org-babel-trim (string &optional regexp)
  1509. "Strip leading and trailing spaces and carriage returns from STRING.
  1510. Like `org-babel-chomp' only it runs on both the front and back
  1511. of the string."
  1512. (org-babel-chomp (org-babel-reverse-string
  1513. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1514. regexp))
  1515. (defvar org-babel-org-babel-call-process-region-original nil)
  1516. (defun org-babel-tramp-handle-call-process-region
  1517. (start end program &optional delete buffer display &rest args)
  1518. "Use tramp to handle call-process-region.
  1519. Fixes a bug in `tramp-handle-call-process-region'."
  1520. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1521. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1522. (write-region start end tmpfile)
  1523. (when delete (delete-region start end))
  1524. (unwind-protect
  1525. ;; (apply 'call-process program tmpfile buffer display args)
  1526. ;; bug in tramp
  1527. (apply 'process-file program tmpfile buffer display args)
  1528. (delete-file tmpfile)))
  1529. ;; org-babel-call-process-region-original is the original emacs definition. It
  1530. ;; is in scope from the let binding in org-babel-execute-src-block
  1531. (apply org-babel-call-process-region-original
  1532. start end program delete buffer display args)))
  1533. (defun org-babel-maybe-remote-file (file)
  1534. "Conditionally parse information on a remote connnection.
  1535. If FILE specifies a remove file, then parse the information on
  1536. the remote connection."
  1537. (if (file-remote-p default-directory)
  1538. (let* ((vec (tramp-dissect-file-name default-directory))
  1539. (user (tramp-file-name-user vec))
  1540. (host (tramp-file-name-host vec)))
  1541. (concat "/" user (when user "@") host ":" file))
  1542. file))
  1543. (defun org-babel-tramp-localname (file)
  1544. "Return the local name component of FILE."
  1545. (if (file-remote-p file)
  1546. (let (localname)
  1547. (with-parsed-tramp-file-name file nil
  1548. localname))
  1549. file))
  1550. (defvar org-babel-temporary-directory
  1551. (or (and (boundp 'org-babel-temporary-directory)
  1552. org-babel-temporary-directory)
  1553. (make-temp-file "babel-" t))
  1554. "Directory to hold temporary files created to execute code blocks.
  1555. Used by `org-babel-temp-file'. This directory will be removed on
  1556. Emacs shutdown.")
  1557. (defun org-babel-temp-file (prefix &optional suffix)
  1558. "Create a temporary file in the `org-babel-temporary-directory'.
  1559. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1560. value of `temporary-file-directory' temporarily set to the value
  1561. of `org-babel-temporary-directory'."
  1562. (if (file-remote-p default-directory)
  1563. (make-temp-file
  1564. (concat (file-remote-p default-directory)
  1565. (expand-file-name
  1566. prefix temporary-file-directory)
  1567. nil suffix))
  1568. (let ((temporary-file-directory (expand-file-name
  1569. org-babel-temporary-directory
  1570. temporary-file-directory)))
  1571. (make-temp-file prefix nil suffix))))
  1572. (defun org-babel-remove-temporary-directory ()
  1573. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1574. (when (boundp 'org-babel-temporary-directory)
  1575. ;; taken from `delete-directory' in files.el
  1576. (mapc (lambda (file)
  1577. ;; This test is equivalent to
  1578. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1579. ;; but more efficient
  1580. (if (eq t (car (file-attributes file)))
  1581. (delete-directory file)
  1582. (delete-file file)))
  1583. ;; We do not want to delete "." and "..".
  1584. (directory-files org-babel-temporary-directory 'full
  1585. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1586. (delete-directory org-babel-temporary-directory)))
  1587. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1588. (provide 'ob)
  1589. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1590. ;;; ob.el ends here