org-babel.el 41 KB

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