org-babel.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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"))
  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-min-lines-for-block-output 10
  77. "If number of lines of output is equal to or exceeds this
  78. value, the output is placed in a
  79. #+begin_example...#+end_example block. Otherwise the output is
  80. marked as literal by inserting colons at the starts of the
  81. lines. This variable only takes effect if the :results output
  82. option is in effect.")
  83. (defvar org-babel-noweb-error-langs nil
  84. "List of language for which errors should be raised when the
  85. source code block satisfying a noweb reference in this language
  86. can not be resolved.")
  87. (defun org-babel-named-src-block-regexp-for-name (name)
  88. "Regexp used to match named src block."
  89. (concat "#\\+srcname:[ \t]*" (regexp-quote name) "[ \t\n]*"
  90. (substring org-babel-src-block-regexp 1)))
  91. (defun org-babel-set-interpreters (var value)
  92. (set-default var value)
  93. (setq org-babel-src-block-regexp
  94. (concat "^[ \t]*#\\+begin_src[ \t]+\\(" ;; (1) lang
  95. (mapconcat 'regexp-quote value "\\|")
  96. "\\)[ \t]*"
  97. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)" ;; (2) switches
  98. "\\([^\n]*\\)\n" ;; (3) header arguments
  99. "\\([^\000]+?\\)#\\+end_src")) ;; (4) body
  100. (setq org-babel-inline-src-block-regexp
  101. (concat "[ \f\t\n\r\v]\\(src_" ;; (1) replacement target
  102. "\\(" ;; (2) lang
  103. (mapconcat 'regexp-quote value "\\|")
  104. "\\)"
  105. "\\(\\|\\[\\(.*\\)\\]\\)" ;; (3,4) (unused, headers)
  106. "{\\([^\f\n\r\v]+\\)}" ;; (5) body
  107. "\\)")))
  108. (defun org-babel-add-interpreter (interpreter)
  109. "Add INTERPRETER to `org-babel-interpreters' and update
  110. `org-babel-src-block-regexp' appropriately."
  111. (unless (member interpreter org-babel-interpreters)
  112. (setq org-babel-interpreters (cons interpreter org-babel-interpreters))
  113. (org-babel-set-interpreters 'org-babel-interpreters org-babel-interpreters)))
  114. (defcustom org-babel-interpreters '()
  115. "Interpreters allows for evaluation tags.
  116. This is a list of program names (as strings) that can evaluate code and
  117. insert the output into an Org-mode buffer. Valid choices are
  118. R Evaluate R code
  119. emacs-lisp Evaluate Emacs Lisp code and display the result
  120. sh Pass command to the shell and display the result
  121. perl The perl interpreter
  122. python The python interpreter
  123. ruby The ruby interpreter
  124. The source block regexp `org-babel-src-block-regexp' is updated
  125. when a new interpreter is added to this list through the
  126. customize interface. To add interpreters to this variable from
  127. lisp code use the `org-babel-add-interpreter' function."
  128. :group 'org-babel
  129. :set 'org-babel-set-interpreters
  130. :type '(set :greedy t
  131. (const "R")
  132. (const "emacs-lisp")
  133. (const "sh")
  134. (const "perl")
  135. (const "python")
  136. (const "ruby")))
  137. ;;; functions
  138. (defun org-babel-execute-src-block (&optional arg info params)
  139. "Execute the current source code block, and dump the results
  140. into the buffer immediately following the block. Results are
  141. commented by `org-toggle-fixed-width-section'. With optional
  142. prefix don't dump results into buffer but rather return the
  143. results in raw elisp (this is useful for automated execution of a
  144. source block).
  145. Optionally supply a value for INFO in the form returned by
  146. `org-babel-get-src-block-info'.
  147. Optionally supply a value for PARAMS which will be merged with
  148. the header arguments specified at the source code block."
  149. (interactive)
  150. ;; (message "supplied params=%S" params) ;; debugging
  151. (let* ((info (or info (org-babel-get-src-block-info)))
  152. (lang (first info))
  153. (params (setf (third info) (org-babel-merge-params (third info) params)))
  154. (body (setf (second info)
  155. (if (assoc :noweb params)
  156. (org-babel-expand-noweb-references info) (second info))))
  157. (result-params (split-string (or (cdr (assoc :results params)) "")))
  158. (result-type (cond ((member "output" result-params) 'output)
  159. ((member "value" result-params) 'value)
  160. (t 'value)))
  161. (cmd (intern (concat "org-babel-execute:" lang)))
  162. result)
  163. ;; (message "params=%S" params) ;; debugging
  164. (unless (member lang org-babel-interpreters)
  165. (error "Language is not in `org-babel-interpreters': %s" lang))
  166. (when arg (setq result-params (cons "silent" result-params)))
  167. (setq result (funcall cmd body params))
  168. (if (eq result-type 'value)
  169. (setq result (if (and (or (member "vector" result-params)
  170. (member "table" result-params))
  171. (not (listp result)))
  172. (list (list result))
  173. result)))
  174. (org-babel-insert-result result result-params info)
  175. result))
  176. (defun org-babel-load-in-session (&optional arg info)
  177. "Load the body of the current source-code block. Evaluate the
  178. header arguments for the source block before entering the
  179. session. After loading the body this pops open the session."
  180. (interactive)
  181. (let* ((info (or info (org-babel-get-src-block-info)))
  182. (lang (first info))
  183. (body (second info))
  184. (params (third info))
  185. (session (cdr (assoc :session params))))
  186. (unless (member lang org-babel-interpreters)
  187. (error "Language is not in `org-babel-interpreters': %s" lang))
  188. ;; if called with a prefix argument, then process header arguments
  189. (pop-to-buffer (funcall (intern (concat "org-babel-load-session:" lang)) session body params))
  190. (move-end-of-line 1)))
  191. (defun org-babel-pop-to-session (&optional arg info)
  192. "Pop to the session of the current source-code block. If
  193. called with a prefix argument then evaluate the header arguments
  194. for the source block before entering the session. Copy the body
  195. of the source block to the kill ring."
  196. (interactive)
  197. (let* ((info (or info (org-babel-get-src-block-info)))
  198. (lang (first info))
  199. (body (second info))
  200. (params (third info))
  201. (session (cdr (assoc :session params))))
  202. (unless (member lang org-babel-interpreters)
  203. (error "Language is not in `org-babel-interpreters': %s" lang))
  204. ;; copy body to the kill ring
  205. (with-temp-buffer (insert (org-babel-trim body)) (copy-region-as-kill (point-min) (point-max)))
  206. ;; if called with a prefix argument, then process header arguments
  207. (if arg (funcall (intern (concat "org-babel-prep-session:" lang)) session params))
  208. ;; just to the session using pop-to-buffer
  209. (pop-to-buffer (funcall (intern (format "org-babel-%s-initiate-session" lang)) session))
  210. (move-end-of-line 1)))
  211. (defun org-babel-open-src-block-result (&optional re-run)
  212. "If `point' is on a src block then open the results of the
  213. source code block, otherwise return nil. With optional prefix
  214. argument RE-RUN the source-code block is evaluated even if
  215. results already exist."
  216. (interactive "P")
  217. (when (org-babel-get-src-block-info)
  218. (save-excursion
  219. ;; go to the results, if there aren't any then run the block
  220. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  221. (progn (org-babel-execute-src-block)
  222. (org-babel-where-is-src-block-result))))
  223. (move-end-of-line 1) (forward-char 1)
  224. ;; open the results
  225. (if (looking-at org-bracket-link-regexp)
  226. ;; file results
  227. (org-open-at-point)
  228. (let ((results (org-babel-read-result)))
  229. (flet ((echo-res (result)
  230. (if (stringp result) result (format "%S" result))))
  231. (pop-to-buffer (get-buffer-create "org-babel-results"))
  232. (delete-region (point-min) (point-max))
  233. (if (listp results)
  234. ;; table result
  235. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  236. ;; scalar result
  237. (insert (echo-res results))))))
  238. t)))
  239. (defun org-babel-execute-buffer (&optional arg)
  240. "Replace EVAL snippets in the entire buffer."
  241. (interactive "P")
  242. (save-excursion
  243. (goto-char (point-min))
  244. (while (re-search-forward org-babel-src-block-regexp nil t)
  245. (goto-char (match-beginning 0))
  246. (org-babel-execute-src-block arg)
  247. (goto-char (match-end 0)))))
  248. (defun org-babel-execute-subtree (&optional arg)
  249. "Replace EVAL snippets in the entire subtree."
  250. (interactive "P")
  251. (save-excursion
  252. (org-narrow-to-subtree)
  253. (org-babel-execute-buffer)
  254. (widen)))
  255. (defun org-babel-get-src-block-info (&optional header-vars-only)
  256. "Get information of the current source block.
  257. Returns a list
  258. (language body header-arguments-alist switches name function-args).
  259. Unless HEADER-VARS-ONLY is non-nil, any variable
  260. references provided in 'function call style' (i.e. in a
  261. parenthesised argument list following the src block name) are
  262. added to the header-arguments-alist."
  263. (let ((case-fold-search t) head info args)
  264. (if (setq head (org-babel-where-is-src-block-head))
  265. (save-excursion
  266. (goto-char head)
  267. (setq info (org-babel-parse-src-block-match))
  268. (forward-line -1)
  269. (when (looking-at "#\\+srcname:[ \t]*\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  270. (setq info (append info (list (org-babel-clean-text-properties (match-string 1)))))
  271. ;; Note that e.g. "name()" and "name( )" result in ((:var . "")).
  272. ;; We maintain that behaviour, and the resulting non-nil sixth
  273. ;; element is relied upon in org-babel-exp-code to detect a functional-style
  274. ;; block in those cases. However, "name" without any
  275. ;; parentheses would result in the same thing, so we
  276. ;; explicitly avoid that.
  277. (if (setq args (match-string 3))
  278. (setq info (append info (list (mapcar (lambda (ref) (cons :var ref))
  279. (org-babel-ref-split-args args))))))
  280. (unless header-vars-only
  281. (setf (third info)
  282. (org-babel-merge-params (sixth info) (third info)))))
  283. info)
  284. (if (save-excursion ;; inline source block
  285. (re-search-backward "[ \f\t\n\r\v]" nil t)
  286. (looking-at org-babel-inline-src-block-regexp))
  287. (org-babel-parse-inline-src-block-match)
  288. nil)))) ;; indicate that no source block was found
  289. (defmacro org-babel-map-source-blocks (file &rest body)
  290. "Evaluate BODY forms on each source-block in FILE."
  291. (declare (indent 1))
  292. `(let ((visited-p (get-buffer (file-name-nondirectory ,file))))
  293. (save-window-excursion
  294. (find-file ,file) (goto-char (point-min))
  295. (while (re-search-forward org-babel-src-block-regexp nil t)
  296. (goto-char (match-beginning 0))
  297. (save-match-data ,@body)
  298. (goto-char (match-end 0))))
  299. (unless visited-p (kill-buffer (file-name-nondirectory file)))))
  300. (defun org-babel-params-from-properties ()
  301. "Return an association list of any source block params which
  302. may be specified in the properties of the current outline entry."
  303. (save-match-data
  304. (delq nil
  305. (mapcar
  306. (lambda (header-arg)
  307. (let ((val (or (org-entry-get (point) header-arg 'selective)
  308. (cdr (assoc header-arg org-file-properties)))))
  309. (when val
  310. ;; (message "param-from-property %s=%s" header-arg val) ;; debugging statement
  311. (cons (intern (concat ":" header-arg)) val))))
  312. '("exports" "results" "session" "tangle" "var")))))
  313. (defun org-babel-parse-src-block-match ()
  314. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  315. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  316. (switches (match-string 2))
  317. (body (org-babel-clean-text-properties (match-string 4)))
  318. (preserve-indentation (or org-src-preserve-indentation
  319. (string-match "-i\\>" switches))))
  320. (list lang
  321. ;; get src block body removing properties, protective commas, and indentation
  322. (with-temp-buffer
  323. (save-match-data
  324. (insert (org-babel-strip-protective-commas body))
  325. (unless preserve-indentation (org-do-remove-indentation))
  326. (buffer-string)))
  327. (org-babel-merge-params
  328. org-babel-default-header-args
  329. (org-babel-params-from-properties)
  330. (if (boundp lang-headers) (eval lang-headers) nil)
  331. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) ""))))
  332. switches)))
  333. (defun org-babel-parse-inline-src-block-match ()
  334. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  335. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  336. (list lang
  337. (org-babel-strip-protective-commas (org-babel-clean-text-properties (match-string 5)))
  338. (org-babel-merge-params
  339. org-babel-default-inline-header-args
  340. (org-babel-params-from-properties)
  341. (if (boundp lang-headers) (eval lang-headers) nil)
  342. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 4) "")))))))
  343. (defun org-babel-parse-header-arguments (arg-string)
  344. "Parse a string of header arguments returning an alist."
  345. (if (> (length arg-string) 0)
  346. (delq nil
  347. (mapcar
  348. (lambda (arg)
  349. (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)" arg)
  350. (cons (intern (concat ":" (match-string 1 arg)))
  351. (org-babel-chomp (match-string 2 arg)))
  352. (cons (intern (concat ":" arg)) nil)))
  353. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  354. (defun org-babel-process-params (params)
  355. "Parse params and resolve references.
  356. Return a list (session vars result-params result-type)."
  357. (let* ((session (cdr (assoc :session params)))
  358. (vars (org-babel-ref-variables params))
  359. (result-params (split-string (or (cdr (assoc :results params)) "")))
  360. (result-type (cond ((member "output" result-params) 'output)
  361. ((member "value" result-params) 'value)
  362. (t 'value))))
  363. (list session vars result-params result-type)))
  364. (defun org-babel-where-is-src-block-head ()
  365. "Return the point at the beginning of the current source
  366. block. Specifically at the beginning of the #+BEGIN_SRC line.
  367. If the point is not on a source block then return nil."
  368. (let ((initial (point)) top bottom)
  369. (or
  370. (save-excursion ;; on a #+srcname: line
  371. (beginning-of-line 1)
  372. (and (looking-at "#\\+srcname") (forward-line 1)
  373. (looking-at org-babel-src-block-regexp)
  374. (point)))
  375. (save-excursion ;; on a #+begin_src line
  376. (beginning-of-line 1)
  377. (and (looking-at org-babel-src-block-regexp)
  378. (point)))
  379. (save-excursion ;; inside a src block
  380. (and
  381. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  382. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  383. (< top initial) (< initial bottom)
  384. (goto-char top) (move-beginning-of-line 1)
  385. (looking-at org-babel-src-block-regexp)
  386. (point))))))
  387. (defun org-babel-goto-named-source-block (&optional name)
  388. "Go to a named source-code block."
  389. (interactive "ssource-block name: ")
  390. (let ((point (org-babel-find-named-block name)))
  391. (if point
  392. ;; taken from `org-open-at-point'
  393. (progn (goto-char point) (org-show-context))
  394. (message "source-code block '%s' not found in this buffer" name))))
  395. (defun org-babel-find-named-block (name)
  396. "Find a named source-code block.
  397. Return the location of the source block identified by
  398. #+srcname NAME, or nil if no such block exists. Set match data
  399. according to org-babel-named-src-block-regexp."
  400. (save-excursion
  401. (let ((case-fold-search t)
  402. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  403. (goto-char (point-min))
  404. (when (or (re-search-forward regexp nil t)
  405. (re-search-backward regexp nil t))
  406. (match-beginning 0)))))
  407. (defun org-babel-find-named-result (name)
  408. "Return the location of the result named NAME in the current
  409. buffer or nil if no such result exists."
  410. (save-excursion
  411. (goto-char (point-min))
  412. (when (re-search-forward ;; ellow end-of-buffer in following regexp?
  413. (concat "#\\+resname:[ \t]*" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  414. (move-beginning-of-line 0) (point))))
  415. (defun org-babel-where-is-src-block-result (&optional insert info)
  416. "Return the point at the beginning of the result of the current
  417. source block. Specifically at the beginning of the #+RESNAME:
  418. line. If no result exists for this block then create a
  419. #+RESNAME: line following the source block."
  420. (save-excursion
  421. (let* ((on-lob-line (progn (beginning-of-line 1)
  422. (looking-at org-babel-lob-one-liner-regexp)))
  423. (name (if on-lob-line (first (org-babel-lob-get-info))
  424. (fifth (or info (org-babel-get-src-block-info)))))
  425. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  426. (when head (goto-char head))
  427. (or (and name (org-babel-find-named-result name))
  428. (and (or on-lob-line (re-search-forward "#\\+end_src" nil t))
  429. (progn (move-end-of-line 1)
  430. (if (eobp) (insert "\n") (forward-char 1))
  431. (setq end (point))
  432. (or (and (not name)
  433. (progn ;; either the unnamed #+resname: line already exists
  434. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  435. (move-beginning-of-line 1) (looking-at "#\\+resname:\n")))
  436. ;; or (with optional insert) we need to back up and make one ourselves
  437. (when insert
  438. (goto-char end) (open-line 2) (forward-char 1)
  439. (insert (concat "#+resname:" (if name (concat " " name)) "\n"))
  440. (move-beginning-of-line 0) t)))
  441. (point))))))
  442. (defun org-babel-read-result ()
  443. "Read the result at `point' into emacs-lisp."
  444. (let ((case-fold-search t) result-string)
  445. (cond
  446. ((org-at-table-p) (org-babel-read-table))
  447. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  448. ((looking-at ": ")
  449. (setq result-string
  450. (org-babel-trim
  451. (mapconcat (lambda (line) (if (and (> (length line) 1)
  452. (string= ": " (substring line 0 2)))
  453. (substring line 2)
  454. line))
  455. (split-string
  456. (buffer-substring (point) (org-babel-result-end)) "[\r\n]+")
  457. "\n")))
  458. (or (org-babel-number-p result-string) result-string))
  459. ((looking-at "^#\\+RESNAME:")
  460. (save-excursion (forward-line 1) (org-babel-read-result))))))
  461. (defun org-babel-read-table ()
  462. "Read the table at `point' into emacs-lisp."
  463. (mapcar (lambda (row)
  464. (if (and (symbolp row) (equal row 'hline)) row
  465. (mapcar #'org-babel-read row)))
  466. (org-table-to-lisp)))
  467. (defun org-babel-insert-result (result &optional insert info)
  468. "Insert RESULT into the current buffer after the end of the
  469. current source block. With optional argument INSERT controls
  470. insertion of results in the org-mode file. INSERT can take the
  471. following values...
  472. replace - (default option) insert results after the source block
  473. replacing any previously inserted results
  474. silent -- no results are inserted
  475. file ---- the results are interpreted as a file path, and are
  476. inserted into the buffer using the Org-mode file syntax
  477. raw ----- results are added directly to the org-mode file. This
  478. is a good option if you code block will output org-mode
  479. formatted text.
  480. org ----- this is the same as the 'raw' option
  481. html ---- results are added inside of a #+BEGIN_HTML block. This
  482. is a good option if you code block will output html
  483. formatted text.
  484. latex --- results are added inside of a #+BEGIN_LATEX block.
  485. This is a good option if you code block will output
  486. latex formatted text.
  487. code ---- the results are extracted in the syntax of the source
  488. code of the language being evaluated and are added
  489. inside of a #+BEGIN_SRC block with the source-code
  490. language set appropriately."
  491. (if (stringp result)
  492. (progn
  493. (setq result (org-babel-clean-text-properties result))
  494. (if (member "file" insert) (setq result (org-babel-result-to-file result))))
  495. (unless (listp result) (setq result (format "%S" result))))
  496. (if (and insert (member "replace" insert) (not (member "silent" insert)))
  497. (org-babel-remove-result info))
  498. (if (= (length result) 0)
  499. (if (member "value" result-params)
  500. (message "No result returned by source block")
  501. (message "Source block produced no output"))
  502. (if (and insert (member "silent" insert))
  503. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result))) result)
  504. (when (and (stringp result) ;; ensure results end in a newline
  505. (not (or (string-equal (substring result -1) "\n")
  506. (string-equal (substring result -1) "\r"))))
  507. (setq result (concat result "\n")))
  508. (save-excursion
  509. (let ((existing-result (org-babel-where-is-src-block-result t info))
  510. (results-switches (cdr (assoc :results_switches (third info)))))
  511. (when existing-result (goto-char existing-result) (forward-line 1))
  512. (setq results-switches (if results-switches (concat " " results-switches) ""))
  513. (cond
  514. ;; assume the result is a table if it's not a string
  515. ((not (stringp result))
  516. (insert (concat (orgtbl-to-orgtbl
  517. (if (and (listp (car result)) (listp (cdr (car result))))
  518. result (list result))
  519. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  520. (forward-line -1) (org-cycle))
  521. ((member "file" insert)
  522. (insert result))
  523. ((member "html" insert)
  524. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n" results-switches result)))
  525. ((member "latex" insert)
  526. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n" results-switches result)))
  527. ((member "code" insert)
  528. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n" lang results-switches result)))
  529. ((or (member "raw" insert) (member "org" insert))
  530. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  531. (t
  532. (org-babel-examplize-region (point) (progn (insert result) (point)) results-switches)))))
  533. (message "finished"))))
  534. (defun org-babel-result-to-org-string (result)
  535. "Return RESULT as a string in org-mode format. This function
  536. relies on `org-babel-insert-result'."
  537. (with-temp-buffer (org-babel-insert-result result) (buffer-string)))
  538. (defun org-babel-remove-result (&optional info)
  539. "Remove the result of the current source block."
  540. (interactive)
  541. (save-excursion
  542. (goto-char (org-babel-where-is-src-block-result t info)) (forward-line 1)
  543. (delete-region (point) (org-babel-result-end))))
  544. (defun org-babel-result-end ()
  545. "Return the point at the end of the current set of results"
  546. (save-excursion
  547. (if (org-at-table-p)
  548. (progn (goto-char (org-table-end)) (point))
  549. (let ((case-fold-search t))
  550. (cond
  551. ((looking-at "#\\+begin_latex")
  552. (search-forward "#+end_latex" nil t)
  553. (forward-line 1))
  554. ((looking-at "#\\+begin_html")
  555. (search-forward "#+end_html" nil t)
  556. (forward-line 1))
  557. ((looking-at "#\\+begin_example")
  558. (search-forward "#+end_example" nil t)
  559. (forward-line 1))
  560. ((looking-at "#\\+begin_src")
  561. (search-forward "#+end_src" nil t)
  562. (forward-line 1))
  563. (t (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  564. (forward-line 1))))))
  565. (point))))
  566. (defun org-babel-result-to-file (result)
  567. "Return an `org-mode' link with the path being the value or
  568. RESULT, and the display being the `file-name-nondirectory' if
  569. non-nil."
  570. (concat "[[file:" result "]]"))
  571. (defun org-babel-examplize-region (beg end &optional results-switches)
  572. "Comment out region using the ': ' org example quote."
  573. (interactive "*r")
  574. (let ((size (abs (- (line-number-at-pos end)
  575. (line-number-at-pos beg)))))
  576. (save-excursion
  577. (cond ((= size 0)
  578. (error "This should be impossible: a newline was appended to result if missing")
  579. (let ((result (buffer-substring beg end)))
  580. (delete-region beg end)
  581. (insert (concat ": " result))))
  582. ((< size org-babel-min-lines-for-block-output)
  583. (goto-char beg)
  584. (dotimes (n size)
  585. (move-beginning-of-line 1) (insert ": ") (forward-line 1)))
  586. (t
  587. (goto-char beg)
  588. (insert (if results-switches
  589. (format "#+begin_example%s\n" results-switches)
  590. "#+begin_example\n"))
  591. (forward-char (- end beg))
  592. (insert "#+end_example\n"))))))
  593. (defun org-babel-merge-params (&rest plists)
  594. "Combine all parameter association lists in PLISTS. Later
  595. elements of PLISTS override the values of previous element. This
  596. takes into account some special considerations for certain
  597. parameters when merging lists."
  598. (let ((results-exclusive-groups
  599. '(("file" "vector" "table" "scalar" "raw" "org" "html" "latex" "code" "pp")
  600. ("replace" "silent")
  601. ("output" "value")))
  602. (exports-exclusive-groups
  603. '(("code" "results" "both" "none")))
  604. params results exports tangle vars var ref)
  605. (flet ((e-merge (exclusive-groups &rest result-params)
  606. ;; maintain exclusivity of mutually exclusive parameters
  607. (let (output)
  608. (mapc (lambda (new-params)
  609. (mapc (lambda (new-param)
  610. (mapc (lambda (exclusive-group)
  611. (when (member new-param exclusive-group)
  612. (mapcar (lambda (excluded-param)
  613. (setq output (delete excluded-param output)))
  614. exclusive-group)))
  615. exclusive-groups)
  616. (setq output (org-uniquify (cons new-param output))))
  617. new-params))
  618. result-params)
  619. output)))
  620. (mapc (lambda (plist)
  621. (mapc (lambda (pair)
  622. (case (car pair)
  623. (:var
  624. ;; we want only one specification per variable
  625. (when (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=[ \t]*\\([^\f\n\r\v]+\\)$" (cdr pair))
  626. ;; TODO: When is this not true?
  627. (setq var (intern (match-string 1 (cdr pair)))
  628. ref (match-string 2 (cdr pair))
  629. vars (cons (cons var ref) (assq-delete-all var vars)))))
  630. (:results
  631. (setq results
  632. (e-merge results-exclusive-groups results (split-string (cdr pair)))))
  633. (:file
  634. (when (cdr pair)
  635. (setq results (e-merge results-exclusive-groups results '("file")))
  636. (unless (or (member "both" exports) (member "none" exports))
  637. (setq exports (e-merge exports-exclusive-groups exports '("results"))))
  638. (setq params (cons pair (assq-delete-all (car pair) params)))))
  639. (:exports
  640. (setq exports (e-merge exports-exclusive-groups
  641. exports (split-string (cdr pair)))))
  642. (:tangle
  643. (setq tangle (e-merge '(("yes" "no"))
  644. tangle (split-string (cdr pair)))))
  645. (t ;; replace: this covers e.g. :session
  646. (setq params (cons pair (assq-delete-all (car pair) params))))))
  647. plist))
  648. plists))
  649. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  650. (while vars (setq params (cons (cons :var (pop vars)) params)))
  651. (cons (cons :tangle (mapconcat 'identity tangle " "))
  652. (cons (cons :exports (mapconcat 'identity exports " "))
  653. (cons (cons :results (mapconcat 'identity results " "))
  654. params)))))
  655. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  656. "This function expands Noweb style references in the body of
  657. the current source-code block. For example the following
  658. reference would be replaced with the body of the source-code
  659. block named 'example-block' (assuming the '#' character starts a
  660. comment) .
  661. # <<example-block>>
  662. This function must be called from inside of the buffer containing
  663. the source-code block which holds BODY.
  664. In addition the following syntax can be used to insert the
  665. results of evaluating the source-code block named 'example-block'.
  666. # <<example-block()>>
  667. Any optional arguments can be passed to example-block by placing
  668. the arguments inside the parenthesis following the convention
  669. defined by `org-babel-lob'. For example
  670. # <<example-block(a=9)>>
  671. would set the value of argument \"a\" equal to \"9\". Note that
  672. these arguments are not evaluated in the current source-code block but are passed literally to the \"example-block\"."
  673. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  674. (info (or info (org-babel-get-src-block-info)))
  675. (lang (first info))
  676. (body (second info))
  677. (new-body "") index source-name evaluate)
  678. (flet ((nb-add (text)
  679. (setq new-body (concat new-body text))))
  680. (with-temp-buffer
  681. (insert body) (goto-char (point-min))
  682. (funcall (intern (concat (or (and (cdr (assoc lang org-src-lang-modes))
  683. (symbol-name
  684. (cdr (assoc lang org-src-lang-modes))))
  685. lang) "-mode")))
  686. (setq index (point))
  687. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  688. (save-match-data (setf source-name (match-string 1)))
  689. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  690. ;; add interval to new-body (removing noweb reference)
  691. (goto-char (match-beginning 0))
  692. (nb-add (buffer-substring index (point)))
  693. (goto-char (match-end 0))
  694. (setq index (point))
  695. (nb-add (save-excursion
  696. (set-buffer parent-buffer)
  697. (if evaluate
  698. (let ((raw (org-babel-ref-resolve-reference
  699. source-name nil)))
  700. (if (stringp raw) raw (format "%S" raw)))
  701. (let ((point (org-babel-find-named-block source-name)))
  702. (if point
  703. (save-excursion
  704. (goto-char point)
  705. (org-babel-trim (org-babel-expand-noweb-references
  706. (org-babel-get-src-block-info))))
  707. ;; optionally raise an error if named source-block doesn't exist
  708. (if (member lang org-babel-noweb-error-langs)
  709. (error
  710. "<<%s>> could not be resolved (see `org-babel-noweb-error-langs')"
  711. source-name)
  712. "")))))))
  713. (nb-add (buffer-substring index (point-max)))))
  714. new-body))
  715. (defun org-babel-clean-text-properties (text)
  716. "Strip all properties from text return."
  717. (set-text-properties 0 (length text) nil text) text)
  718. (defun org-babel-strip-protective-commas (body)
  719. "Strip protective commas from bodies of source blocks."
  720. (replace-regexp-in-string "^,#" "#" body))
  721. (defun org-babel-read (cell)
  722. "Convert the string value of CELL to a number if appropriate.
  723. Otherwise if cell looks like lisp (meaning it starts with a
  724. \"(\" or a \"'\") then read it as lisp, otherwise return it
  725. unmodified as a string.
  726. This is taken almost directly from `org-read-prop'."
  727. (if (and (stringp cell) (not (equal cell "")))
  728. (or (org-babel-number-p cell)
  729. (if (or (equal "(" (substring cell 0 1))
  730. (equal "'" (substring cell 0 1)))
  731. (read cell)
  732. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  733. cell))
  734. (defun org-babel-number-p (string)
  735. "Return t if STRING represents a number"
  736. (if (and (string-match "^-?[[:digit:]]*\\.?[[:digit:]]*$" string)
  737. (= (match-end 0) (length string)))
  738. (string-to-number string)))
  739. (defun org-babel-import-elisp-from-file (file-name)
  740. "Read the results located at FILE-NAME into an elisp table. If
  741. the table is trivial, then return it as a scalar."
  742. (let (result)
  743. (with-temp-buffer
  744. (condition-case nil
  745. (progn
  746. (org-table-import file-name nil)
  747. (delete-file file-name)
  748. (setq result (mapcar (lambda (row)
  749. (mapcar #'org-babel-string-read row))
  750. (org-table-to-lisp))))
  751. (error nil)))
  752. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  753. (if (consp (car result))
  754. (if (null (cdr (car result)))
  755. (caar result)
  756. result)
  757. (car result))
  758. result)))
  759. (defun org-babel-string-read (cell)
  760. "Strip nested \"s from around strings in exported R values."
  761. (org-babel-read (or (and (stringp cell)
  762. (string-match "\\\"\\(.+\\)\\\"" cell)
  763. (match-string 1 cell))
  764. cell)))
  765. (defun org-babel-reverse-string (string)
  766. (apply 'string (reverse (string-to-list string))))
  767. (defun org-babel-chomp (string &optional regexp)
  768. "Remove any trailing space or carriage returns characters from
  769. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  770. overwritten by specifying a regexp as a second argument."
  771. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  772. (while (and (> (length string) 0) (string-match regexp (substring string -1)))
  773. (setq string (substring string 0 -1)))
  774. string))
  775. (defun org-babel-trim (string &optional regexp)
  776. "Like `org-babel-chomp' only it runs on both the front and back of the string"
  777. (org-babel-chomp (org-babel-reverse-string
  778. (org-babel-chomp (org-babel-reverse-string string) regexp)) regexp))
  779. (provide 'org-babel)
  780. ;;; org-babel.el ends here