org-babel.el 29 KB

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