org-babel.el 37 KB

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