org-babel.el 17 KB

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