org-babel.el 56 KB

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