org-babel.el 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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-open-at-point (around org-babel-open-at-point activate)
  34. "If `point' is on a source code block, then open that block's
  35. results with `org-babel-open-src-block-results', otherwise defer
  36. to `org-open-at-point'."
  37. (message "opening at point")
  38. (or (org-babel-open-src-block-result)
  39. ad-do-it))
  40. (defun org-babel-pop-to-session-maybe ()
  41. "Detect if this is context for a org-babel src-block and if so
  42. then run `org-babel-pop-to-session'."
  43. (interactive)
  44. (let ((info (org-babel-get-src-block-info)))
  45. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  46. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  47. (defvar org-babel-default-header-args '((:session . "none") (:results . "replace"))
  48. "Default arguments to use when evaluating a source block.")
  49. (defvar org-babel-default-inline-header-args '((:results . "silent") (:exports . "code"))
  50. "Default arguments to use when evaluating an inline source block.")
  51. (defvar org-babel-src-block-regexp nil
  52. "Regexp used to test when inside of a org-babel src-block")
  53. (defvar org-babel-inline-src-block-regexp nil
  54. "Regexp used to test when on an inline org-babel src-block")
  55. (defvar org-babel-min-lines-for-block-output 10
  56. "If number of lines of output is equal to or exceeds this
  57. value, the output is placed in a
  58. #+begin_example...#+end_example block. Otherwise the output is
  59. marked as literal by inserting colons at the starts of the
  60. lines. This variable only takes effect if the :results output
  61. option is in effect.")
  62. (defun org-babel-named-src-block-regexp-for-name (name)
  63. "Regexp used to match named src block."
  64. (concat "#\\+srcname:[ \t]*" (regexp-quote name) "[ \t\n]*"
  65. org-babel-src-block-regexp))
  66. (defun org-babel-set-interpreters (var value)
  67. (set-default var value)
  68. (setq org-babel-src-block-regexp
  69. (concat "#\\+begin_src \\("
  70. (mapconcat 'regexp-quote value "\\|")
  71. "\\)[ \t]*"
  72. "\\([ \t]+\\([^\n]+\\)\\)?\n" ;; match header arguments
  73. "\\([^\000]+?\\)#\\+end_src"))
  74. (setq org-babel-inline-src-block-regexp
  75. (concat "src_\\("
  76. (mapconcat 'regexp-quote value "\\|")
  77. "\\)"
  78. "\\(\\|\\[\\(.*\\)\\]\\)"
  79. "{\\([^\n]+\\)}")))
  80. (defun org-babel-add-interpreter (interpreter)
  81. "Add INTERPRETER to `org-babel-interpreters' and update
  82. `org-babel-src-block-regexp' appropriately."
  83. (unless (member interpreter org-babel-interpreters)
  84. (setq org-babel-interpreters (cons interpreter org-babel-interpreters))
  85. ;; (add-to-list 'org-babel-session-defaults (cons interpreter (format "org-babel-%s" interpreter)))
  86. (org-babel-set-interpreters 'org-babel-interpreters org-babel-interpreters)))
  87. (defcustom org-babel-interpreters '()
  88. "Interpreters allows for evaluation tags.
  89. This is a list of program names (as strings) that can evaluate code and
  90. insert the output into an Org-mode buffer. Valid choices are
  91. R Evaluate R code
  92. emacs-lisp Evaluate Emacs Lisp code and display the result
  93. sh Pass command to the shell and display the result
  94. perl The perl interpreter
  95. python The python interpreter
  96. ruby The ruby interpreter
  97. The source block regexp `org-babel-src-block-regexp' is updated
  98. when a new interpreter is added to this list through the
  99. customize interface. To add interpreters to this variable from
  100. lisp code use the `org-babel-add-interpreter' function."
  101. :group 'org-babel
  102. :set 'org-babel-set-interpreters
  103. :type '(set :greedy t
  104. (const "R")
  105. (const "emacs-lisp")
  106. (const "sh")
  107. (const "perl")
  108. (const "python")
  109. (const "ruby")))
  110. ;;; functions
  111. (defun org-babel-pop-to-session (&optional arg info)
  112. "Pop to the session of the current source-code block. If
  113. called with a prefix argument then evaluate the header arguments
  114. for the source block before entering the session. Copy the body
  115. of the source block to the kill ring."
  116. (interactive)
  117. (let* ((info (or info (org-babel-get-src-block-info)))
  118. (lang (first info))
  119. (body (second info))
  120. (params (third info))
  121. (session (cdr (assoc :session params))))
  122. (unless (member lang org-babel-interpreters)
  123. (error "Language is not in `org-babel-interpreters': %s" lang))
  124. ;; copy body to the kill ring
  125. (with-temp-buffer (insert (org-babel-trim body)) (copy-region-as-kill (point-min) (point-max)))
  126. ;; if called with a prefix argument, then process header arguments
  127. (if arg (funcall (intern (concat "org-babel-prep-session:" lang)) session params))
  128. ;; just to the session using pop-to-buffer
  129. (pop-to-buffer (funcall (intern (format "org-babel-%s-initiate-session" lang)) session))
  130. (move-end-of-line 1)))
  131. (defun org-babel-execute-src-block (&optional arg info params)
  132. "Execute the current source code block, and dump the results
  133. into the buffer immediately following the block. Results are
  134. commented by `org-toggle-fixed-width-section'. With optional
  135. prefix don't dump results into buffer but rather return the
  136. results in raw elisp (this is useful for automated execution of a
  137. source block).
  138. Optionally supply a value for INFO in the form returned by
  139. `org-babel-get-src-block-info'.
  140. Optionally supply a value for PARAMS which will be merged with
  141. the header arguments specified at the source code block."
  142. (interactive)
  143. (message "supplied params=%S" params)
  144. (let* ((info (or info (org-babel-get-src-block-info)))
  145. (lang (first info))
  146. (body (second info))
  147. (params (org-babel-merge-params
  148. (third info) (org-babel-get-src-block-function-args) params))
  149. (processed-params (org-babel-process-params params))
  150. (result-params (third processed-params))
  151. (result-type (fourth processed-params))
  152. (cmd (intern (concat "org-babel-execute:" lang)))
  153. result)
  154. (message "params=%S" params) ;; debugging statement
  155. (unless (member lang org-babel-interpreters)
  156. (error "Language is not in `org-babel-interpreters': %s" lang))
  157. (when arg (setq result-params (cons "silent" result-params)))
  158. (setq result (multiple-value-bind (session vars result-params result-type) processed-params
  159. (funcall cmd body params)))
  160. (if (eq result-type 'value)
  161. (setq result (org-babel-process-value-result result result-params)))
  162. (org-babel-insert-result result result-params)
  163. (case result-type (output nil) (value result))))
  164. (defun org-babel-open-src-block-result (&optional re-run)
  165. "If `point' is on a src block then open the results of the
  166. source code block, otherwise return nil. With optional prefix
  167. argument RE-RUN the source-code block is evaluated even if
  168. results already exist."
  169. (interactive)
  170. (message "opening src block results")
  171. (when (org-babel-get-src-block-info)
  172. (save-excursion
  173. ;; go to the results, if there aren't any then run the block
  174. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  175. (progn (org-babel-execute-src-block)
  176. (org-babel-where-is-src-block-result))))
  177. (move-end-of-line 1) (forward-char 1)
  178. ;; open the results
  179. (if (looking-at org-bracket-link-regexp)
  180. (org-open-at-point) ;; file
  181. ;; vector or scalar
  182. (let ((results (org-babel-read-result)))
  183. (pop-to-buffer (get-buffer-create "org-babel-results"))
  184. (delete-region (point-min) (point-max))
  185. (if (listp results)
  186. (insert (orgtbl-to-tsv (list results) nil))
  187. (insert results))))
  188. t)))
  189. (defun org-babel-process-value-result (result result-params)
  190. "Process returned value for insertion in buffer.
  191. Currently, this function forces to table output if :results
  192. vector has been supplied.
  193. You can see below the various fragments of results-processing
  194. code that were present in the language-specific files. Out of
  195. those fragments, I've moved the org-babel-python-table-or-results
  196. and org-babel-import-elisp-from-file functionality into the
  197. org-babel-*-evaluate functions. I think those should only be used
  198. in the :results value case, as in the 'output case we are not
  199. concerned with creating elisp versions of results. "
  200. (if (and (member "vector" result-params) (not (listp result)))
  201. (list (list result))
  202. result))
  203. (defun org-babel-execute-buffer (&optional arg)
  204. "Replace EVAL snippets in the entire buffer."
  205. (interactive "P")
  206. (save-excursion
  207. (goto-char (point-min))
  208. (while (re-search-forward org-babel-src-block-regexp nil t)
  209. (goto-char (match-beginning 0))
  210. (org-babel-execute-src-block arg)
  211. (goto-char (match-end 0)))))
  212. (defun org-babel-execute-subtree (&optional arg)
  213. "Replace EVAL snippets in the entire subtree."
  214. (interactive "P")
  215. (save-excursion
  216. (org-narrow-to-subtree)
  217. (org-babel-execute-buffer)
  218. (widen)))
  219. (defun org-babel-get-src-block-name ()
  220. "Return the name of the current source block if one exists.
  221. This function is analogous to org-babel-lob-get-info. For both
  222. functions, after they are called, (match-string 1) matches the
  223. function name, and (match-string 2) matches the function
  224. arguments inside the parentheses. I think perhaps these functions
  225. should be renamed to bring out this similarity, perhaps involving
  226. the word 'call'."
  227. (let ((case-fold-search t)
  228. (head (org-babel-where-is-src-block-head)))
  229. (if head
  230. (save-excursion
  231. (goto-char head)
  232. (if (save-excursion
  233. (forward-line -1)
  234. (looking-at "#\\+srcname:[ \f\t\n\r\v]*\\([^ ()\f\t\n\r\v]+\\)\(\\(.*\\)\)"))
  235. (org-babel-clean-text-properties (match-string 1)))))))
  236. (defun org-babel-get-src-block-info ()
  237. "Return the information of the current source block as a list
  238. of the following form. (language body header-arguments-alist)"
  239. (let ((case-fold-search t) head)
  240. (if (setq head (org-babel-where-is-src-block-head))
  241. (save-excursion (goto-char head) (org-babel-parse-src-block-match))
  242. (if (save-excursion ;; inline source block
  243. (re-search-backward "[ \f\t\n\r\v]" nil t)
  244. (forward-char 1)
  245. (looking-at org-babel-inline-src-block-regexp))
  246. (org-babel-parse-inline-src-block-match)
  247. nil)))) ;; indicate that no source block was found
  248. (defun org-babel-get-src-block-function-args ()
  249. (when (org-babel-get-src-block-name)
  250. (mapcar (lambda (ref) (cons :var ref))
  251. (org-babel-ref-split-args (match-string 2)))))
  252. (defmacro org-babel-map-source-blocks (file &rest body)
  253. "Evaluate BODY forms on each source-block in FILE."
  254. (declare (indent 1))
  255. `(save-window-excursion
  256. (find-file ,file) (goto-char (point-min))
  257. (while (re-search-forward org-babel-src-block-regexp nil t)
  258. (goto-char (match-beginning 0))
  259. (save-match-data ,@body)
  260. (goto-char (match-end 0)))))
  261. (defun org-babel-parse-src-block-match ()
  262. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  263. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  264. (list lang
  265. (org-babel-strip-protective-commas (org-babel-clean-text-properties (match-string 4)))
  266. (org-babel-merge-params
  267. org-babel-default-header-args
  268. (if (boundp lang-headers) (eval lang-headers) nil)
  269. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) "")))))))
  270. (defun org-babel-parse-inline-src-block-match ()
  271. (let* ((lang (org-babel-clean-text-properties (match-string 1)))
  272. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  273. (list lang
  274. (org-babel-strip-protective-commas (org-babel-clean-text-properties (match-string 4)))
  275. (org-babel-merge-params
  276. org-babel-default-inline-header-args
  277. (if (boundp lang-headers) (eval lang-headers) nil)
  278. (org-babel-parse-header-arguments (org-babel-clean-text-properties (or (match-string 3) "")))))))
  279. (defun org-babel-parse-header-arguments (arg-string)
  280. "Parse a string of header arguments returning an alist."
  281. (if (> (length arg-string) 0)
  282. (delq nil
  283. (mapcar
  284. (lambda (arg)
  285. (if (string-match "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)" arg)
  286. (cons (intern (concat ":" (match-string 1 arg)))
  287. (org-babel-chomp (match-string 2 arg)))
  288. (cons (intern (concat ":" arg)) nil)))
  289. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  290. (defun org-babel-process-params (params)
  291. "Parse params and resolve references.
  292. Return a list (session vars result-params result-type). These are
  293. made available to the org-babel-execute:LANG functions via
  294. multiple-value-bind."
  295. (let* ((session (cdr (assoc :session params)))
  296. (vars (org-babel-ref-variables params))
  297. (result-params (split-string (or (cdr (assoc :results params)) "")))
  298. (result-type (cond ((member "output" result-params) 'output)
  299. ((member "value" result-params) 'value)
  300. (t 'value))))
  301. (list session vars result-params result-type)))
  302. (defun org-babel-where-is-src-block-head ()
  303. "Return the point at the beginning of the current source
  304. block. Specifically at the beginning of the #+BEGIN_SRC line.
  305. If the point is not on a source block then return nil."
  306. (let ((initial (point)) top bottom)
  307. (or
  308. (save-excursion ;; on a #+srcname: line
  309. (beginning-of-line 1)
  310. (and (looking-at "#\\+srcname") (forward-line 1)
  311. (looking-at org-babel-src-block-regexp)
  312. (point)))
  313. (save-excursion ;; on a #+begin_src line
  314. (beginning-of-line 1)
  315. (and (looking-at org-babel-src-block-regexp)
  316. (point)))
  317. (save-excursion ;; inside a src block
  318. (and
  319. (re-search-backward "#\\+begin_src" nil t) (setq top (point))
  320. (re-search-forward "#\\+end_src" nil t) (setq bottom (point))
  321. (< top initial) (< initial bottom)
  322. (goto-char top) (looking-at org-babel-src-block-regexp)
  323. (point))))))
  324. (defun org-babel-goto-named-source-block (&optional name)
  325. "Go to a named source-code block."
  326. (interactive "ssource-block name: ")
  327. (let ((point (org-babel-find-named-block name)))
  328. (if point
  329. ;; taken from `org-open-at-point'
  330. (progn (goto-char point) (org-show-context))
  331. (message "source-code block '%s' not found in this buffer" name))))
  332. (defun org-babel-find-named-block (name)
  333. "Find a named source-code block.
  334. Return the location of the source block identified by
  335. #+srcname NAME, or nil if no such block exists. Set match data
  336. according to org-babel-named-src-block-regexp."
  337. (save-excursion
  338. (let ((case-fold-search t)
  339. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  340. (goto-char (point-min))
  341. (when (or (re-search-forward regexp nil t)
  342. (re-search-backward regexp nil t))
  343. (match-beginning 0)))))
  344. (defun org-babel-find-named-result (name)
  345. "Return the location of the result named NAME in the current
  346. buffer or nil if no such result exists."
  347. (save-excursion
  348. (goto-char (point-min))
  349. (when (re-search-forward ;; ellow end-of-buffer in following regexp?
  350. (concat "#\\+resname:[ \t]*" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  351. (move-beginning-of-line 1) (point))))
  352. (defun org-babel-where-is-src-block-result (&optional insert)
  353. "Return the point at the beginning of the result of the current
  354. source block. Specifically at the beginning of the #+RESNAME:
  355. line. If no result exists for this block then create a
  356. #+RESNAME: line following the source block."
  357. (save-excursion
  358. (let* ((on-lob-line (progn (beginning-of-line 1)
  359. (looking-at org-babel-lob-one-liner-regexp)))
  360. (name (if on-lob-line (org-babel-lob-get-info) (org-babel-get-src-block-name)))
  361. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  362. (when head (goto-char head))
  363. (or (and name (message name) (org-babel-find-named-result name))
  364. (and (or on-lob-line (re-search-forward "#\\+end_src" nil t))
  365. (progn (move-end-of-line 1)
  366. (if (eobp) (insert "\n") (forward-char 1))
  367. (setq end (point))
  368. (or (progn ;; either an unnamed #+resname: line already exists
  369. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  370. (move-beginning-of-line 1) (looking-at "#\\+resname:"))
  371. (when insert ;; or (with optional insert) we need to back up and make one ourselves
  372. (goto-char end) (open-line 2) (forward-char 1)
  373. (insert (concat "#+resname:" (if name (concat " " name))))
  374. (move-beginning-of-line 1) t)))
  375. (point))))))
  376. (defun org-babel-read-result ()
  377. "Read the result at `point' into emacs-lisp."
  378. (cond
  379. ((org-at-table-p) (org-babel-read-table))
  380. ((looking-at ": ")
  381. (let ((result-string
  382. (org-babel-trim
  383. (mapconcat (lambda (line) (if (and (> (length line) 1)
  384. (string= ": " (substring line 0 2)))
  385. (substring line 2)
  386. line))
  387. (split-string
  388. (buffer-substring (point) (org-babel-result-end)) "[\r\n]+")
  389. "\n"))))
  390. (or (org-babel-number-p result-string) result-string)))
  391. ((looking-at "^#\\+RESNAME:")
  392. (save-excursion (forward-line 1) (org-babel-read-result)))))
  393. (defun org-babel-read-table ()
  394. "Read the table at `point' into emacs-lisp."
  395. (mapcar (lambda (row)
  396. (if (and (symbolp row) (equal row 'hline)) row
  397. (mapcar #'org-babel-read row)))
  398. (org-table-to-lisp)))
  399. (defun org-babel-insert-result (result &optional insert)
  400. "Insert RESULT into the current buffer after the end of the
  401. current source block. With optional argument INSERT controls
  402. insertion of results in the org-mode file. INSERT can take the
  403. following values...
  404. t ------ the default option, simply insert the results after the
  405. source block
  406. replace - insert results after the source block replacing any
  407. previously inserted results
  408. silent -- no results are inserted"
  409. (if (stringp result)
  410. (progn
  411. (setq result (org-babel-clean-text-properties result))
  412. (if (member "file" insert) (setq result (org-babel-result-to-file result))))
  413. (unless (listp result) (setq result (format "%S" result))))
  414. (if (and insert (member "replace" insert) (not (member "silent" insert)))
  415. (org-babel-remove-result))
  416. (if (= (length result) 0)
  417. (if (member "value" result-params)
  418. (message "No result returned by source block")
  419. (message "Source block produced no output"))
  420. (if (and insert (member "silent" insert))
  421. (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result))) result)
  422. (when (and (stringp result) ;; ensure results end in a newline
  423. (not (or (string-equal (substring result -1) "\n")
  424. (string-equal (substring result -1) "\r"))))
  425. (setq result (concat result "\n")))
  426. (save-excursion
  427. (let ((existing-result (org-babel-where-is-src-block-result t)))
  428. (when existing-result (goto-char existing-result) (forward-line 1)))
  429. (if (stringp result) ;; assume the result is a table if it's not a string
  430. (if (member "file" insert)
  431. (insert result)
  432. (org-babel-examplize-region (point) (progn (insert result) (point))))
  433. (progn
  434. (insert
  435. (concat (orgtbl-to-orgtbl
  436. (if (consp (car result)) result (list result))
  437. '(:fmt (lambda (cell) (format "%S" cell)))) "\n"))
  438. (forward-line -1)
  439. (org-cycle))))
  440. (message "finished"))))
  441. (defun org-babel-result-to-org-string (result)
  442. "Return RESULT as a string in org-mode format. This function
  443. relies on `org-babel-insert-result'."
  444. (with-temp-buffer (org-babel-insert-result result) (buffer-string)))
  445. (defun org-babel-remove-result ()
  446. "Remove the result of the current source block."
  447. (interactive)
  448. (save-excursion
  449. (goto-char (org-babel-where-is-src-block-result t)) (forward-line 1)
  450. (delete-region (point) (org-babel-result-end))))
  451. (defun org-babel-result-end ()
  452. "Return the point at the end of the current set of results"
  453. (save-excursion
  454. (if (org-at-table-p)
  455. (org-table-end)
  456. (let ((case-fold-search nil))
  457. (if (looking-at "#\\+begin_example")
  458. (search-forward "#+end_example" nil t)
  459. (progn
  460. (while (if (looking-at "\\(: \\|\\[\\[\\)")
  461. (progn (while (looking-at "\\(: \\|\\[\\[\\)")
  462. (forward-line 1)) t))
  463. (forward-line 1))
  464. (forward-line -1))))
  465. (point))))
  466. (defun org-babel-result-to-file (result)
  467. "Return an `org-mode' link with the path being the value or
  468. RESULT, and the display being the `file-name-nondirectory' if
  469. non-nil."
  470. (let ((name (file-name-nondirectory result)))
  471. (concat "[[file:" result (if name (concat "][" name "]]") "]]"))))
  472. (defun org-babel-examplize-region (beg end)
  473. "Comment out region using the ': ' org example quote."
  474. (interactive "*r")
  475. (let ((size (abs (- (line-number-at-pos end)
  476. (line-number-at-pos beg)))))
  477. (save-excursion
  478. (cond ((= size 0)
  479. (error "This should be impossible: a newline was appended to result if missing")
  480. (let ((result (buffer-substring beg end)))
  481. (delete-region beg end)
  482. (insert (concat ": " result))))
  483. ((< size org-babel-min-lines-for-block-output)
  484. (goto-char beg)
  485. (dotimes (n size)
  486. (move-beginning-of-line 1) (insert ": ") (forward-line 1)))
  487. (t
  488. (goto-char beg)
  489. (insert "#+begin_example\n")
  490. (forward-char (- end beg))
  491. (insert "#+end_example\n"))))))
  492. (defun org-babel-merge-params (&rest plists)
  493. "Combine all parameter association lists in PLISTS. Later
  494. elements of PLISTS override the values of previous element. This
  495. takes into account some special considerations for certain
  496. parameters when merging lists."
  497. (let (params results exports tangle vars var ref)
  498. (flet ((e-merge (exclusive-groups &rest result-params)
  499. ;; maintain exclusivity of mutually exclusive parameters
  500. (let (output)
  501. (mapc (lambda (new-params)
  502. (mapc (lambda (new-param)
  503. (mapc (lambda (exclusive-group)
  504. (when (member new-param exclusive-group)
  505. (mapcar (lambda (excluded-param)
  506. (setq output (delete excluded-param output)))
  507. exclusive-group)))
  508. exclusive-groups)
  509. (setq output (org-uniquify (cons new-param output))))
  510. new-params))
  511. result-params)
  512. output)))
  513. (mapc (lambda (plist)
  514. (mapc (lambda (pair)
  515. (case (car pair)
  516. (:var
  517. ;; we want only one specification per variable
  518. (when (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=[ \t]*\\([^\f\n\r\v]+\\)$" (cdr pair))
  519. ;; TODO: When is this not true?
  520. (setq var (intern (match-string 1 (cdr pair)))
  521. ref (match-string 2 (cdr pair))
  522. vars (cons (cons var ref) (assq-delete-all var vars)))))
  523. (:results
  524. (setq results (e-merge '(("file" "vector" "scalar")
  525. ("replace" "silent")
  526. ("output" "value"))
  527. results (split-string (cdr pair)))))
  528. (:exports
  529. (setq exports (e-merge '(("code" "results" "both"))
  530. exports (split-string (cdr pair)))))
  531. (:tangle
  532. (setq tangle (e-merge '(("yes" "no"))
  533. tangle (split-string (cdr pair)))))
  534. (t ;; replace: this covers e.g. :session
  535. (setq params (cons pair (assq-delete-all (car pair) params))))))
  536. plist))
  537. plists))
  538. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  539. (while vars (setq params (cons (cons :var (pop vars)) params)))
  540. (cons (cons :tangle (mapconcat 'identity tangle " "))
  541. (cons (cons :exports (mapconcat 'identity exports " "))
  542. (cons (cons :results (mapconcat 'identity results " "))
  543. params)))))
  544. (defun org-babel-clean-text-properties (text)
  545. "Strip all properties from text return."
  546. (set-text-properties 0 (length text) nil text) text)
  547. (defun org-babel-strip-protective-commas (body)
  548. "Strip protective commas from bodies of source blocks."
  549. (replace-regexp-in-string "^,#" "#" body))
  550. (defun org-babel-read (cell)
  551. "Convert the string value of CELL to a number if appropriate.
  552. Otherwise if cell looks like lisp (meaning it starts with a
  553. \"(\" or a \"'\") then read it as lisp, otherwise return it
  554. unmodified as a string.
  555. This is taken almost directly from `org-read-prop'."
  556. (if (and (stringp cell) (not (equal cell "")))
  557. (or (org-babel-number-p cell)
  558. (if (or (equal "(" (substring cell 0 1))
  559. (equal "'" (substring cell 0 1)))
  560. (read cell)
  561. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  562. cell))
  563. (defun org-babel-number-p (string)
  564. "Return t if STRING represents a number"
  565. (if (string-match "^[[:digit:]]*\\.?[[:digit:]]*$" string)
  566. (string-to-number string)))
  567. (defun org-babel-import-elisp-from-file (file-name)
  568. "Read the results located at FILE-NAME into an elisp table. If
  569. the table is trivial, then return it as a scalar."
  570. (let (result)
  571. (with-temp-buffer
  572. (condition-case nil
  573. (progn
  574. (org-table-import file-name nil)
  575. (delete-file file-name)
  576. (setq result (mapcar (lambda (row)
  577. (mapcar #'org-babel-string-read row))
  578. (org-table-to-lisp))))
  579. (error nil)))
  580. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  581. (if (consp (car result))
  582. (if (null (cdr (car result)))
  583. (caar result)
  584. result)
  585. (car result))
  586. result)))
  587. (defun org-babel-string-read (cell)
  588. "Strip nested \"s from around strings in exported R values."
  589. (org-babel-read (or (and (stringp cell)
  590. (string-match "\\\"\\(.+\\)\\\"" cell)
  591. (match-string 1 cell))
  592. cell)))
  593. (defun org-babel-reverse-string (string)
  594. (apply 'string (reverse (string-to-list string))))
  595. (defun org-babel-chomp (string &optional regexp)
  596. "Remove any trailing space or carriage returns characters from
  597. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  598. overwritten by specifying a regexp as a second argument."
  599. (while (and (> (length string) 0) (string-match "[ \f\t\n\r\v]" (substring string -1)))
  600. (setq string (substring string 0 -1)))
  601. string)
  602. (defun org-babel-trim (string &optional regexp)
  603. "Like `org-babel-chomp' only it runs on both the front and back of the string"
  604. (org-babel-chomp (org-babel-reverse-string
  605. (org-babel-chomp (org-babel-reverse-string string) regexp)) regexp))
  606. (provide 'org-babel)
  607. ;;; org-babel.el ends here