org-babel.el 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. ;;; org-babel.el --- facilitating communication between programming languages and people
  2. ;; Copyright (C) 2009 Eric Schulte, Dan Davison
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;;; License:
  8. ;; This program 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, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;; Commentary:
  23. ;; See org-babel.org in the parent directory for more information
  24. ;;; Code:
  25. (require 'org)
  26. (defun org-babel-execute-src-block-maybe ()
  27. "Detect if this is context for a org-babel src-block and if so
  28. then run `org-babel-execute-src-block'."
  29. (interactive)
  30. (let ((info (org-babel-get-src-block-info)))
  31. (if info (progn (org-babel-execute-src-block current-prefix-arg info) t) nil)))
  32. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-src-block-maybe)
  33. (defadvice org-edit-special (around org-babel-prep-session-for-edit activate)
  34. "Prepare the current source block's session according to it's
  35. header arguments before editing in an org-src buffer. This
  36. function is called when `org-edit-special' is called with a
  37. prefix argument from inside of a source-code block."
  38. (when current-prefix-arg
  39. (let* ((info (org-babel-get-src-block-info))
  40. (lang (first info))
  41. (params (third info))
  42. (session (cdr (assoc :session params))))
  43. (when (and info session) ;; if we are in a source-code block which has a session
  44. (funcall (intern (concat "org-babel-prep-session:" lang)) session params))))
  45. ad-do-it)
  46. (defadvice org-open-at-point (around org-babel-open-at-point activate)
  47. "If `point' is on a source code block, then open that block's
  48. results with `org-babel-open-src-block-results', otherwise defer
  49. to `org-open-at-point'."
  50. (interactive "P")
  51. (or (call-interactively #'org-babel-open-src-block-result) ad-do-it))
  52. (defun org-babel-load-in-session-maybe ()
  53. "Detect if this is context for a org-babel src-block and if so
  54. then run `org-babel-load-in-session'."
  55. (interactive)
  56. (let ((info (org-babel-get-src-block-info)))
  57. (if info (progn (org-babel-load-in-session current-prefix-arg info) t) nil)))
  58. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  59. (defun org-babel-pop-to-session-maybe ()
  60. "Detect if this is context for a org-babel src-block and if so
  61. then run `org-babel-pop-to-session'."
  62. (interactive)
  63. (let ((info (org-babel-get-src-block-info)))
  64. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  65. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  66. (defvar org-babel-default-header-args
  67. '((:session . "none") (:results . "replace") (:exports . "code") (:nocache))
  68. "Default arguments to use when evaluating a source block.")
  69. (defvar org-babel-default-inline-header-args
  70. '((:session . "none") (:results . "silent") (:exports . "results"))
  71. "Default arguments to use when evaluating an inline source block.")
  72. (defvar org-babel-src-block-regexp nil
  73. "Regexp used to test when inside of a org-babel src-block")
  74. (defvar org-babel-inline-src-block-regexp nil
  75. "Regexp used to test when on an inline org-babel src-block")
  76. (defvar org-babel-result-regexp
  77. "#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:"
  78. "Regular expression used to match result lines. If the
  79. results are associated with a hash key then the hash will be
  80. saved in the second match data.")
  81. (defvar org-babel-source-name-regexp
  82. "#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  83. "Regular expression used to match a source name line.")
  84. (defvar org-babel-min-lines-for-block-output 10
  85. "If number of lines of output is equal to or exceeds this
  86. value, the output is placed in a #+begin_example...#+end_example
  87. block. Otherwise the output is marked as literal by inserting
  88. colons at the starts of the lines. This variable only takes
  89. effect if the :results output option is in effect.")
  90. (defvar org-babel-noweb-error-langs nil
  91. "List of language for which errors should be raised when the
  92. source code block satisfying a noweb reference in this language
  93. can not be resolved.")
  94. (defvar org-babel-hash-show 4
  95. "Number of initial characters to show of a hidden results hash.")
  96. (defun org-babel-named-src-block-regexp-for-name (name)
  97. "Regexp used to match named src block."
  98. (concat org-babel-source-name-regexp (regexp-quote name) "[ \t\n]*"
  99. (substring org-babel-src-block-regexp 1)))
  100. (defun org-babel-set-interpreters (var value)
  101. (set-default var value)
  102. (setq org-babel-src-block-regexp
  103. (concat "^[ \t]*#\\+begin_src[ \t]+\\(" ;; (1) lang
  104. (mapconcat 'regexp-quote value "\\|")
  105. "\\)[ \t]*"
  106. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)" ;; (2) switches
  107. "\\([^\n]*\\)\n" ;; (3) header arguments
  108. "\\([^\000]+?\\)#\\+end_src")) ;; (4) body
  109. (setq org-babel-inline-src-block-regexp
  110. (concat "[ \f\t\n\r\v]\\(src_" ;; (1) replacement target
  111. "\\(" ;; (2) lang
  112. (mapconcat 'regexp-quote value "\\|")
  113. "\\)"
  114. "\\(\\|\\[\\(.*\\)\\]\\)" ;; (3,4) (unused, headers)
  115. "{\\([^\f\n\r\v]+\\)}" ;; (5) body
  116. "\\)")))
  117. (defun org-babel-add-interpreter (interpreter)
  118. "Add INTERPRETER to `org-babel-interpreters' and update
  119. `org-babel-src-block-regexp' appropriately."
  120. (unless (member interpreter org-babel-interpreters)
  121. (setq org-babel-interpreters (cons interpreter org-babel-interpreters))
  122. (org-babel-set-interpreters 'org-babel-interpreters org-babel-interpreters)))
  123. (defcustom org-babel-interpreters '()
  124. "Interpreters allows for evaluation tags.
  125. This is a list of program names (as strings) that can evaluate code and
  126. insert the output into an Org-mode buffer. Valid choices are
  127. R Evaluate R code
  128. emacs-lisp Evaluate Emacs Lisp code and display the result
  129. sh Pass command to the shell and display the result
  130. perl The perl interpreter
  131. python The python interpreter
  132. ruby The ruby interpreter
  133. The source block regexp `org-babel-src-block-regexp' is updated
  134. when a new interpreter is added to this list through the
  135. customize interface. To add interpreters to this variable from
  136. lisp code use the `org-babel-add-interpreter' function."
  137. :group 'org-babel
  138. :set 'org-babel-set-interpreters
  139. :type '(set :greedy t
  140. (const "R")
  141. (const "emacs-lisp")
  142. (const "sh")
  143. (const "perl")
  144. (const "python")
  145. (const "ruby")))
  146. ;;; functions
  147. (defun org-babel-execute-src-block (&optional arg info params)
  148. "Execute the current source code block, and insert the results
  149. into the buffer. Source code execution and the collection and
  150. formatting of results can be controlled through a variety of
  151. header arguments.
  152. Optionally supply a value for INFO in the form returned by
  153. `org-babel-get-src-block-info'.
  154. Optionally supply a value for PARAMS which will be merged with
  155. the header arguments specified at the front of the source code
  156. block."
  157. (interactive)
  158. ;; (message "supplied params=%S" params) ;; debugging
  159. (let* ((info (or info (org-babel-get-src-block-info)))
  160. (lang (first info))
  161. (params (setf (third info)
  162. (sort (org-babel-merge-params (third info) params)
  163. (lambda (el1 el2) (string< (symbol-name (car el1))
  164. (symbol-name (car el2)))))))
  165. (new-hash (unless (assoc :nocache params) (org-babel-sha1-hash info)))
  166. (old-hash (org-babel-result-hash info))
  167. (body (setf (second info)
  168. (if (assoc :noweb params)
  169. (org-babel-expand-noweb-references info) (second info))))
  170. (result-params (split-string (or (cdr (assoc :results params)) "")))
  171. (result-type (cond ((member "output" result-params) 'output)
  172. ((member "value" result-params) 'value)
  173. (t 'value)))
  174. (cmd (intern (concat "org-babel-execute:" lang)))
  175. result)
  176. ;; (message "params=%S" params) ;; debugging
  177. (unless (member lang org-babel-interpreters)
  178. (error "Language is not in `org-babel-interpreters': %s" lang))
  179. (if (and (not arg) new-hash (equal new-hash old-hash))
  180. (save-excursion ;; return cached result
  181. (goto-char (org-babel-where-is-src-block-result nil info))
  182. (move-end-of-line 1) (forward-char 1)
  183. (setq result (org-babel-read-result))
  184. (message (replace-regexp-in-string "%" "%%" (format "%S" result))) result)
  185. (setq result (funcall cmd body params))
  186. (if (eq result-type 'value)
  187. (setq result (if (and (or (member "vector" result-params)
  188. (member "table" result-params))
  189. (not (listp result)))
  190. (list (list result))
  191. result)))
  192. (org-babel-insert-result result result-params info new-hash)
  193. result)))
  194. (defun org-babel-load-in-session (&optional arg info)
  195. "Load the body of the current source-code block. Evaluate the
  196. header arguments for the source block before entering the
  197. session. After loading the body this pops open the session."
  198. (interactive)
  199. (let* ((info (or info (org-babel-get-src-block-info)))
  200. (lang (first info))
  201. (body (second info))
  202. (params (third info))
  203. (session (cdr (assoc :session params))))
  204. (unless (member lang org-babel-interpreters)
  205. (error "Language is not in `org-babel-interpreters': %s" lang))
  206. ;; if called with a prefix argument, then process header arguments
  207. (pop-to-buffer (funcall (intern (concat "org-babel-load-session:" lang)) session body params))
  208. (move-end-of-line 1)))
  209. (defun org-babel-pop-to-session (&optional arg info)
  210. "Pop to the session of the current source-code block. If
  211. called with a prefix argument then evaluate the header arguments
  212. for the source block before entering the session. Copy the body
  213. of the source block to the kill ring."
  214. (interactive)
  215. (let* ((info (or info (org-babel-get-src-block-info)))
  216. (lang (first info))
  217. (body (second info))
  218. (params (third info))
  219. (session (cdr (assoc :session params))))
  220. (unless (member lang org-babel-interpreters)
  221. (error "Language is not in `org-babel-interpreters': %s" lang))
  222. ;; copy body to the kill ring
  223. (with-temp-buffer (insert (org-babel-trim body)) (copy-region-as-kill (point-min) (point-max)))
  224. ;; if called with a prefix argument, then process header arguments
  225. (if arg (funcall (intern (concat "org-babel-prep-session:" lang)) session params))
  226. ;; just to the session using pop-to-buffer
  227. (pop-to-buffer (funcall (intern (format "org-babel-%s-initiate-session" lang)) session))
  228. (move-end-of-line 1)))
  229. (defun org-babel-open-src-block-result (&optional re-run)
  230. "If `point' is on a src block then open the results of the
  231. source code block, otherwise return nil. With optional prefix
  232. argument RE-RUN the source-code block is evaluated even if
  233. results already exist."
  234. (interactive "P")
  235. (when (org-babel-get-src-block-info)
  236. (save-excursion
  237. ;; go to the results, if there aren't any then run the block
  238. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  239. (progn (org-babel-execute-src-block)
  240. (org-babel-where-is-src-block-result))))
  241. (move-end-of-line 1) (forward-char 1)
  242. ;; open the results
  243. (if (looking-at org-bracket-link-regexp)
  244. ;; file results
  245. (org-open-at-point)
  246. (let ((results (org-babel-read-result)))
  247. (flet ((echo-res (result)
  248. (if (stringp result) result (format "%S" result))))
  249. (pop-to-buffer (get-buffer-create "org-babel-results"))
  250. (delete-region (point-min) (point-max))
  251. (if (listp results)
  252. ;; table result
  253. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  254. ;; scalar result
  255. (insert (echo-res results))))))
  256. t)))
  257. (defun org-babel-execute-buffer (&optional arg)
  258. "Replace EVAL snippets in the entire buffer."
  259. (interactive "P")
  260. (save-excursion
  261. (goto-char (point-min))
  262. (while (re-search-forward org-babel-src-block-regexp nil t)
  263. (goto-char (match-beginning 0))
  264. (org-babel-execute-src-block arg)
  265. (goto-char (match-end 0)))))
  266. (defun org-babel-execute-subtree (&optional arg)
  267. "Replace EVAL snippets in the entire subtree."
  268. (interactive "P")
  269. (save-excursion
  270. (org-narrow-to-subtree)
  271. (org-babel-execute-buffer)
  272. (widen)))
  273. (defun org-babel-get-src-block-info (&optional header-vars-only)
  274. "Get information of the current source block.
  275. Returns a list
  276. (language body header-arguments-alist switches name function-args).
  277. Unless HEADER-VARS-ONLY is non-nil, any variable
  278. references provided in 'function call style' (i.e. in a
  279. parenthesised argument list following the src block name) are
  280. added to the header-arguments-alist."
  281. (let ((case-fold-search t) head info args)
  282. (if (setq head (org-babel-where-is-src-block-head))
  283. (save-excursion
  284. (goto-char head)
  285. (setq info (org-babel-parse-src-block-match))
  286. (forward-line -1)
  287. (when (looking-at (concat org-babel-source-name-regexp
  288. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  289. (setq info (append info (list (org-babel-clean-text-properties (match-string 2)))))
  290. ;; Note that e.g. "name()" and "name( )" result in ((:var . "")).
  291. ;; We maintain that behaviour, and the resulting non-nil sixth
  292. ;; element is relied upon in org-babel-exp-code to detect a functional-style
  293. ;; block in those cases. However, "name" without any
  294. ;; parentheses would result in the same thing, so we
  295. ;; explicitly avoid that.
  296. (if (setq args (match-string 4))
  297. (setq info (append info (list (mapcar (lambda (ref) (cons :var ref))
  298. (org-babel-ref-split-args args))))))
  299. (unless header-vars-only
  300. (setf (third info)
  301. (org-babel-merge-params (sixth info) (third info)))))
  302. info)
  303. (if (save-excursion ;; inline source block
  304. (re-search-backward "[ \f\t\n\r\v]" nil t)
  305. (looking-at org-babel-inline-src-block-regexp))
  306. (org-babel-parse-inline-src-block-match)
  307. nil)))) ;; indicate that no source block was found
  308. (defun org-babel-sha1-hash (&optional info)
  309. (interactive)
  310. (let* ((info (or info (org-babel-get-src-block-info)))
  311. (hash (sha1 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
  312. (third info) ":")
  313. (second info)))))
  314. (when (interactive-p) (message hash))
  315. hash))
  316. (defun org-babel-result-hash (&optional info)
  317. (org-babel-where-is-src-block-result nil info)
  318. (org-babel-clean-text-properties (match-string 3)))
  319. (defun org-babel-hide-hash ()
  320. "Hide the hash in the current results line. Only the initial
  321. `org-babel-hash-show' characters of the hash will remain
  322. visible."
  323. (org-add-to-invisibility-spec '(org-babel-hide-hash . t))
  324. (save-excursion
  325. (when (and (re-search-forward org-babel-result-regexp nil t)
  326. (match-string 3))
  327. (let* ((start (match-beginning 3))
  328. (hide-start (+ org-babel-hash-show start))
  329. (end (match-end 3))
  330. (hash (match-string 3))
  331. ov1 ov2)
  332. (setq ov1 (org-make-overlay start hide-start))
  333. (setq ov2 (org-make-overlay hide-start end))
  334. (org-overlay-put ov2 'invisible 'org-babel-hide-hash)
  335. (org-overlay-put ov1 'babel-hash hash)))))
  336. (defun org-babel-hide-all-hashes ()
  337. "Hide the hash in the current buffer. Only the initial
  338. `org-babel-hash-show' characters of each hash will remain
  339. visible. This function should be called as part of the
  340. `org-mode-hook'."
  341. (save-excursion
  342. (while (re-search-forward org-babel-result-regexp nil t)
  343. (goto-char (match-beginning 0))
  344. (org-babel-hide-hash)
  345. (goto-char (match-end 0)))))
  346. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  347. (defun org-babel-hash-at-point (&optional point)
  348. "Return the value of the hash at `point'. The hash is also
  349. added as the last element of the kill ring. This can be called
  350. with C-c C-c."
  351. (interactive)
  352. (let ((hash (car (delq nil (mapcar
  353. (lambda (ol) (org-overlay-get ol 'babel-hash))
  354. (org-overlays-at (or point (point))))))))
  355. (when hash (kill-new hash) (message hash))))
  356. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  357. (defun org-babel-result-hide-spec ()
  358. (org-add-to-invisibility-spec '(org-babel-hide-result . t)))
  359. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  360. (defvar org-babel-hide-result-overlays nil
  361. "Overlays hiding results.")
  362. (defun org-babel-result-hide-all ()
  363. "Fold all results in the current buffer."
  364. (interactive)
  365. (org-babel-show-result-all)
  366. (save-excursion
  367. (while (re-search-forward org-babel-result-regexp nil t)
  368. (save-excursion (goto-char (match-beginning 0))
  369. (org-babel-hide-result-toggle-maybe)))))
  370. (defun org-babel-show-result-all ()
  371. "Unfold all results in the current buffer."
  372. (mapc 'org-delete-overlay org-babel-hide-result-overlays)
  373. (setq org-babel-hide-result-overlays nil))
  374. (defun org-babel-hide-result-toggle-maybe ()
  375. "Toggle visibility of result at point."
  376. (interactive)
  377. (let ((case-fold-search t))
  378. (if (save-excursion
  379. (beginning-of-line 1)
  380. (looking-at org-babel-result-regexp))
  381. (progn (org-babel-hide-result-toggle)
  382. t) ;; to signal that we took action
  383. nil))) ;; to signal that we did not
  384. (defun org-babel-hide-result-toggle (&optional force)
  385. "Toggle the visibility of the current result."
  386. (interactive)
  387. (save-excursion
  388. (beginning-of-line)
  389. (if (re-search-forward org-babel-result-regexp nil t)
  390. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  391. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  392. ov)
  393. (if (memq t (mapcar (lambda (overlay)
  394. (eq (org-overlay-get overlay 'invisible)
  395. 'org-babel-hide-result))
  396. (org-overlays-at start)))
  397. (if (or (not force) (eq force 'off))
  398. (mapc (lambda (ov)
  399. (when (member ov org-babel-hide-result-overlays)
  400. (setq org-babel-hide-result-overlays
  401. (delq ov org-babel-hide-result-overlays)))
  402. (when (eq (org-overlay-get ov 'invisible)
  403. 'org-babel-hide-result)
  404. (org-delete-overlay ov)))
  405. (org-overlays-at start)))
  406. (setq ov (org-make-overlay start end))
  407. (org-overlay-put ov 'invisible 'org-babel-hide-result)
  408. ;; make the block accessible to isearch
  409. (org-overlay-put
  410. ov 'isearch-open-invisible
  411. (lambda (ov)
  412. (when (member ov org-babel-hide-result-overlays)
  413. (setq org-babel-hide-result-overlays
  414. (delq ov org-babel-hide-result-overlays)))
  415. (when (eq (org-overlay-get ov 'invisible)
  416. 'org-babel-hide-result)
  417. (org-delete-overlay ov))))
  418. (push ov org-babel-hide-result-overlays)))
  419. (error "Not looking at a result line"))))
  420. ;; org-tab-after-check-for-cycling-hook
  421. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  422. ;; Remove overlays when changing major mode
  423. (add-hook 'org-mode-hook
  424. (lambda () (org-add-hook 'change-major-mode-hook
  425. 'org-babel-show-result-all 'append 'local)))
  426. (defmacro org-babel-map-source-blocks (file &rest body)
  427. "Evaluate BODY forms on each source-block in FILE."
  428. (declare (indent 1))
  429. `(let ((visited-p (get-buffer (file-name-nondirectory ,file))))
  430. (save-window-excursion
  431. (find-file ,file) (goto-char (point-min))
  432. (while (re-search-forward org-babel-src-block-regexp nil t)
  433. (goto-char (match-beginning 0))
  434. (save-match-data ,@body)
  435. (goto-char (match-end 0))))
  436. (unless visited-p (kill-buffer (file-name-nondirectory file)))))
  437. (defun org-babel-params-from-properties ()
  438. "Return an association list of any source block params which
  439. may be specified in the properties of the current outline entry."
  440. (save-match-data
  441. (delq nil
  442. (mapcar
  443. (lambda (header-arg)
  444. (let ((val (or (condition-case nil
  445. (org-entry-get (point) header-arg 'selective)
  446. (error nil))
  447. (cdr (assoc header-arg org-file-properties)))))
  448. (when val
  449. ;; (message "param-from-property %s=%s" header-arg val) ;; debugging statement
  450. (cons (intern (concat ":" header-arg)) val))))
  451. '("exports" "results" "session" "tangle" "var")))))
  452. (defun org-babel-parse-src-block-match ()
  453. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  454. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  455. (switches (match-string 2))
  456. (body (org-babel-clean-text-properties (match-string 4)))
  457. (preserve-indentation (or org-src-preserve-indentation
  458. (string-match "-i\\>" switches))))
  459. (list lang
  460. ;; get src block body removing properties, protective commas, and indentation
  461. (with-temp-buffer
  462. (save-match-data
  463. (insert (org-babel-strip-protective-commas body))
  464. (unless preserve-indentation (org-do-remove-indentation))
  465. (buffer-string)))
  466. (org-babel-merge-params
  467. org-babel-default-header-args
  468. (org-babel-params-from-properties)
  469. (if (boundp lang-headers) (eval lang-headers) nil)
  470. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) ""))))
  471. switches)))
  472. (defun org-babel-parse-inline-src-block-match ()
  473. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  474. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  475. (list lang
  476. (org-babel-strip-protective-commas (org-babel-clean-text-properties (match-string 5)))
  477. (org-babel-merge-params
  478. org-babel-default-inline-header-args
  479. (org-babel-params-from-properties)
  480. (if (boundp lang-headers) (eval lang-headers) nil)
  481. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 4) "")))))))
  482. (defun org-babel-parse-header-arguments (arg-string)
  483. "Parse a string of header arguments returning an alist."
  484. (if (> (length arg-string) 0)
  485. (delq nil
  486. (mapcar
  487. (lambda (arg)
  488. (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)" arg)
  489. (cons (intern (concat ":" (match-string 1 arg)))
  490. (let ((raw (org-babel-chomp (match-string 2 arg))))
  491. (if (org-babel-number-p raw) raw (eval (org-babel-read raw)))))
  492. (cons (intern (concat ":" arg)) nil)))
  493. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  494. (defun org-babel-process-params (params)
  495. "Parse params and resolve references.
  496. Return a list (session vars result-params result-type)."
  497. (let* ((session (cdr (assoc :session params)))
  498. (vars (org-babel-ref-variables params))
  499. (result-params (split-string (or (cdr (assoc :results params)) "")))
  500. (result-type (cond ((member "output" result-params) 'output)
  501. ((member "value" result-params) 'value)
  502. (t 'value))))
  503. (list session vars result-params result-type)))
  504. (defun org-babel-where-is-src-block-head ()
  505. "Return the point at the beginning of the current source
  506. block. Specifically at the beginning of the #+BEGIN_SRC line.
  507. If the point is not on a source block then return nil."
  508. (let ((initial (point)) top bottom)
  509. (or
  510. (save-excursion ;; on a source name line
  511. (beginning-of-line 1)
  512. (and (looking-at org-babel-source-name-regexp) (forward-line 1)
  513. (looking-at org-babel-src-block-regexp)
  514. (point)))
  515. (save-excursion ;; on a #+begin_src line
  516. (beginning-of-line 1)
  517. (and (looking-at org-babel-src-block-regexp)
  518. (point)))
  519. (save-excursion ;; inside a src block
  520. (and
  521. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  522. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  523. (< top initial) (< initial bottom)
  524. (goto-char top) (move-beginning-of-line 1)
  525. (looking-at org-babel-src-block-regexp)
  526. (point))))))
  527. (defun org-babel-goto-named-source-block (&optional name)
  528. "Go to a named source-code block."
  529. (interactive "ssource-block name: ")
  530. (let ((point (org-babel-find-named-block name)))
  531. (if point
  532. ;; taken from `org-open-at-point'
  533. (progn (goto-char point) (org-show-context))
  534. (message "source-code block '%s' not found in this buffer" name))))
  535. (defun org-babel-find-named-block (name)
  536. "Find a named source-code block.
  537. Return the location of the source block identified by source
  538. NAME, or nil if no such block exists. Set match data according to
  539. org-babel-named-src-block-regexp."
  540. (save-excursion
  541. (let ((case-fold-search t)
  542. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  543. (goto-char (point-min))
  544. (when (or (re-search-forward regexp nil t)
  545. (re-search-backward regexp nil t))
  546. (match-beginning 0)))))
  547. (defun org-babel-find-named-result (name)
  548. "Return the location of the result named NAME in the current
  549. buffer or nil if no such result exists."
  550. (save-excursion
  551. (goto-char (point-min))
  552. (when (re-search-forward
  553. (concat org-babel-result-regexp "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  554. (move-beginning-of-line 0) (point))))
  555. (defun org-babel-where-is-src-block-result (&optional insert info hash)
  556. "Return the point at the beginning of the result of the current
  557. source block. Specifically at the beginning of the results line.
  558. If no result exists for this block then create a results line
  559. following the source block."
  560. (save-excursion
  561. (let* ((on-lob-line (progn (beginning-of-line 1)
  562. (looking-at org-babel-lob-one-liner-regexp)))
  563. (name (if on-lob-line (first (org-babel-lob-get-info))
  564. (fifth (or info (org-babel-get-src-block-info)))))
  565. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  566. (when head (goto-char head))
  567. (or (and name (org-babel-find-named-result name))
  568. (and (or on-lob-line (re-search-forward "#\\+end_src" nil t))
  569. (progn (move-end-of-line 1)
  570. (if (eobp) (insert "\n") (forward-char 1))
  571. (setq end (point))
  572. (or (and (not name)
  573. (progn ;; unnamed results line already exists
  574. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  575. (move-beginning-of-line 1)
  576. (looking-at (concat org-babel-result-regexp "\n"))))
  577. ;; or (with optional insert) back up and make one ourselves
  578. (when insert
  579. (goto-char end)
  580. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n"))
  581. (insert (concat "#+results" (if hash (concat "["hash"]"))
  582. ":"(if name (concat " " name)) "\n"))
  583. (move-beginning-of-line 0)
  584. (if hash (org-babel-hide-hash)) t)))
  585. (point))))))
  586. (defun org-babel-read-result ()
  587. "Read the result at `point' into emacs-lisp."
  588. (let ((case-fold-search t) result-string)
  589. (cond
  590. ((org-at-table-p) (org-babel-read-table))
  591. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  592. ((looking-at ": ")
  593. (setq result-string
  594. (org-babel-trim
  595. (mapconcat (lambda (line) (if (and (> (length line) 1)
  596. (string= ": " (substring line 0 2)))
  597. (substring line 2)
  598. line))
  599. (split-string
  600. (buffer-substring (point) (org-babel-result-end)) "[\r\n]+")
  601. "\n")))
  602. (or (org-babel-number-p result-string) result-string))
  603. ((looking-at org-babel-result-regexp)
  604. (save-excursion (forward-line 1) (org-babel-read-result))))))
  605. (defun org-babel-read-table ()
  606. "Read the table at `point' into emacs-lisp."
  607. (mapcar (lambda (row)
  608. (if (and (symbolp row) (equal row 'hline)) row
  609. (mapcar #'org-babel-read row)))
  610. (org-table-to-lisp)))
  611. (defun org-babel-insert-result (result &optional result-params info hash)
  612. "Insert RESULT into the current buffer after the end of the
  613. current source block. With optional argument RESULT-PARAMS
  614. controls insertion of results in the org-mode file.
  615. RESULT-PARAMS can take the following values...
  616. replace - (default option) insert results after the source block
  617. replacing any previously inserted results
  618. silent -- no results are inserted
  619. file ---- the results are interpreted as a file path, and are
  620. inserted into the buffer using the Org-mode file syntax
  621. raw ----- results are added directly to the org-mode file. This
  622. is a good option if you code block will output org-mode
  623. formatted text.
  624. org ----- this is the same as the 'raw' option
  625. html ---- results are added inside of a #+BEGIN_HTML block. This
  626. is a good option if you code block will output html
  627. formatted text.
  628. latex --- results are added inside of a #+BEGIN_LATEX block.
  629. This is a good option if you code block will output
  630. latex formatted text.
  631. code ---- the results are extracted in the syntax of the source
  632. code of the language being evaluated and are added
  633. inside of a #+BEGIN_SRC block with the source-code
  634. language set appropriately."
  635. (if (stringp result)
  636. (progn
  637. (setq result (org-babel-clean-text-properties result))
  638. (when (member "file" result-params)
  639. (setq result (org-babel-result-to-file result))))
  640. (unless (listp result) (setq result (format "%S" result))))
  641. (if (and result-params (member "replace" result-params)
  642. (not (member "silent" result-params)))
  643. (org-babel-remove-result info))
  644. (if (= (length result) 0)
  645. (if (member "value" result-params)
  646. (message "No result returned by source block")
  647. (message "Source block produced no output"))
  648. (if (and result-params (member "silent" result-params))
  649. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  650. result)
  651. (when (and (stringp result) ;; ensure results end in a newline
  652. (not (or (string-equal (substring result -1) "\n")
  653. (string-equal (substring result -1) "\r"))))
  654. (setq result (concat result "\n")))
  655. (save-excursion
  656. (let ((existing-result (org-babel-where-is-src-block-result t info hash))
  657. (results-switches (cdr (assoc :results_switches (third info)))))
  658. (when existing-result (goto-char existing-result) (forward-line 1))
  659. (setq results-switches
  660. (if results-switches (concat " " results-switches) ""))
  661. (cond
  662. ;; assume the result is a table if it's not a string
  663. ((not (stringp result))
  664. (insert (concat (orgtbl-to-orgtbl
  665. (if (and (listp (car result))
  666. (listp (cdr (car result))))
  667. result (list result))
  668. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  669. (forward-line -1) (org-cycle))
  670. ((member "file" result-params)
  671. (insert result))
  672. ((member "html" result-params)
  673. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n" results-switches result)))
  674. ((member "latex" result-params)
  675. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n" results-switches result)))
  676. ((member "code" result-params)
  677. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n" lang results-switches result)))
  678. ((or (member "raw" result-params) (member "org" result-params))
  679. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  680. (t
  681. (org-babel-examplize-region
  682. (point) (progn (insert result) (point)) results-switches)))))
  683. (message "finished"))))
  684. (defun org-babel-result-to-org-string (result)
  685. "Return RESULT as a string in org-mode format. This function
  686. relies on `org-babel-insert-result'."
  687. (with-temp-buffer (org-babel-insert-result result) (buffer-string)))
  688. (defun org-babel-remove-result (&optional info)
  689. "Remove the result of the current source block."
  690. (interactive)
  691. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  692. (when location
  693. (save-excursion
  694. (goto-char location) (setq start (point)) (forward-line 1)
  695. (delete-region start (org-babel-result-end))))))
  696. (defun org-babel-result-end ()
  697. "Return the point at the end of the current set of results"
  698. (save-excursion
  699. (if (org-at-table-p)
  700. (progn (goto-char (org-table-end)) (point))
  701. (let ((case-fold-search t))
  702. (cond
  703. ((looking-at "#\\+begin_latex")
  704. (search-forward "#+end_latex" nil t)
  705. (forward-line 1))
  706. ((looking-at "#\\+begin_html")
  707. (search-forward "#+end_html" nil t)
  708. (forward-line 1))
  709. ((looking-at "#\\+begin_example")
  710. (search-forward "#+end_example" nil t)
  711. (forward-line 1))
  712. ((looking-at "#\\+begin_src")
  713. (search-forward "#+end_src" nil t)
  714. (forward-line 1))
  715. (t (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  716. (forward-line 1))))))
  717. (point))))
  718. (defun org-babel-result-to-file (result)
  719. "Return an `org-mode' link with the path being the value or
  720. RESULT, and the display being the `file-name-nondirectory' if
  721. non-nil."
  722. (concat "[[file:" result "]]"))
  723. (defun org-babel-examplize-region (beg end &optional results-switches)
  724. "Comment out region using the ': ' org example quote."
  725. (interactive "*r")
  726. (let ((size (abs (- (line-number-at-pos end)
  727. (line-number-at-pos beg)))))
  728. (save-excursion
  729. (cond ((= size 0)
  730. (error "This should be impossible: a newline was appended to result if missing"))
  731. ((< size org-babel-min-lines-for-block-output)
  732. (goto-char beg)
  733. (dotimes (n size)
  734. (move-beginning-of-line 1) (insert ": ") (forward-line 1)))
  735. (t
  736. (goto-char beg)
  737. (insert (if results-switches
  738. (format "#+begin_example%s\n" results-switches)
  739. "#+begin_example\n"))
  740. (forward-char (- end beg))
  741. (insert "#+end_example\n"))))))
  742. (defun org-babel-merge-params (&rest plists)
  743. "Combine all parameter association lists in PLISTS. Later
  744. elements of PLISTS override the values of previous element. This
  745. takes into account some special considerations for certain
  746. parameters when merging lists."
  747. (let ((results-exclusive-groups
  748. '(("file" "vector" "table" "scalar" "raw" "org" "html" "latex" "code" "pp")
  749. ("replace" "silent")
  750. ("output" "value")))
  751. (exports-exclusive-groups
  752. '(("code" "results" "both" "none")))
  753. params results exports tangle cache vars var ref)
  754. (flet ((e-merge (exclusive-groups &rest result-params)
  755. ;; maintain exclusivity of mutually exclusive parameters
  756. (let (output)
  757. (mapc (lambda (new-params)
  758. (mapc (lambda (new-param)
  759. (mapc (lambda (exclusive-group)
  760. (when (member new-param exclusive-group)
  761. (mapcar (lambda (excluded-param)
  762. (setq output (delete excluded-param output)))
  763. exclusive-group)))
  764. exclusive-groups)
  765. (setq output (org-uniquify (cons new-param output))))
  766. new-params))
  767. result-params)
  768. output)))
  769. (mapc (lambda (plist)
  770. (mapc (lambda (pair)
  771. (case (car pair)
  772. (:var
  773. ;; we want only one specification per variable
  774. (when (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=[ \t]*\\([^\f\n\r\v]+\\)$" (cdr pair))
  775. ;; TODO: When is this not true?
  776. (setq var (intern (match-string 1 (cdr pair)))
  777. ref (match-string 2 (cdr pair))
  778. vars (cons (cons var ref) (assq-delete-all var vars)))))
  779. (:results
  780. (setq results
  781. (e-merge results-exclusive-groups results (split-string (cdr pair)))))
  782. (:file
  783. (when (cdr pair)
  784. (setq results (e-merge results-exclusive-groups results '("file")))
  785. (unless (or (member "both" exports) (member "none" exports))
  786. (setq exports (e-merge exports-exclusive-groups exports '("results"))))
  787. (setq params (cons pair (assq-delete-all (car pair) params)))))
  788. (:exports
  789. (setq exports (e-merge exports-exclusive-groups
  790. exports (split-string (cdr pair)))))
  791. (:tangle
  792. (setq tangle (e-merge '(("yes" "no"))
  793. tangle (split-string (cdr pair)))))
  794. (:cache (setq cache t)) (:nocache (setq cache nil))
  795. (t ;; replace: this covers e.g. :session
  796. (setq params (cons pair (assq-delete-all (car pair) params))))))
  797. plist))
  798. plists))
  799. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  800. (while vars (setq params (cons (cons :var (pop vars)) params)))
  801. (cons (if cache (list :cache) (list :nocache))
  802. (cons (cons :tangle (mapconcat 'identity tangle " "))
  803. (cons (cons :exports (mapconcat 'identity exports " "))
  804. (cons (cons :results (mapconcat 'identity results " "))
  805. params))))))
  806. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  807. "This function expands Noweb style references in the body of
  808. the current source-code block. For example the following
  809. reference would be replaced with the body of the source-code
  810. block named 'example-block' (assuming the '#' character starts a
  811. comment) .
  812. # <<example-block>>
  813. This function must be called from inside of the buffer containing
  814. the source-code block which holds BODY.
  815. In addition the following syntax can be used to insert the
  816. results of evaluating the source-code block named 'example-block'.
  817. # <<example-block()>>
  818. Any optional arguments can be passed to example-block by placing
  819. the arguments inside the parenthesis following the convention
  820. defined by `org-babel-lob'. For example
  821. # <<example-block(a=9)>>
  822. would set the value of argument \"a\" equal to \"9\". Note that
  823. these arguments are not evaluated in the current source-code block but are passed literally to the \"example-block\"."
  824. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  825. (info (or info (org-babel-get-src-block-info)))
  826. (lang (first info))
  827. (body (second info))
  828. (new-body "") index source-name evaluate)
  829. (flet ((nb-add (text)
  830. (setq new-body (concat new-body text))))
  831. (with-temp-buffer
  832. (insert body) (goto-char (point-min))
  833. (funcall (intern (concat (or (and (cdr (assoc lang org-src-lang-modes))
  834. (symbol-name
  835. (cdr (assoc lang org-src-lang-modes))))
  836. lang) "-mode")))
  837. (setq index (point))
  838. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  839. (save-match-data (setf source-name (match-string 1)))
  840. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  841. ;; add interval to new-body (removing noweb reference)
  842. (goto-char (match-beginning 0))
  843. (nb-add (buffer-substring index (point)))
  844. (goto-char (match-end 0))
  845. (setq index (point))
  846. (nb-add (save-excursion
  847. (set-buffer parent-buffer)
  848. (if evaluate
  849. (let ((raw (org-babel-ref-resolve-reference
  850. source-name nil)))
  851. (if (stringp raw) raw (format "%S" raw)))
  852. (let ((point (org-babel-find-named-block source-name)))
  853. (if point
  854. (save-excursion
  855. (goto-char point)
  856. (org-babel-trim (org-babel-expand-noweb-references
  857. (org-babel-get-src-block-info))))
  858. ;; optionally raise an error if named source-block doesn't exist
  859. (if (member lang org-babel-noweb-error-langs)
  860. (error
  861. "<<%s>> could not be resolved (see `org-babel-noweb-error-langs')"
  862. source-name)
  863. "")))))))
  864. (nb-add (buffer-substring index (point-max)))))
  865. new-body))
  866. (defun org-babel-clean-text-properties (text)
  867. "Strip all properties from text return."
  868. (set-text-properties 0 (length text) nil text) text)
  869. (defun org-babel-strip-protective-commas (body)
  870. "Strip protective commas from bodies of source blocks."
  871. (replace-regexp-in-string "^,#" "#" body))
  872. (defun org-babel-read (cell)
  873. "Convert the string value of CELL to a number if appropriate.
  874. Otherwise if cell looks like lisp (meaning it starts with a
  875. \"(\" or a \"'\") then read it as lisp, otherwise return it
  876. unmodified as a string.
  877. This is taken almost directly from `org-read-prop'."
  878. (if (and (stringp cell) (not (equal cell "")))
  879. (or (org-babel-number-p cell)
  880. (if (or (equal "(" (substring cell 0 1))
  881. (equal "'" (substring cell 0 1)))
  882. (read cell)
  883. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  884. cell))
  885. (defun org-babel-number-p (string)
  886. "Return t if STRING represents a number"
  887. (if (and (string-match "^-?[[:digit:]]*\\.?[[:digit:]]*$" string)
  888. (= (match-end 0) (length string)))
  889. (string-to-number string)))
  890. (defun org-babel-import-elisp-from-file (file-name)
  891. "Read the results located at FILE-NAME into an elisp table. If
  892. the table is trivial, then return it as a scalar."
  893. (let (result)
  894. (with-temp-buffer
  895. (condition-case nil
  896. (progn
  897. (org-table-import file-name nil)
  898. (delete-file file-name)
  899. (setq result (mapcar (lambda (row)
  900. (mapcar #'org-babel-string-read row))
  901. (org-table-to-lisp))))
  902. (error nil)))
  903. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  904. (if (consp (car result))
  905. (if (null (cdr (car result)))
  906. (caar result)
  907. result)
  908. (car result))
  909. result)))
  910. (defun org-babel-string-read (cell)
  911. "Strip nested \"s from around strings in exported R values."
  912. (org-babel-read (or (and (stringp cell)
  913. (string-match "\\\"\\(.+\\)\\\"" cell)
  914. (match-string 1 cell))
  915. cell)))
  916. (defun org-babel-reverse-string (string)
  917. (apply 'string (reverse (string-to-list string))))
  918. (defun org-babel-chomp (string &optional regexp)
  919. "Remove any trailing space or carriage returns characters from
  920. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  921. overwritten by specifying a regexp as a second argument."
  922. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  923. (while (and (> (length string) 0) (string-match regexp (substring string -1)))
  924. (setq string (substring string 0 -1)))
  925. string))
  926. (defun org-babel-trim (string &optional regexp)
  927. "Like `org-babel-chomp' only it runs on both the front and back of the string"
  928. (org-babel-chomp (org-babel-reverse-string
  929. (org-babel-chomp (org-babel-reverse-string string) regexp)) regexp))
  930. (provide 'org-babel)
  931. ;;; org-babel.el ends here