org-babel.el 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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. 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 (member "vector" result-params) (not (listp result)))
  238. (list (list result))
  239. result))
  240. (defun org-babel-execute-buffer (&optional arg)
  241. "Replace EVAL snippets in the entire buffer."
  242. (interactive "P")
  243. (save-excursion
  244. (goto-char (point-min))
  245. (while (re-search-forward org-babel-src-block-regexp nil t)
  246. (goto-char (match-beginning 0))
  247. (org-babel-execute-src-block arg)
  248. (goto-char (match-end 0)))))
  249. (defun org-babel-execute-subtree (&optional arg)
  250. "Replace EVAL snippets in the entire subtree."
  251. (interactive "P")
  252. (save-excursion
  253. (org-narrow-to-subtree)
  254. (org-babel-execute-buffer)
  255. (widen)))
  256. (defun org-babel-get-src-block-name ()
  257. "Return the name of the current source block if one exists.
  258. This function is analogous to org-babel-lob-get-info. For both
  259. functions, after they are called, (match-string 1) matches the
  260. function name, and (match-string 3) matches the function
  261. arguments inside the parentheses. I think perhaps these functions
  262. should be renamed to bring out this similarity, perhaps involving
  263. the word 'call'.
  264. Currently the function `org-babel-get-src-block-function-args'
  265. relies on the match-data from a match in this function. I think
  266. splitting a match and the use of it's data is bad form, and we
  267. should re-work these two functions, perhaps combining them into
  268. one function which returns more data than just the name. [Eric]"
  269. (let ((case-fold-search t)
  270. (head (org-babel-where-is-src-block-head)))
  271. (if head
  272. (save-excursion
  273. (goto-char head)
  274. (if (save-excursion
  275. (forward-line -1)
  276. ;; the second match of this regexp is used later to
  277. ;; find arguments in the "functional" style, where
  278. ;; they are passed as part of the source name line
  279. (looking-at "#\\+srcname:[ \t]*\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  280. (org-babel-clean-text-properties (match-string 1)))))))
  281. (defun org-babel-get-src-block-info ()
  282. "Return the information of the current source block as a list
  283. of the following form. (language body header-arguments-alist)"
  284. (let ((case-fold-search t) head)
  285. (if (setq head (org-babel-where-is-src-block-head))
  286. (save-excursion (goto-char head) (org-babel-parse-src-block-match))
  287. (if (save-excursion ;; inline source block
  288. (re-search-backward "[ \f\t\n\r\v]" nil t)
  289. (forward-char 1)
  290. (looking-at org-babel-inline-src-block-regexp))
  291. (org-babel-parse-inline-src-block-match)
  292. nil)))) ;; indicate that no source block was found
  293. (defun org-babel-get-src-block-function-args ()
  294. (when (org-babel-get-src-block-name)
  295. (mapcar (lambda (ref) (cons :var ref))
  296. (org-babel-ref-split-args (match-string 3)))))
  297. (defmacro org-babel-map-source-blocks (file &rest body)
  298. "Evaluate BODY forms on each source-block in FILE."
  299. (declare (indent 1))
  300. `(let ((visited-p (get-buffer (file-name-nondirectory ,file))))
  301. (save-window-excursion
  302. (find-file ,file) (goto-char (point-min))
  303. (while (re-search-forward org-babel-src-block-regexp nil t)
  304. (goto-char (match-beginning 0))
  305. (save-match-data ,@body)
  306. (goto-char (match-end 0))))
  307. (unless visited-p (kill-buffer (file-name-nondirectory file)))))
  308. (defun org-babel-params-from-properties ()
  309. "Return an association list of any source block params which
  310. may be specified in the properties of the current outline entry."
  311. (save-match-data
  312. (delq nil
  313. (mapcar
  314. (lambda (header-arg)
  315. (let ((val (org-entry-get (point) header-arg)))
  316. (when val
  317. ;; (message "param-from-property %s=%s" header-arg val) ;; debugging statement
  318. (cons (intern (concat ":" header-arg)) val))))
  319. '("exports" "results" "session" "tangle" "var")))))
  320. (defun org-babel-parse-src-block-match ()
  321. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  322. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  323. (body (org-babel-clean-text-properties (match-string 4)))
  324. (preserve-indentation org-src-preserve-indentation))
  325. (list lang
  326. ;; get src block body removing properties, protective commas, and indentation
  327. (with-temp-buffer
  328. (save-match-data
  329. (insert (org-babel-strip-protective-commas body))
  330. (unless preserve-indentation (org-do-remove-indentation))
  331. (buffer-string)))
  332. (org-babel-merge-params
  333. org-babel-default-header-args
  334. (org-babel-params-from-properties)
  335. (if (boundp lang-headers) (eval lang-headers) nil)
  336. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) "")))))))
  337. (defun org-babel-parse-inline-src-block-match ()
  338. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  339. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  340. (list lang
  341. (org-babel-strip-protective-commas (org-babel-clean-text-properties (match-string 4)))
  342. (org-babel-merge-params
  343. org-babel-default-inline-header-args
  344. (org-babel-params-from-properties)
  345. (if (boundp lang-headers) (eval lang-headers) nil)
  346. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) "")))))))
  347. (defun org-babel-parse-header-arguments (arg-string)
  348. "Parse a string of header arguments returning an alist."
  349. (if (> (length arg-string) 0)
  350. (delq nil
  351. (mapcar
  352. (lambda (arg)
  353. (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)" arg)
  354. (cons (intern (concat ":" (match-string 1 arg)))
  355. (org-babel-chomp (match-string 2 arg)))
  356. (cons (intern (concat ":" arg)) nil)))
  357. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  358. (defun org-babel-process-params (params)
  359. "Parse params and resolve references.
  360. Return a list (session vars result-params result-type). These are
  361. made available to the org-babel-execute:LANG functions via
  362. multiple-value-bind."
  363. (let* ((session (cdr (assoc :session params)))
  364. (vars (org-babel-ref-variables params))
  365. (result-params (split-string (or (cdr (assoc :results params)) "")))
  366. (result-type (cond ((member "output" result-params) 'output)
  367. ((member "value" result-params) 'value)
  368. (t 'value))))
  369. (list session vars result-params result-type)))
  370. (defun org-babel-where-is-src-block-head ()
  371. "Return the point at the beginning of the current source
  372. block. Specifically at the beginning of the #+BEGIN_SRC line.
  373. If the point is not on a source block then return nil."
  374. (let ((initial (point)) top bottom)
  375. (or
  376. (save-excursion ;; on a #+srcname: line
  377. (beginning-of-line 1)
  378. (and (looking-at "#\\+srcname") (forward-line 1)
  379. (looking-at org-babel-src-block-regexp)
  380. (point)))
  381. (save-excursion ;; on a #+begin_src line
  382. (beginning-of-line 1)
  383. (and (looking-at org-babel-src-block-regexp)
  384. (point)))
  385. (save-excursion ;; inside a src block
  386. (and
  387. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  388. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  389. (< top initial) (< initial bottom)
  390. (goto-char top) (move-beginning-of-line 1)
  391. (looking-at org-babel-src-block-regexp)
  392. (point))))))
  393. (defun org-babel-goto-named-source-block (&optional name)
  394. "Go to a named source-code block."
  395. (interactive "ssource-block name: ")
  396. (let ((point (org-babel-find-named-block name)))
  397. (if point
  398. ;; taken from `org-open-at-point'
  399. (progn (goto-char point) (org-show-context))
  400. (message "source-code block '%s' not found in this buffer" name))))
  401. (defun org-babel-find-named-block (name)
  402. "Find a named source-code block.
  403. Return the location of the source block identified by
  404. #+srcname NAME, or nil if no such block exists. Set match data
  405. according to org-babel-named-src-block-regexp."
  406. (save-excursion
  407. (let ((case-fold-search t)
  408. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  409. (goto-char (point-min))
  410. (when (or (re-search-forward regexp nil t)
  411. (re-search-backward regexp nil t))
  412. (match-beginning 0)))))
  413. (defun org-babel-find-named-result (name)
  414. "Return the location of the result named NAME in the current
  415. buffer or nil if no such result exists."
  416. (save-excursion
  417. (goto-char (point-min))
  418. (when (re-search-forward ;; ellow end-of-buffer in following regexp?
  419. (concat "#\\+resname:[ \t]*" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  420. (move-beginning-of-line 0) (point))))
  421. (defun org-babel-where-is-src-block-result (&optional insert)
  422. "Return the point at the beginning of the result of the current
  423. source block. Specifically at the beginning of the #+RESNAME:
  424. line. If no result exists for this block then create a
  425. #+RESNAME: line following the source block."
  426. (save-excursion
  427. (let* ((on-lob-line (progn (beginning-of-line 1)
  428. (looking-at org-babel-lob-one-liner-regexp)))
  429. (name (if on-lob-line (first (org-babel-lob-get-info)) (org-babel-get-src-block-name)))
  430. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  431. (when head (goto-char head))
  432. (or (and name (org-babel-find-named-result name))
  433. (and (or on-lob-line (re-search-forward "#\\+end_src" nil t))
  434. (progn (move-end-of-line 1)
  435. (if (eobp) (insert "\n") (forward-char 1))
  436. (setq end (point))
  437. (or (and (not name)
  438. (progn ;; either the unnamed #+resname: line already exists
  439. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  440. (move-beginning-of-line 1) (looking-at "#\\+resname:\n")))
  441. ;; or (with optional insert) we need to back up and make one ourselves
  442. (when insert
  443. (goto-char end) (open-line 2) (forward-char 1)
  444. (insert (concat "#+resname:" (if name (concat " " name)) "\n"))
  445. (move-beginning-of-line 0) t)))
  446. (point))))))
  447. (defun org-babel-read-result ()
  448. "Read the result at `point' into emacs-lisp."
  449. (cond
  450. ((org-at-table-p) (org-babel-read-table))
  451. ((looking-at ": ")
  452. (let ((result-string
  453. (org-babel-trim
  454. (mapconcat (lambda (line) (if (and (> (length line) 1)
  455. (string= ": " (substring line 0 2)))
  456. (substring line 2)
  457. line))
  458. (split-string
  459. (buffer-substring (point) (org-babel-result-end)) "[\r\n]+")
  460. "\n"))))
  461. (or (org-babel-number-p result-string) result-string)))
  462. ((looking-at "^#\\+RESNAME:")
  463. (save-excursion (forward-line 1) (org-babel-read-result)))))
  464. (defun org-babel-read-table ()
  465. "Read the table at `point' into emacs-lisp."
  466. (mapcar (lambda (row)
  467. (if (and (symbolp row) (equal row 'hline)) row
  468. (mapcar #'org-babel-read row)))
  469. (org-table-to-lisp)))
  470. (defun org-babel-insert-result (result &optional insert)
  471. "Insert RESULT into the current buffer after the end of the
  472. current source block. With optional argument INSERT controls
  473. insertion of results in the org-mode file. INSERT can take the
  474. following values...
  475. replace - (default option) insert results after the source block
  476. replacing any previously inserted results
  477. silent -- no results are inserted
  478. file ---- the results are interpreted as a file path, and are
  479. inserted into the buffer using the Org-mode file syntax
  480. raw ----- results are added directly to the org-mode file. This
  481. is a good option if you code block will output org-mode
  482. formatted text.
  483. org ----- this is the same as the 'raw' option
  484. html ---- results are added inside of a #+BEGIN_HTML block. This
  485. is a good option if you code block will output html
  486. formatted text.
  487. latex --- results are added inside of a #+BEGIN_LATEX block.
  488. This is a good option if you code block will output
  489. latex formatted text."
  490. (if (stringp result)
  491. (progn
  492. (setq result (org-babel-clean-text-properties result))
  493. (if (member "file" insert) (setq result (org-babel-result-to-file result))))
  494. (unless (listp result) (setq result (format "%S" result))))
  495. (if (and insert (member "replace" insert) (not (member "silent" insert)))
  496. (org-babel-remove-result))
  497. (if (= (length result) 0)
  498. (if (member "value" result-params)
  499. (message "No result returned by source block")
  500. (message "Source block produced no output"))
  501. (if (and insert (member "silent" insert))
  502. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result))) result)
  503. (when (and (stringp result) ;; ensure results end in a newline
  504. (not (or (string-equal (substring result -1) "\n")
  505. (string-equal (substring result -1) "\r"))))
  506. (setq result (concat result "\n")))
  507. (save-excursion
  508. (let ((existing-result (org-babel-where-is-src-block-result t)))
  509. (when existing-result (goto-char existing-result) (forward-line 1)))
  510. (if (stringp result) ;; assume the result is a table if it's not a string
  511. (if (member "file" insert)
  512. (insert result)
  513. (if (member "html" insert)
  514. (insert (format "#+BEGIN_HTML\n%s#+END_HTML\n" result))
  515. (if (member "latex" insert)
  516. (insert (format "#+BEGIN_LaTeX\n%s#+END_LaTeX\n" result))
  517. (if (or (member "raw" insert) (member "org" insert))
  518. (progn (save-excursion (insert result))
  519. (if (org-at-table-p) (org-cycle)))
  520. (org-babel-examplize-region (point) (progn (insert result) (point)))))))
  521. (progn
  522. (insert
  523. (concat (orgtbl-to-orgtbl
  524. (if (and (listp (car result)) (listp (cdr (car result))))
  525. result (list result))
  526. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  527. (forward-line -1)
  528. (org-cycle))))
  529. (message "finished"))))
  530. (defun org-babel-result-to-org-string (result)
  531. "Return RESULT as a string in org-mode format. This function
  532. relies on `org-babel-insert-result'."
  533. (with-temp-buffer (org-babel-insert-result result) (buffer-string)))
  534. (defun org-babel-remove-result ()
  535. "Remove the result of the current source block."
  536. (interactive)
  537. (save-excursion
  538. (goto-char (org-babel-where-is-src-block-result t)) (forward-line 1)
  539. (delete-region (point) (org-babel-result-end))))
  540. (defun org-babel-result-end ()
  541. "Return the point at the end of the current set of results"
  542. (save-excursion
  543. (if (org-at-table-p)
  544. (progn (goto-char (org-table-end)) (point))
  545. (let ((case-fold-search t))
  546. (cond
  547. ((looking-at "#\\+begin_latex")
  548. (search-forward "#+end_latex" nil t)
  549. (forward-line 1))
  550. ((looking-at "#\\+begin_html")
  551. (search-forward "#+end_html" nil t)
  552. (forward-line 1))
  553. ((looking-at "#\\+begin_example")
  554. (search-forward "#+end_example" nil t)
  555. (forward-line 1))
  556. (t (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  557. (forward-line 1))))))
  558. (point))))
  559. (defun org-babel-result-to-file (result)
  560. "Return an `org-mode' link with the path being the value or
  561. RESULT, and the display being the `file-name-nondirectory' if
  562. non-nil."
  563. (concat "[[file:" result "]]"))
  564. (defun org-babel-examplize-region (beg end)
  565. "Comment out region using the ': ' org example quote."
  566. (interactive "*r")
  567. (let ((size (abs (- (line-number-at-pos end)
  568. (line-number-at-pos beg)))))
  569. (save-excursion
  570. (cond ((= size 0)
  571. (error "This should be impossible: a newline was appended to result if missing")
  572. (let ((result (buffer-substring beg end)))
  573. (delete-region beg end)
  574. (insert (concat ": " result))))
  575. ((< size org-babel-min-lines-for-block-output)
  576. (goto-char beg)
  577. (dotimes (n size)
  578. (move-beginning-of-line 1) (insert ": ") (forward-line 1)))
  579. (t
  580. (goto-char beg)
  581. (insert "#+begin_example\n")
  582. (forward-char (- end beg))
  583. (insert "#+end_example\n"))))))
  584. (defun org-babel-merge-params (&rest plists)
  585. "Combine all parameter association lists in PLISTS. Later
  586. elements of PLISTS override the values of previous element. This
  587. takes into account some special considerations for certain
  588. parameters when merging lists."
  589. (let ((results-exclusive-groups
  590. '(("file" "vector" "scalar" "raw" "org" "html" "latex")
  591. ("replace" "silent")
  592. ("output" "value")))
  593. params results exports tangle vars var ref)
  594. (flet ((e-merge (exclusive-groups &rest result-params)
  595. ;; maintain exclusivity of mutually exclusive parameters
  596. (let (output)
  597. (mapc (lambda (new-params)
  598. (mapc (lambda (new-param)
  599. (mapc (lambda (exclusive-group)
  600. (when (member new-param exclusive-group)
  601. (mapcar (lambda (excluded-param)
  602. (setq output (delete excluded-param output)))
  603. exclusive-group)))
  604. exclusive-groups)
  605. (setq output (org-uniquify (cons new-param output))))
  606. new-params))
  607. result-params)
  608. output)))
  609. (mapc (lambda (plist)
  610. (mapc (lambda (pair)
  611. (case (car pair)
  612. (:var
  613. ;; we want only one specification per variable
  614. (when (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=[ \t]*\\([^\f\n\r\v]+\\)$" (cdr pair))
  615. ;; TODO: When is this not true?
  616. (setq var (intern (match-string 1 (cdr pair)))
  617. ref (match-string 2 (cdr pair))
  618. vars (cons (cons var ref) (assq-delete-all var vars)))))
  619. (:results
  620. (setq results
  621. (e-merge results-exclusive-groups results (split-string (cdr pair)))))
  622. (:file
  623. (when (cdr pair)
  624. (setq results (e-merge results-exclusive-groups results '("file")))
  625. (setq params (cons pair (assq-delete-all (car pair) params)))))
  626. (:exports
  627. (setq exports (e-merge '(("code" "results" "both" "none"))
  628. exports (split-string (cdr pair)))))
  629. (:tangle
  630. (setq tangle (e-merge '(("yes" "no"))
  631. tangle (split-string (cdr pair)))))
  632. (t ;; replace: this covers e.g. :session
  633. (setq params (cons pair (assq-delete-all (car pair) params))))))
  634. plist))
  635. plists))
  636. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  637. (while vars (setq params (cons (cons :var (pop vars)) params)))
  638. (cons (cons :tangle (mapconcat 'identity tangle " "))
  639. (cons (cons :exports (mapconcat 'identity exports " "))
  640. (cons (cons :results (mapconcat 'identity results " "))
  641. params)))))
  642. (defun org-babel-clean-text-properties (text)
  643. "Strip all properties from text return."
  644. (set-text-properties 0 (length text) nil text) text)
  645. (defun org-babel-strip-protective-commas (body)
  646. "Strip protective commas from bodies of source blocks."
  647. (replace-regexp-in-string "^,#" "#" body))
  648. (defun org-babel-read (cell)
  649. "Convert the string value of CELL to a number if appropriate.
  650. Otherwise if cell looks like lisp (meaning it starts with a
  651. \"(\" or a \"'\") then read it as lisp, otherwise return it
  652. unmodified as a string.
  653. This is taken almost directly from `org-read-prop'."
  654. (if (and (stringp cell) (not (equal cell "")))
  655. (or (org-babel-number-p cell)
  656. (if (or (equal "(" (substring cell 0 1))
  657. (equal "'" (substring cell 0 1)))
  658. (read cell)
  659. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  660. cell))
  661. (defun org-babel-number-p (string)
  662. "Return t if STRING represents a number"
  663. (if (and (string-match "^-?[[:digit:]]*\\.?[[:digit:]]*$" string)
  664. (= (match-end 0) (length string)))
  665. (string-to-number string)))
  666. (defun org-babel-import-elisp-from-file (file-name)
  667. "Read the results located at FILE-NAME into an elisp table. If
  668. the table is trivial, then return it as a scalar."
  669. (let (result)
  670. (with-temp-buffer
  671. (condition-case nil
  672. (progn
  673. (org-table-import file-name nil)
  674. (delete-file file-name)
  675. (setq result (mapcar (lambda (row)
  676. (mapcar #'org-babel-string-read row))
  677. (org-table-to-lisp))))
  678. (error nil)))
  679. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  680. (if (consp (car result))
  681. (if (null (cdr (car result)))
  682. (caar result)
  683. result)
  684. (car result))
  685. result)))
  686. (defun org-babel-string-read (cell)
  687. "Strip nested \"s from around strings in exported R values."
  688. (org-babel-read (or (and (stringp cell)
  689. (string-match "\\\"\\(.+\\)\\\"" cell)
  690. (match-string 1 cell))
  691. cell)))
  692. (defun org-babel-reverse-string (string)
  693. (apply 'string (reverse (string-to-list string))))
  694. (defun org-babel-chomp (string &optional regexp)
  695. "Remove any trailing space or carriage returns characters from
  696. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  697. overwritten by specifying a regexp as a second argument."
  698. (while (and (> (length string) 0) (string-match "[ \f\t\n\r\v]" (substring string -1)))
  699. (setq string (substring string 0 -1)))
  700. string)
  701. (defun org-babel-trim (string &optional regexp)
  702. "Like `org-babel-chomp' only it runs on both the front and back of the string"
  703. (org-babel-chomp (org-babel-reverse-string
  704. (org-babel-chomp (org-babel-reverse-string string) regexp)) regexp))
  705. (provide 'org-babel)
  706. ;;; org-babel.el ends here