org-babel.el 20 KB

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