ob.el 65 KB

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