org-babel.el 15 KB

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