org-babel.el 56 KB

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