org-babel.el 57 KB

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