org-babel.el 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. (defadvice org-edit-special (around org-babel-prep-session-for-edit activate)
  34. "Prepare the current source block's session according to it's
  35. header arguments before editing in an org-src buffer. This
  36. function is called when `org-edit-special' is called with a
  37. prefix argument from inside of a source-code block."
  38. (when current-prefix-arg
  39. (let* ((info (org-babel-get-src-block-info))
  40. (lang (first info))
  41. (params (third info))
  42. (session (cdr (assoc :session params))))
  43. (when (and info session) ;; if we are in a source-code block which has a session
  44. (funcall (intern (concat "org-babel-prep-session:" lang)) session params))))
  45. ad-do-it)
  46. (defadvice org-open-at-point (around org-babel-open-at-point activate)
  47. "If `point' is on a source code block, then open that block's
  48. results with `org-babel-open-src-block-results', otherwise defer
  49. to `org-open-at-point'."
  50. (interactive "P")
  51. (or (call-interactively #'org-babel-open-src-block-result) ad-do-it))
  52. (defun org-babel-load-in-session-maybe ()
  53. "Detect if this is context for a org-babel src-block and if so
  54. then run `org-babel-load-in-session'."
  55. (interactive)
  56. (let ((info (org-babel-get-src-block-info)))
  57. (if info (progn (org-babel-load-in-session current-prefix-arg info) t) nil)))
  58. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  59. (defun org-babel-pop-to-session-maybe ()
  60. "Detect if this is context for a org-babel src-block and if so
  61. then run `org-babel-pop-to-session'."
  62. (interactive)
  63. (let ((info (org-babel-get-src-block-info)))
  64. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  65. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  66. (defvar org-babel-default-header-args
  67. '((:session . "none") (:results . "replace") (:exports . "code"))
  68. "Default arguments to use when evaluating a source block.")
  69. (defvar org-babel-default-inline-header-args
  70. '((:session . "none") (:results . "silent") (:exports . "results"))
  71. "Default arguments to use when evaluating an inline source block.")
  72. (defvar org-babel-src-block-regexp nil
  73. "Regexp used to test when inside of a org-babel src-block")
  74. (defvar org-babel-inline-src-block-regexp nil
  75. "Regexp used to test when on an inline org-babel src-block")
  76. (defvar org-babel-min-lines-for-block-output 10
  77. "If number of lines of output is equal to or exceeds this
  78. value, the output is placed in a
  79. #+begin_example...#+end_example block. Otherwise the output is
  80. marked as literal by inserting colons at the starts of the
  81. lines. This variable only takes effect if the :results output
  82. option is in effect.")
  83. (defvar org-babel-noweb-error-langs nil
  84. "List of language for which errors should be raised when the
  85. source code block satisfying a noweb reference in this language
  86. can not be resolved.")
  87. (defun org-babel-named-src-block-regexp-for-name (name)
  88. "Regexp used to match named src block."
  89. (concat "#\\+srcname:[ \t]*" (regexp-quote name) "[ \t\n]*"
  90. (substring org-babel-src-block-regexp 1)))
  91. (defun org-babel-set-interpreters (var value)
  92. (set-default var value)
  93. (setq org-babel-src-block-regexp
  94. (concat "^[ \t]*#\\+begin_src[ \t]+\\(" ;; (1) lang
  95. (mapconcat 'regexp-quote value "\\|")
  96. "\\)[ \t]*"
  97. "\\([^:\n]*\\)" ;; (2) switches
  98. "\\([^\n]*\\)\n" ;; (3) header arguments
  99. "\\([^\000]+?\\)#\\+end_src")) ;; (4) body
  100. (setq org-babel-inline-src-block-regexp
  101. (concat "[ \f\t\n\r\v]\\(src_" ;; (1) replacement target
  102. "\\(" ;; (2) lang
  103. (mapconcat 'regexp-quote value "\\|")
  104. "\\)"
  105. "\\(\\|\\[\\(.*\\)\\]\\)" ;; (3,4) (unused, headers)
  106. "{\\([^\f\n\r\v]+\\)}" ;; (5) body
  107. "\\)")))
  108. (defun org-babel-add-interpreter (interpreter)
  109. "Add INTERPRETER to `org-babel-interpreters' and update
  110. `org-babel-src-block-regexp' appropriately."
  111. (unless (member interpreter org-babel-interpreters)
  112. (setq org-babel-interpreters (cons interpreter org-babel-interpreters))
  113. (org-babel-set-interpreters 'org-babel-interpreters org-babel-interpreters)))
  114. (defcustom org-babel-interpreters '()
  115. "Interpreters allows for evaluation tags.
  116. This is a list of program names (as strings) that can evaluate code and
  117. insert the output into an Org-mode buffer. Valid choices are
  118. R Evaluate R code
  119. emacs-lisp Evaluate Emacs Lisp code and display the result
  120. sh Pass command to the shell and display the result
  121. perl The perl interpreter
  122. python The python interpreter
  123. ruby The ruby interpreter
  124. The source block regexp `org-babel-src-block-regexp' is updated
  125. when a new interpreter is added to this list through the
  126. customize interface. To add interpreters to this variable from
  127. lisp code use the `org-babel-add-interpreter' function."
  128. :group 'org-babel
  129. :set 'org-babel-set-interpreters
  130. :type '(set :greedy t
  131. (const "R")
  132. (const "emacs-lisp")
  133. (const "sh")
  134. (const "perl")
  135. (const "python")
  136. (const "ruby")))
  137. ;;; functions
  138. (defun org-babel-execute-src-block (&optional arg info params)
  139. "Execute the current source code block, and dump the results
  140. into the buffer immediately following the block. Results are
  141. commented by `org-toggle-fixed-width-section'. With optional
  142. prefix don't dump results into buffer but rather return the
  143. results in raw elisp (this is useful for automated execution of a
  144. source block).
  145. Optionally supply a value for INFO in the form returned by
  146. `org-babel-get-src-block-info'.
  147. Optionally supply a value for PARAMS which will be merged with
  148. the header arguments specified at the source code block."
  149. (interactive)
  150. ;; (message "supplied params=%S" params) ;; debugging
  151. (let* ((info (or info (org-babel-get-src-block-info)))
  152. (lang (first info))
  153. (params (setf (third info) (org-babel-merge-params (third info) params)))
  154. (body (setf (second info)
  155. (if (assoc :noweb params)
  156. (org-babel-expand-noweb-references info) (second info))))
  157. (processed-params (org-babel-process-params params))
  158. (result-params (third processed-params))
  159. (result-type (fourth processed-params))
  160. (cmd (intern (concat "org-babel-execute:" lang)))
  161. result)
  162. ;; (message "params=%S" params) ;; debugging statement
  163. ;; (message "vars=%S" (second processed-params)) ;; debugging statement
  164. (unless (member lang org-babel-interpreters)
  165. (error "Language is not in `org-babel-interpreters': %s" lang))
  166. (when arg (setq result-params (cons "silent" result-params)))
  167. (setq result (multiple-value-bind (session vars result-params result-type) processed-params
  168. (funcall cmd body params)))
  169. (if (eq result-type 'value)
  170. (setq result (org-babel-process-value-result result result-params)))
  171. (org-babel-insert-result result result-params info)
  172. result))
  173. (defun org-babel-load-in-session (&optional arg info)
  174. "Load the body of the current source-code block. Evaluate the
  175. header arguments for the source block before entering the
  176. session. After loading the body this pops open the session."
  177. (interactive)
  178. (let* ((info (or info (org-babel-get-src-block-info)))
  179. (lang (first info))
  180. (body (second info))
  181. (params (third info))
  182. (session (cdr (assoc :session params))))
  183. (unless (member lang org-babel-interpreters)
  184. (error "Language is not in `org-babel-interpreters': %s" lang))
  185. ;; if called with a prefix argument, then process header arguments
  186. (pop-to-buffer (funcall (intern (concat "org-babel-load-session:" lang)) session body params))
  187. (move-end-of-line 1)))
  188. (defun org-babel-pop-to-session (&optional arg info)
  189. "Pop to the session of the current source-code block. If
  190. called with a prefix argument then evaluate the header arguments
  191. for the source block before entering the session. Copy the body
  192. of the source block to the kill ring."
  193. (interactive)
  194. (let* ((info (or info (org-babel-get-src-block-info)))
  195. (lang (first info))
  196. (body (second info))
  197. (params (third info))
  198. (session (cdr (assoc :session params))))
  199. (unless (member lang org-babel-interpreters)
  200. (error "Language is not in `org-babel-interpreters': %s" lang))
  201. ;; copy body to the kill ring
  202. (with-temp-buffer (insert (org-babel-trim body)) (copy-region-as-kill (point-min) (point-max)))
  203. ;; if called with a prefix argument, then process header arguments
  204. (if arg (funcall (intern (concat "org-babel-prep-session:" lang)) session params))
  205. ;; just to the session using pop-to-buffer
  206. (pop-to-buffer (funcall (intern (format "org-babel-%s-initiate-session" lang)) session))
  207. (move-end-of-line 1)))
  208. (defun org-babel-open-src-block-result (&optional re-run)
  209. "If `point' is on a src block then open the results of the
  210. source code block, otherwise return nil. With optional prefix
  211. argument RE-RUN the source-code block is evaluated even if
  212. results already exist."
  213. (interactive "P")
  214. (when (org-babel-get-src-block-info)
  215. (save-excursion
  216. ;; go to the results, if there aren't any then run the block
  217. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  218. (progn (org-babel-execute-src-block)
  219. (org-babel-where-is-src-block-result))))
  220. (move-end-of-line 1) (forward-char 1)
  221. ;; open the results
  222. (if (looking-at org-bracket-link-regexp)
  223. ;; file results
  224. (org-open-at-point)
  225. (let ((results (org-babel-read-result)))
  226. (flet ((echo-res (result)
  227. (if (stringp result) result (format "%S" result))))
  228. (pop-to-buffer (get-buffer-create "org-babel-results"))
  229. (delete-region (point-min) (point-max))
  230. (if (listp results)
  231. ;; table result
  232. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  233. ;; scalar result
  234. (insert (echo-res results))))))
  235. t)))
  236. (defun org-babel-process-value-result (result result-params)
  237. "Process returned value for insertion in buffer.
  238. Currently, this function forces to table output if :results
  239. table or :results vector has been supplied.
  240. You can see below the various fragments of results-processing
  241. code that were present in the language-specific files. Out of
  242. those fragments, I've moved the org-babel-python-table-or-results
  243. and org-babel-import-elisp-from-file functionality into the
  244. org-babel-*-evaluate functions. I think those should only be used
  245. in the :results value case, as in the 'output case we are not
  246. concerned with creating elisp versions of results. "
  247. (if (and (or (member "vector" result-params)
  248. (member "table" result-params))
  249. (not (listp result)))
  250. (list (list result))
  251. result))
  252. (defun org-babel-execute-buffer (&optional arg)
  253. "Replace EVAL snippets in the entire buffer."
  254. (interactive "P")
  255. (save-excursion
  256. (goto-char (point-min))
  257. (while (re-search-forward org-babel-src-block-regexp nil t)
  258. (goto-char (match-beginning 0))
  259. (org-babel-execute-src-block arg)
  260. (goto-char (match-end 0)))))
  261. (defun org-babel-execute-subtree (&optional arg)
  262. "Replace EVAL snippets in the entire subtree."
  263. (interactive "P")
  264. (save-excursion
  265. (org-narrow-to-subtree)
  266. (org-babel-execute-buffer)
  267. (widen)))
  268. (defun org-babel-get-src-block-info (&optional header-vars-only)
  269. "Get information of the current source block.
  270. Returns a list
  271. (language body header-arguments-alist switches name function-args).
  272. Unless HEADER-VARS-ONLY is non-nil, any variable
  273. references provided in 'function call style' (i.e. in a
  274. parenthesised argument list following the src block name) are
  275. added to the header-arguments-alist."
  276. (let ((case-fold-search t) head info args)
  277. (if (setq head (org-babel-where-is-src-block-head))
  278. (save-excursion
  279. (goto-char head)
  280. (setq info (org-babel-parse-src-block-match))
  281. (forward-line -1)
  282. (when (looking-at "#\\+srcname:[ \t]*\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
  283. (setq info (append info (list (org-babel-clean-text-properties (match-string 1)))))
  284. ;; Note that e.g. "name()" and "name( )" result in ((:var . "")).
  285. ;; We maintain that behaviour, and the resulting non-nil sixth
  286. ;; element is relied upon in org-babel-exp-code to detect a functional-style
  287. ;; block in those cases. However, "name" without any
  288. ;; parentheses would result in the same thing, so we
  289. ;; explicitly avoid that.
  290. (if (setq args (match-string 3))
  291. (setq info (append info (list (mapcar (lambda (ref) (cons :var ref))
  292. (org-babel-ref-split-args args))))))
  293. (unless header-vars-only
  294. (setf (third info)
  295. (org-babel-merge-params (sixth info) (third info)))))
  296. info)
  297. (if (save-excursion ;; inline source block
  298. (re-search-backward "[ \f\t\n\r\v]" nil t)
  299. (looking-at org-babel-inline-src-block-regexp))
  300. (org-babel-parse-inline-src-block-match)
  301. nil)))) ;; indicate that no source block was found
  302. (defmacro org-babel-map-source-blocks (file &rest body)
  303. "Evaluate BODY forms on each source-block in FILE."
  304. (declare (indent 1))
  305. `(let ((visited-p (get-buffer (file-name-nondirectory ,file))))
  306. (save-window-excursion
  307. (find-file ,file) (goto-char (point-min))
  308. (while (re-search-forward org-babel-src-block-regexp nil t)
  309. (goto-char (match-beginning 0))
  310. (save-match-data ,@body)
  311. (goto-char (match-end 0))))
  312. (unless visited-p (kill-buffer (file-name-nondirectory file)))))
  313. (defun org-babel-params-from-properties ()
  314. "Return an association list of any source block params which
  315. may be specified in the properties of the current outline entry."
  316. (save-match-data
  317. (delq nil
  318. (mapcar
  319. (lambda (header-arg)
  320. (let ((val (or (org-entry-get (point) header-arg 'selective)
  321. (cdr (assoc header-arg org-file-properties)))))
  322. (when val
  323. ;; (message "param-from-property %s=%s" header-arg val) ;; debugging statement
  324. (cons (intern (concat ":" header-arg)) val))))
  325. '("exports" "results" "session" "tangle" "var")))))
  326. (defun org-babel-parse-src-block-match ()
  327. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  328. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  329. (switches (match-string 2))
  330. (body (org-babel-clean-text-properties (match-string 4)))
  331. (preserve-indentation (or org-src-preserve-indentation
  332. (string-match "-i\\>" switches))))
  333. (list lang
  334. ;; get src block body removing properties, protective commas, and indentation
  335. (with-temp-buffer
  336. (save-match-data
  337. (insert (org-babel-strip-protective-commas body))
  338. (unless preserve-indentation (org-do-remove-indentation))
  339. (buffer-string)))
  340. (org-babel-merge-params
  341. org-babel-default-header-args
  342. (org-babel-params-from-properties)
  343. (if (boundp lang-headers) (eval lang-headers) nil)
  344. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) ""))))
  345. switches)))
  346. (defun org-babel-parse-inline-src-block-match ()
  347. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  348. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  349. (list lang
  350. (org-babel-strip-protective-commas (org-babel-clean-text-properties (match-string 5)))
  351. (org-babel-merge-params
  352. org-babel-default-inline-header-args
  353. (org-babel-params-from-properties)
  354. (if (boundp lang-headers) (eval lang-headers) nil)
  355. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 4) "")))))))
  356. (defun org-babel-parse-header-arguments (arg-string)
  357. "Parse a string of header arguments returning an alist."
  358. (if (> (length arg-string) 0)
  359. (delq nil
  360. (mapcar
  361. (lambda (arg)
  362. (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)" arg)
  363. (cons (intern (concat ":" (match-string 1 arg)))
  364. (org-babel-chomp (match-string 2 arg)))
  365. (cons (intern (concat ":" arg)) nil)))
  366. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  367. (defun org-babel-process-params (params)
  368. "Parse params and resolve references.
  369. Return a list (session vars result-params result-type). These are
  370. made available to the org-babel-execute:LANG functions via
  371. multiple-value-bind."
  372. (let* ((session (cdr (assoc :session params)))
  373. (vars (org-babel-ref-variables params))
  374. (result-params (split-string (or (cdr (assoc :results params)) "")))
  375. (result-type (cond ((member "output" result-params) 'output)
  376. ((member "value" result-params) 'value)
  377. (t 'value))))
  378. (list session vars result-params result-type)))
  379. (defun org-babel-where-is-src-block-head ()
  380. "Return the point at the beginning of the current source
  381. block. Specifically at the beginning of the #+BEGIN_SRC line.
  382. If the point is not on a source block then return nil."
  383. (let ((initial (point)) top bottom)
  384. (or
  385. (save-excursion ;; on a #+srcname: line
  386. (beginning-of-line 1)
  387. (and (looking-at "#\\+srcname") (forward-line 1)
  388. (looking-at org-babel-src-block-regexp)
  389. (point)))
  390. (save-excursion ;; on a #+begin_src line
  391. (beginning-of-line 1)
  392. (and (looking-at org-babel-src-block-regexp)
  393. (point)))
  394. (save-excursion ;; inside a src block
  395. (and
  396. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  397. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  398. (< top initial) (< initial bottom)
  399. (goto-char top) (move-beginning-of-line 1)
  400. (looking-at org-babel-src-block-regexp)
  401. (point))))))
  402. (defun org-babel-goto-named-source-block (&optional name)
  403. "Go to a named source-code block."
  404. (interactive "ssource-block name: ")
  405. (let ((point (org-babel-find-named-block name)))
  406. (if point
  407. ;; taken from `org-open-at-point'
  408. (progn (goto-char point) (org-show-context))
  409. (message "source-code block '%s' not found in this buffer" name))))
  410. (defun org-babel-find-named-block (name)
  411. "Find a named source-code block.
  412. Return the location of the source block identified by
  413. #+srcname NAME, or nil if no such block exists. Set match data
  414. according to org-babel-named-src-block-regexp."
  415. (save-excursion
  416. (let ((case-fold-search t)
  417. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  418. (goto-char (point-min))
  419. (when (or (re-search-forward regexp nil t)
  420. (re-search-backward regexp nil t))
  421. (match-beginning 0)))))
  422. (defun org-babel-find-named-result (name)
  423. "Return the location of the result named NAME in the current
  424. buffer or nil if no such result exists."
  425. (save-excursion
  426. (goto-char (point-min))
  427. (when (re-search-forward ;; ellow end-of-buffer in following regexp?
  428. (concat "#\\+resname:[ \t]*" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  429. (move-beginning-of-line 0) (point))))
  430. (defun org-babel-where-is-src-block-result (&optional insert info)
  431. "Return the point at the beginning of the result of the current
  432. source block. Specifically at the beginning of the #+RESNAME:
  433. line. If no result exists for this block then create a
  434. #+RESNAME: line following the source block."
  435. (save-excursion
  436. (let* ((on-lob-line (progn (beginning-of-line 1)
  437. (looking-at org-babel-lob-one-liner-regexp)))
  438. (name (if on-lob-line (first (org-babel-lob-get-info))
  439. (fifth (or info (org-babel-get-src-block-info)))))
  440. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  441. (when head (goto-char head))
  442. (or (and name (org-babel-find-named-result name))
  443. (and (or on-lob-line (re-search-forward "#\\+end_src" nil t))
  444. (progn (move-end-of-line 1)
  445. (if (eobp) (insert "\n") (forward-char 1))
  446. (setq end (point))
  447. (or (and (not name)
  448. (progn ;; either the unnamed #+resname: line already exists
  449. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  450. (move-beginning-of-line 1) (looking-at "#\\+resname:\n")))
  451. ;; or (with optional insert) we need to back up and make one ourselves
  452. (when insert
  453. (goto-char end) (open-line 2) (forward-char 1)
  454. (insert (concat "#+resname:" (if name (concat " " name)) "\n"))
  455. (move-beginning-of-line 0) t)))
  456. (point))))))
  457. (defun org-babel-read-result ()
  458. "Read the result at `point' into emacs-lisp."
  459. (let ((case-fold-search t) result-string)
  460. (cond
  461. ((org-at-table-p) (org-babel-read-table))
  462. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  463. ((looking-at ": ")
  464. (setq result-string
  465. (org-babel-trim
  466. (mapconcat (lambda (line) (if (and (> (length line) 1)
  467. (string= ": " (substring line 0 2)))
  468. (substring line 2)
  469. line))
  470. (split-string
  471. (buffer-substring (point) (org-babel-result-end)) "[\r\n]+")
  472. "\n")))
  473. (or (org-babel-number-p result-string) result-string))
  474. ((looking-at "^#\\+RESNAME:")
  475. (save-excursion (forward-line 1) (org-babel-read-result))))))
  476. (defun org-babel-read-table ()
  477. "Read the table at `point' into emacs-lisp."
  478. (mapcar (lambda (row)
  479. (if (and (symbolp row) (equal row 'hline)) row
  480. (mapcar #'org-babel-read row)))
  481. (org-table-to-lisp)))
  482. (defun org-babel-insert-result (result &optional insert info)
  483. "Insert RESULT into the current buffer after the end of the
  484. current source block. With optional argument INSERT controls
  485. insertion of results in the org-mode file. INSERT can take the
  486. following values...
  487. replace - (default option) insert results after the source block
  488. replacing any previously inserted results
  489. silent -- no results are inserted
  490. file ---- the results are interpreted as a file path, and are
  491. inserted into the buffer using the Org-mode file syntax
  492. raw ----- results are added directly to the org-mode file. This
  493. is a good option if you code block will output org-mode
  494. formatted text.
  495. org ----- this is the same as the 'raw' option
  496. html ---- results are added inside of a #+BEGIN_HTML block. This
  497. is a good option if you code block will output html
  498. formatted text.
  499. latex --- results are added inside of a #+BEGIN_LATEX block.
  500. This is a good option if you code block will output
  501. latex formatted text.
  502. code ---- the results are extracted in the syntax of the source
  503. code of the language being evaluated and are added
  504. inside of a #+BEGIN_SRC block with the source-code
  505. language set appropriately."
  506. (if (stringp result)
  507. (progn
  508. (setq result (org-babel-clean-text-properties result))
  509. (if (member "file" insert) (setq result (org-babel-result-to-file result))))
  510. (unless (listp result) (setq result (format "%S" result))))
  511. (if (and insert (member "replace" insert) (not (member "silent" insert)))
  512. (org-babel-remove-result info))
  513. (if (= (length result) 0)
  514. (if (member "value" result-params)
  515. (message "No result returned by source block")
  516. (message "Source block produced no output"))
  517. (if (and insert (member "silent" insert))
  518. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result))) result)
  519. (when (and (stringp result) ;; ensure results end in a newline
  520. (not (or (string-equal (substring result -1) "\n")
  521. (string-equal (substring result -1) "\r"))))
  522. (setq result (concat result "\n")))
  523. (save-excursion
  524. (let ((existing-result (org-babel-where-is-src-block-result t info))
  525. (results-switches (cdr (assoc :results_switches (third info)))))
  526. (when existing-result (goto-char existing-result) (forward-line 1))
  527. (setq results-switches (if results-switches (concat " " results-switches) ""))
  528. (cond
  529. ;; assume the result is a table if it's not a string
  530. ((not (stringp result))
  531. (insert (concat (orgtbl-to-orgtbl
  532. (if (and (listp (car result)) (listp (cdr (car result))))
  533. result (list result))
  534. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  535. (forward-line -1) (org-cycle))
  536. ((member "file" insert)
  537. (insert result))
  538. ((member "html" insert)
  539. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n" results-switches result)))
  540. ((member "latex" insert)
  541. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n" results-switches result)))
  542. ((member "code" insert)
  543. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n" lang results-switches result)))
  544. ((or (member "raw" insert) (member "org" insert))
  545. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  546. (t
  547. (org-babel-examplize-region (point) (progn (insert result) (point)) results-switches)))))
  548. (message "finished"))))
  549. (defun org-babel-result-to-org-string (result)
  550. "Return RESULT as a string in org-mode format. This function
  551. relies on `org-babel-insert-result'."
  552. (with-temp-buffer (org-babel-insert-result result) (buffer-string)))
  553. (defun org-babel-remove-result (&optional info)
  554. "Remove the result of the current source block."
  555. (interactive)
  556. (save-excursion
  557. (goto-char (org-babel-where-is-src-block-result t info)) (forward-line 1)
  558. (delete-region (point) (org-babel-result-end))))
  559. (defun org-babel-result-end ()
  560. "Return the point at the end of the current set of results"
  561. (save-excursion
  562. (if (org-at-table-p)
  563. (progn (goto-char (org-table-end)) (point))
  564. (let ((case-fold-search t))
  565. (cond
  566. ((looking-at "#\\+begin_latex")
  567. (search-forward "#+end_latex" nil t)
  568. (forward-line 1))
  569. ((looking-at "#\\+begin_html")
  570. (search-forward "#+end_html" nil t)
  571. (forward-line 1))
  572. ((looking-at "#\\+begin_example")
  573. (search-forward "#+end_example" nil t)
  574. (forward-line 1))
  575. ((looking-at "#\\+begin_src")
  576. (search-forward "#+end_src" nil t)
  577. (forward-line 1))
  578. (t (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  579. (forward-line 1))))))
  580. (point))))
  581. (defun org-babel-result-to-file (result)
  582. "Return an `org-mode' link with the path being the value or
  583. RESULT, and the display being the `file-name-nondirectory' if
  584. non-nil."
  585. (concat "[[file:" result "]]"))
  586. (defun org-babel-examplize-region (beg end &optional results-switches)
  587. "Comment out region using the ': ' org example quote."
  588. (interactive "*r")
  589. (let ((size (abs (- (line-number-at-pos end)
  590. (line-number-at-pos beg)))))
  591. (save-excursion
  592. (cond ((= size 0)
  593. (error "This should be impossible: a newline was appended to result if missing")
  594. (let ((result (buffer-substring beg end)))
  595. (delete-region beg end)
  596. (insert (concat ": " result))))
  597. ((< size org-babel-min-lines-for-block-output)
  598. (goto-char beg)
  599. (dotimes (n size)
  600. (move-beginning-of-line 1) (insert ": ") (forward-line 1)))
  601. (t
  602. (goto-char beg)
  603. (insert (if results-switches
  604. (format "#+begin_example%s\n" results-switches)
  605. "#+begin_example\n"))
  606. (forward-char (- end beg))
  607. (insert "#+end_example\n"))))))
  608. (defun org-babel-merge-params (&rest plists)
  609. "Combine all parameter association lists in PLISTS. Later
  610. elements of PLISTS override the values of previous element. This
  611. takes into account some special considerations for certain
  612. parameters when merging lists."
  613. (let ((results-exclusive-groups
  614. '(("file" "vector" "table" "scalar" "raw" "org" "html" "latex" "code" "pp")
  615. ("replace" "silent")
  616. ("output" "value")))
  617. (exports-exclusive-groups
  618. '(("code" "results" "both" "none")))
  619. params results exports tangle vars var ref)
  620. (flet ((e-merge (exclusive-groups &rest result-params)
  621. ;; maintain exclusivity of mutually exclusive parameters
  622. (let (output)
  623. (mapc (lambda (new-params)
  624. (mapc (lambda (new-param)
  625. (mapc (lambda (exclusive-group)
  626. (when (member new-param exclusive-group)
  627. (mapcar (lambda (excluded-param)
  628. (setq output (delete excluded-param output)))
  629. exclusive-group)))
  630. exclusive-groups)
  631. (setq output (org-uniquify (cons new-param output))))
  632. new-params))
  633. result-params)
  634. output)))
  635. (mapc (lambda (plist)
  636. (mapc (lambda (pair)
  637. (case (car pair)
  638. (:var
  639. ;; we want only one specification per variable
  640. (when (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=[ \t]*\\([^\f\n\r\v]+\\)$" (cdr pair))
  641. ;; TODO: When is this not true?
  642. (setq var (intern (match-string 1 (cdr pair)))
  643. ref (match-string 2 (cdr pair))
  644. vars (cons (cons var ref) (assq-delete-all var vars)))))
  645. (:results
  646. (setq results
  647. (e-merge results-exclusive-groups results (split-string (cdr pair)))))
  648. (:file
  649. (when (cdr pair)
  650. (setq results (e-merge results-exclusive-groups results '("file")))
  651. (unless (or (member "both" exports) (member "none" exports))
  652. (setq exports (e-merge exports-exclusive-groups exports '("results"))))
  653. (setq params (cons pair (assq-delete-all (car pair) params)))))
  654. (:exports
  655. (setq exports (e-merge exports-exclusive-groups
  656. exports (split-string (cdr pair)))))
  657. (:tangle
  658. (setq tangle (e-merge '(("yes" "no"))
  659. tangle (split-string (cdr pair)))))
  660. (t ;; replace: this covers e.g. :session
  661. (setq params (cons pair (assq-delete-all (car pair) params))))))
  662. plist))
  663. plists))
  664. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  665. (while vars (setq params (cons (cons :var (pop vars)) params)))
  666. (cons (cons :tangle (mapconcat 'identity tangle " "))
  667. (cons (cons :exports (mapconcat 'identity exports " "))
  668. (cons (cons :results (mapconcat 'identity results " "))
  669. params)))))
  670. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  671. "This function expands Noweb style references in the body of
  672. the current source-code block. For example the following
  673. reference would be replaced with the body of the source-code
  674. block named 'example-block' (assuming the '#' character starts a
  675. comment) .
  676. # <<example-block>>
  677. This function must be called from inside of the buffer containing
  678. the source-code block which holds BODY.
  679. In addition the following syntax can be used to insert the
  680. results of evaluating the source-code block named 'example-block'.
  681. # <<example-block()>>
  682. Any optional arguments can be passed to example-block by placing
  683. the arguments inside the parenthesis following the convention
  684. defined by `org-babel-lob'. For example
  685. # <<example-block(a=9)>>
  686. would set the value of argument \"a\" equal to \"9\". Note that
  687. these arguments are not evaluated in the current source-code block but are passed literally to the \"example-block\"."
  688. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  689. (info (or info (org-babel-get-src-block-info)))
  690. (lang (first info))
  691. (body (second info))
  692. (new-body "") index source-name evaluate)
  693. (flet ((nb-add (text)
  694. (setq new-body (concat new-body text))))
  695. (with-temp-buffer
  696. (insert body) (goto-char (point-min))
  697. (funcall (intern (concat (or (and (cdr (assoc lang org-src-lang-modes))
  698. (symbol-name
  699. (cdr (assoc lang org-src-lang-modes))))
  700. lang) "-mode")))
  701. (setq index (point))
  702. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  703. (save-match-data (setf source-name (match-string 1)))
  704. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  705. ;; add interval to new-body (removing noweb reference)
  706. (goto-char (match-beginning 0))
  707. (nb-add (buffer-substring index (point)))
  708. (goto-char (match-end 0))
  709. (setq index (point))
  710. (nb-add (save-excursion
  711. (set-buffer parent-buffer)
  712. (if evaluate
  713. (let ((raw (org-babel-ref-resolve-reference
  714. source-name nil)))
  715. (if (stringp raw) raw (format "%S" raw)))
  716. (let ((point (org-babel-find-named-block source-name)))
  717. (if point
  718. (save-excursion
  719. (goto-char point)
  720. (org-babel-trim (org-babel-expand-noweb-references
  721. (org-babel-get-src-block-info))))
  722. ;; optionally raise an error if named source-block doesn't exist
  723. (if (member lang org-babel-noweb-error-langs)
  724. (error
  725. "<<%s>> could not be resolved (see `org-babel-noweb-error-langs')"
  726. source-name)
  727. "")))))))
  728. (nb-add (buffer-substring index (point-max)))))
  729. new-body))
  730. (defun org-babel-clean-text-properties (text)
  731. "Strip all properties from text return."
  732. (set-text-properties 0 (length text) nil text) text)
  733. (defun org-babel-strip-protective-commas (body)
  734. "Strip protective commas from bodies of source blocks."
  735. (replace-regexp-in-string "^,#" "#" body))
  736. (defun org-babel-read (cell)
  737. "Convert the string value of CELL to a number if appropriate.
  738. Otherwise if cell looks like lisp (meaning it starts with a
  739. \"(\" or a \"'\") then read it as lisp, otherwise return it
  740. unmodified as a string.
  741. This is taken almost directly from `org-read-prop'."
  742. (if (and (stringp cell) (not (equal cell "")))
  743. (or (org-babel-number-p cell)
  744. (if (or (equal "(" (substring cell 0 1))
  745. (equal "'" (substring cell 0 1)))
  746. (read cell)
  747. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  748. cell))
  749. (defun org-babel-number-p (string)
  750. "Return t if STRING represents a number"
  751. (if (and (string-match "^-?[[:digit:]]*\\.?[[:digit:]]*$" string)
  752. (= (match-end 0) (length string)))
  753. (string-to-number string)))
  754. (defun org-babel-import-elisp-from-file (file-name)
  755. "Read the results located at FILE-NAME into an elisp table. If
  756. the table is trivial, then return it as a scalar."
  757. (let (result)
  758. (with-temp-buffer
  759. (condition-case nil
  760. (progn
  761. (org-table-import file-name nil)
  762. (delete-file file-name)
  763. (setq result (mapcar (lambda (row)
  764. (mapcar #'org-babel-string-read row))
  765. (org-table-to-lisp))))
  766. (error nil)))
  767. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  768. (if (consp (car result))
  769. (if (null (cdr (car result)))
  770. (caar result)
  771. result)
  772. (car result))
  773. result)))
  774. (defun org-babel-string-read (cell)
  775. "Strip nested \"s from around strings in exported R values."
  776. (org-babel-read (or (and (stringp cell)
  777. (string-match "\\\"\\(.+\\)\\\"" cell)
  778. (match-string 1 cell))
  779. cell)))
  780. (defun org-babel-reverse-string (string)
  781. (apply 'string (reverse (string-to-list string))))
  782. (defun org-babel-chomp (string &optional regexp)
  783. "Remove any trailing space or carriage returns characters from
  784. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  785. overwritten by specifying a regexp as a second argument."
  786. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  787. (while (and (> (length string) 0) (string-match regexp (substring string -1)))
  788. (setq string (substring string 0 -1)))
  789. string))
  790. (defun org-babel-trim (string &optional regexp)
  791. "Like `org-babel-chomp' only it runs on both the front and back of the string"
  792. (org-babel-chomp (org-babel-reverse-string
  793. (org-babel-chomp (org-babel-reverse-string string) regexp)) regexp))
  794. (provide 'org-babel)
  795. ;;; org-babel.el ends here