org-babel.el 47 KB

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