org-babel.el 32 KB

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