org-babel.el 18 KB

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