org-babel.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. ;;; org-babel.el --- facilitating communication between programming languages and people
  2. ;; Copyright (C) 2009 Eric Schulte, Dan Davison, Austin F. Frank
  3. ;; Author: Eric Schulte, Dan Davison, Austin F. Frank
  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 rorg.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. (defvar org-babel-default-header-args '()
  34. "Default arguments to use when evaluating a source block.")
  35. (defvar org-babel-default-inline-header-args '((:results . "silent") (:exports . "results"))
  36. "Default arguments to use when evaluating an inline source block.")
  37. (defvar org-babel-src-block-regexp nil
  38. "Regexp used to test when inside of a org-babel src-block")
  39. (defvar org-babel-inline-src-block-regexp nil
  40. "Regexp used to test when on an inline org-babel src-block")
  41. (defun org-babel-set-interpreters (var value)
  42. (set-default var value)
  43. (setq org-babel-src-block-regexp
  44. (concat "#\\+begin_src \\("
  45. (mapconcat 'regexp-quote value "\\|")
  46. "\\)[ \t]*"
  47. "\\([ \t]+\\([^\n]+\\)\\)?\n" ;; match header arguments
  48. "\\([^\000]+?\\)#\\+end_src"))
  49. (setq org-babel-inline-src-block-regexp
  50. (concat "src_\\("
  51. (mapconcat 'regexp-quote value "\\|")
  52. "\\)"
  53. "\\(\\|\\[\\(.*\\)\\]\\)"
  54. "{\\([^\n]+\\)}")))
  55. (defun org-babel-add-interpreter (interpreter)
  56. "Add INTERPRETER to `org-babel-interpreters' and update
  57. `org-babel-src-block-regexp' appropriately."
  58. (unless (member interpreter org-babel-interpreters)
  59. (setq org-babel-interpreters (cons interpreter org-babel-interpreters))
  60. (org-babel-set-interpreters 'org-babel-interpreters org-babel-interpreters)))
  61. (defcustom org-babel-interpreters '()
  62. "Interpreters allows for evaluation tags.
  63. This is a list of program names (as strings) that can evaluate code and
  64. insert the output into an Org-mode buffer. Valid choices are
  65. R Evaluate R code
  66. emacs-lisp Evaluate Emacs Lisp code and display the result
  67. sh Pass command to the shell and display the result
  68. perl The perl interpreter
  69. python The python interpreter
  70. ruby The ruby interpreter
  71. The source block regexp `org-babel-src-block-regexp' is updated
  72. when a new interpreter is added to this list through the
  73. customize interface. To add interpreters to this variable from
  74. lisp code use the `org-babel-add-interpreter' function."
  75. :group 'org-babel
  76. :set 'org-babel-set-interpreters
  77. :type '(set :greedy t
  78. (const "R")
  79. (const "emacs-lisp")
  80. (const "sh")
  81. (const "perl")
  82. (const "python")
  83. (const "ruby")))
  84. ;;; functions
  85. (defun org-babel-execute-src-block (&optional arg info params)
  86. "Execute the current source code block, and dump the results
  87. into the buffer immediately following the block. Results are
  88. commented by `org-toggle-fixed-width-section'. With optional
  89. prefix don't dump results into buffer but rather return the
  90. results in raw elisp (this is useful for automated execution of a
  91. source block).
  92. Optionally supply a value for INFO in the form returned by
  93. `org-babel-get-src-block-info'.
  94. Optionally supply a value for PARAMS which will be merged with
  95. the header arguments specified at the source code block."
  96. (interactive)
  97. (let* ((info (or info (org-babel-get-src-block-info)))
  98. (lang (first info))
  99. (body (second info))
  100. (params (org-combine-plists (third info) params))
  101. (cmd (intern (concat "org-babel-execute:" lang)))
  102. result)
  103. ;; (message (format "params=%S" params)) ;; debugging statement
  104. (unless (member lang org-babel-interpreters)
  105. (error "Language is not in `org-babel-interpreters': %s" lang))
  106. (setq result (funcall cmd body params))
  107. ;; possibly force result into a vector
  108. (if (and (not (listp result)) (cdr (assoc :results params))
  109. (member "vector" (split-string (cdr (assoc :results params)))))
  110. (setq result (list result)))
  111. (if arg
  112. (message (format "%S" result))
  113. (org-babel-insert-result result (cdr (assoc :results params))))
  114. result))
  115. (defun org-babel-eval-buffer (&optional arg)
  116. "Replace EVAL snippets in the entire buffer."
  117. (interactive "P")
  118. (save-excursion
  119. (goto-char (point-min))
  120. (while (re-search-forward org-babel-regexp nil t)
  121. (org-babel-eval-src-block arg))))
  122. (defun org-babel-eval-subtree (&optional arg)
  123. "Replace EVAL snippets in the entire subtree."
  124. (interactive "P")
  125. (save-excursion
  126. (org-narrow-to-subtree)
  127. (org-babel-eval-buffer)
  128. (widen)))
  129. (defun org-babel-get-src-block-name ()
  130. "Return the name of the current source block if one exists"
  131. (let ((case-fold-search t))
  132. (save-excursion
  133. (goto-char (org-babel-where-is-src-block-head))
  134. (if (save-excursion (forward-line -1)
  135. (looking-at "#\\+srcname:[ \f\t\n\r\v]*\\([^ \f\t\n\r\v]+\\)"))
  136. (org-babel-clean-text-properties (match-string 1))))))
  137. (defun org-babel-get-src-block-info ()
  138. "Return the information of the current source block as a list
  139. of the following form. (language body header-arguments-alist)"
  140. (let ((case-fold-search t) head)
  141. (if (setq head (org-babel-where-is-src-block-head))
  142. (save-excursion (goto-char head) (org-babel-parse-src-block-match))
  143. (if (save-excursion ;; inline source block
  144. (re-search-backward "[ \f\t\n\r\v]" nil t)
  145. (forward-char 1)
  146. (looking-at org-babel-inline-src-block-regexp))
  147. (org-babel-parse-inline-src-block-match)
  148. nil)))) ;; indicate that no source block was found
  149. (defun org-babel-parse-src-block-match ()
  150. (list (org-babel-clean-text-properties (match-string 1))
  151. (org-babel-clean-text-properties (match-string 4))
  152. (org-combine-plists org-babel-default-header-args
  153. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) ""))))))
  154. (defun org-babel-parse-inline-src-block-match ()
  155. (list (org-babel-clean-text-properties (match-string 1))
  156. (org-babel-clean-text-properties (match-string 4))
  157. (org-combine-plists org-babel-default-inline-header-args
  158. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) ""))))))
  159. (defun org-babel-parse-header-arguments (arg-string)
  160. "Parse a string of header arguments returning an alist."
  161. (delq nil
  162. (mapcar
  163. (lambda (arg) (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]*\\([^ \f\t\n\r\v]+.*\\)" arg)
  164. (cons (intern (concat ":" (match-string 1 arg))) (match-string 2 arg))))
  165. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t))))
  166. (defun org-babel-where-is-src-block-head ()
  167. "Return the point at the beginning of the current source
  168. block. Specifically at the beginning of the #+BEGIN_SRC line.
  169. If the point is not on a source block then return nil."
  170. (let ((initial (point)) top bottom)
  171. (or
  172. (save-excursion ;; on a #+srcname: line
  173. (beginning-of-line 1)
  174. (and (looking-at "#\\+srcname") (forward-line 1)
  175. (looking-at org-babel-src-block-regexp)
  176. (point)))
  177. (save-excursion ;; on a #+begin_src line
  178. (beginning-of-line 1)
  179. (and (looking-at org-babel-src-block-regexp)
  180. (point)))
  181. (save-excursion ;; inside a src block
  182. (and
  183. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  184. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  185. (< top initial) (< initial bottom)
  186. (goto-char top) (looking-at org-babel-src-block-regexp)
  187. (point))))))
  188. (defun org-babel-find-named-result (name)
  189. "Return the location of the result named NAME in the current
  190. buffer or nil if no such result exists."
  191. (save-excursion
  192. (goto-char (point-min))
  193. (when (re-search-forward (concat "#\\+resname:[ \t]*" (regexp-quote name)) nil t)
  194. (move-beginning-of-line 1) (point))))
  195. (defun org-babel-where-is-src-block-result ()
  196. "Return the point at the beginning of the result of the current
  197. source block. Specifically at the beginning of the #+RESNAME:
  198. line. If no result exists for this block then create a
  199. #+RESNAME: line following the source block."
  200. (save-excursion
  201. (goto-char (org-babel-where-is-src-block-head))
  202. (let ((name (org-babel-get-src-block-name)) end head)
  203. (or (and name (message name) (org-babel-find-named-result name))
  204. (and (re-search-forward "#\\+end_src" nil t)
  205. (progn (move-end-of-line 1)
  206. (if (eobp) (insert "\n") (forward-char 1))
  207. (setq end (point))
  208. (or (progn ;; either an unnamed #+resname: line already exists
  209. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  210. (move-beginning-of-line 1) (looking-at "#\\+resname:"))
  211. (progn ;; or we need to back up and make one ourselves
  212. (goto-char end) (open-line 2) (forward-char 1)
  213. (insert (concat "#+resname:" (if name (concat " " name))))
  214. (move-beginning-of-line 1) t)))
  215. (point))))))
  216. (defun org-babel-insert-result (result &optional insert)
  217. "Insert RESULT into the current buffer after the end of the
  218. current source block. With optional argument INSERT controls
  219. insertion of results in the org-mode file. INSERT can take the
  220. following values...
  221. t ------ the default options, simply insert the results after the
  222. source block
  223. replace - insert results after the source block replacing any
  224. previously inserted results
  225. silent -- no results are inserted"
  226. (if insert (setq insert (split-string insert)))
  227. (if (stringp result)
  228. (progn
  229. (setq result (org-babel-clean-text-properties result))
  230. (if (member "file" insert) (setq result (org-babel-result-to-file result))))
  231. (unless (listp result) (setq result (format "%S" result))))
  232. (if (and insert (member "replace" insert)) (org-babel-remove-result))
  233. (if (= (length result) 0)
  234. (message "no result returned by source block")
  235. (if (and insert (member "silent" insert))
  236. (progn (message (format "%S" result)) result)
  237. (when (and (stringp result) ;; ensure results end in a newline
  238. (not (or (string-equal (substring result -1) "\n")
  239. (string-equal (substring result -1) "\r"))))
  240. (setq result (concat result "\n")))
  241. (save-excursion
  242. (goto-char (org-babel-where-is-src-block-result)) (forward-line 1)
  243. (if (stringp result) ;; assume the result is a table if it's not a string
  244. (if (member "file" insert)
  245. (insert result)
  246. (org-babel-examplize-region (point) (progn (insert result) (point))))
  247. (progn
  248. (insert
  249. (concat (orgtbl-to-orgtbl
  250. (if (consp (car result)) result (list result))
  251. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  252. (forward-line -1)
  253. (org-cycle))))
  254. (message "finished"))))
  255. (defun org-babel-result-to-org-string (result)
  256. "Return RESULT as a string in org-mode format. This function
  257. relies on `org-babel-insert-result'."
  258. (with-temp-buffer (org-babel-insert-result result) (buffer-string)))
  259. (defun org-babel-remove-result ()
  260. "Remove the result of the current source block."
  261. (save-excursion
  262. (goto-char (org-babel-where-is-src-block-result)) (forward-line 1)
  263. (delete-region (point)
  264. (save-excursion
  265. (if (org-at-table-p)
  266. (org-table-end)
  267. (while (if (looking-at "\\(: \\|\\[\\[\\)")
  268. (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  269. (forward-line 1)) t))
  270. (forward-line 1))
  271. (forward-line -1)
  272. (point))))))
  273. (defun org-babel-result-to-file (result)
  274. "Return an `org-mode' link with the path being the value or
  275. RESULT, and the display being the `file-name-nondirectory' if
  276. non-nil."
  277. (let ((name (file-name-nondirectory result)))
  278. (concat "[[" result (if name (concat "][" name "]]") "]]"))))
  279. (defun org-babel-examplize-region (beg end)
  280. "Comment out region using the ': ' org example quote."
  281. (interactive "*r")
  282. (let ((size (abs (- (line-number-at-pos end)
  283. (line-number-at-pos beg)))))
  284. (if (= size 0)
  285. (let ((result (buffer-substring beg end)))
  286. (delete-region beg end)
  287. (insert (concat ": " result)))
  288. (save-excursion
  289. (goto-char beg)
  290. (dotimes (n size)
  291. (move-beginning-of-line 1) (insert ": ") (forward-line 1))))))
  292. (defun org-babel-clean-text-properties (text)
  293. "Strip all properties from text return."
  294. (set-text-properties 0 (length text) nil text) text)
  295. (defun org-babel-read (cell)
  296. "Convert the string value of CELL to a number if appropriate.
  297. Otherwise if cell looks like a list (meaning it starts with a
  298. '(') then read it as lisp, otherwise return it unmodified as a
  299. string.
  300. This is taken almost directly from `org-read-prop'."
  301. (if (and (stringp cell) (not (equal cell "")))
  302. (if (org-babel-number-p cell)
  303. (string-to-number cell)
  304. (if (or (equal "(" (substring cell 0 1))
  305. (equal "'" (substring cell 0 1)))
  306. (read cell)
  307. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  308. cell))
  309. (defun org-babel-number-p (string)
  310. "Return t if STRING represents a number"
  311. (string-match "^[[:digit:]]*\\.?[[:digit:]]*$" string))
  312. (defun org-babel-chomp (string &optional regexp)
  313. "Remove any trailing space or carriage returns characters from
  314. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  315. overwritten by specifying a regexp as a second argument."
  316. (while (string-match "[ \f\t\n\r\v]" (substring results -1))
  317. (setq results (substring results 0 -1)))
  318. results)
  319. (provide 'org-babel)
  320. ;;; org-babel.el ends here