org-babel.el 34 KB

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