org-babel.el 56 KB

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