ob.el 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. ;;; ob.el --- working with code blocks in org-mode
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs 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 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; See the online documentation for more information
  20. ;;
  21. ;; http://orgmode.org/worg/org-contrib/babel/
  22. ;;; Code:
  23. (eval-when-compile (require 'cl))
  24. (require 'org-macs)
  25. (defvar org-babel-call-process-region-original)
  26. (declare-function show-all "outline" ())
  27. (declare-function tramp-compat-make-temp-file "tramp" (filename &optional dir-flag))
  28. (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
  29. (declare-function tramp-file-name-user "tramp" (vec))
  30. (declare-function tramp-file-name-host "tramp" (vec))
  31. (declare-function org-edit-src-code "org" (context code edit-buffer-name))
  32. (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
  33. (declare-function org-save-outline-visibility "org" (use-markers &rest body))
  34. (declare-function org-narrow-to-subtree "org" ())
  35. (declare-function org-entry-get "org" (pom property &optional inherit))
  36. (declare-function org-make-options-regexp "org" (kwds &optional extra))
  37. (declare-function org-match-string-no-properties "org" (num &optional string))
  38. (declare-function org-do-remove-indentation "org" (&optional n))
  39. (declare-function org-show-context "org" (&optional key))
  40. (declare-function org-at-table-p "org" (&optional table-type))
  41. (declare-function org-cycle "org" (&optional arg))
  42. (declare-function org-uniquify "org" (list))
  43. (declare-function org-table-import "org" (file arg))
  44. (declare-function org-add-hook "org-compat" (hook function &optional append local))
  45. (declare-function org-table-align "org-table" ())
  46. (declare-function org-table-end "org-table" (&optional table-type))
  47. (declare-function orgtbl-to-generic "org-table" (table params))
  48. (declare-function orgtbl-to-orgtbl "org-table" (table params))
  49. (declare-function org-babel-lob-get-info "ob-lob" nil)
  50. (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
  51. (declare-function org-babel-ref-variables "ob-ref" (params))
  52. (declare-function org-babel-ref-resolve-reference "ob-ref" (ref &optional params))
  53. (defgroup org-babel nil
  54. "Code block evaluation and management in `org-mode' documents."
  55. :tag "Babel"
  56. :group 'org)
  57. (defcustom org-confirm-babel-evaluate t
  58. "Require confirmation before interactively evaluating code
  59. blocks in Org-mode buffers. The default value of this variable
  60. is t, meaning confirmation is required for any code block
  61. evaluation. This variable can be set to nil to inhibit any
  62. future confirmation requests. This variable can also be set to a
  63. function which takes two arguments the language of the code block
  64. and the body of the code block. Such a function should then
  65. return a non-nil value if the user should be prompted for
  66. execution or nil if no prompt is required.
  67. Warning: Disabling confirmation may result in accidental
  68. evaluation of potentially harmful code. It may be advisable
  69. remove code block execution from C-c C-c as further protection
  70. against accidental code block evaluation. The
  71. `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
  72. remove code block execution from the C-c C-c keybinding."
  73. :group 'org-babel
  74. :type '(choice boolean function))
  75. ;; don't allow this variable to be changed through file settings
  76. (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
  77. (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
  78. "This variable can be set to remove code block evaluation from
  79. the C-c C-c key binding."
  80. :group 'org-babel
  81. :type 'boolean)
  82. (defvar org-babel-source-name-regexp
  83. "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
  84. "Regular expression used to match a source name line.")
  85. (defvar org-babel-src-block-regexp
  86. (concat
  87. ;; (1) indentation (2) lang
  88. "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
  89. ;; (3) switches
  90. "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
  91. ;; (4) header arguments
  92. "\\([^\n]*\\)\n"
  93. ;; (5) body
  94. "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
  95. "Regexp used to identify code blocks.")
  96. (defvar org-babel-inline-src-block-regexp
  97. (concat
  98. ;; (1) replacement target (2) lang
  99. "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
  100. ;; (3,4) (unused, headers)
  101. "\\(\\|\\[\\(.*?\\)\\]\\)"
  102. ;; (5) body
  103. "{\\([^\f\n\r\v]+?\\)}\\)")
  104. "Regexp used to identify inline src-blocks.")
  105. (defun org-babel-get-src-block-info (&optional header-vars-only)
  106. "Get information of the current source block.
  107. Returns a list
  108. (language body header-arguments-alist switches name function-args indent).
  109. Unless HEADER-VARS-ONLY is non-nil, any variable
  110. references provided in 'function call style' (i.e. in a
  111. parenthesised argument list following the src block name) are
  112. added to the header-arguments-alist."
  113. (let ((case-fold-search t) head info args indent)
  114. (if (setq head (org-babel-where-is-src-block-head))
  115. (save-excursion
  116. (goto-char head)
  117. (setq info (org-babel-parse-src-block-match))
  118. (setq indent (car (last info)))
  119. (setq info (butlast info))
  120. (forward-line -1)
  121. (if (looking-at
  122. (concat org-babel-source-name-regexp
  123. "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
  124. (progn
  125. (setq info (append info (list (org-babel-clean-text-properties
  126. (match-string 2)))))
  127. ;; Note that e.g. "name()" and "name( )" result in
  128. ;; ((:var . "")). We maintain that behaviour, and the
  129. ;; resulting non-nil sixth element is relied upon in
  130. ;; org-babel-exp-code to detect a functional-style
  131. ;; block in those cases. However, "name" without any
  132. ;; parentheses would result in the same thing, so we
  133. ;; explicitly avoid that.
  134. (if (setq args (match-string 4))
  135. (setq info
  136. (append info (list
  137. (mapcar
  138. (lambda (ref) (cons :var ref))
  139. (org-babel-ref-split-args args))))))
  140. (unless header-vars-only
  141. (setf (nth 2 info)
  142. (org-babel-merge-params (nth 5 info) (nth 2 info)))))
  143. (setq info (append info (list nil nil))))
  144. (append info (list indent)))
  145. (if (save-excursion ;; inline source block
  146. (re-search-backward "[ \f\t\n\r\v]" nil t)
  147. (looking-at org-babel-inline-src-block-regexp))
  148. (org-babel-parse-inline-src-block-match)
  149. nil))))
  150. (defun org-babel-confirm-evaluate (info)
  151. "Confirm that the user wishes to evaluate the code block
  152. defined by INFO. This behavior can be suppressed by setting the
  153. value of `org-confirm-babel-evaluate' to nil, in which case all
  154. future interactive code block evaluations will proceed without
  155. any confirmation from the user.
  156. Note disabling confirmation may result in accidental evaluation
  157. of potentially harmful code."
  158. (let* ((eval (cdr (assoc :eval (nth 2 info))))
  159. (query (or (equal eval "query")
  160. (and (functionp org-confirm-babel-evaluate)
  161. (funcall org-confirm-babel-evaluate
  162. (nth 0 info) (nth 1 info)))
  163. org-confirm-babel-evaluate)))
  164. (when (or (equal eval "never")
  165. (and query
  166. (not (yes-or-no-p
  167. (format "Evaluate this%scode on your system? "
  168. (if info (format " %s " (nth 0 info)) " "))))))
  169. (error "evaluation aborted"))))
  170. ;;;###autoload
  171. (defun org-babel-execute-src-block-maybe ()
  172. "Detect if this is context for a org-babel src-block and if so
  173. then run `org-babel-execute-src-block'."
  174. (interactive)
  175. (if (not org-babel-no-eval-on-ctrl-c-ctrl-c)
  176. (let ((info (org-babel-get-src-block-info)))
  177. (if info
  178. (progn (org-babel-execute-src-block current-prefix-arg info) t) nil))
  179. nil))
  180. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-src-block-maybe)
  181. ;;;###autoload
  182. (defun org-babel-expand-src-block-maybe ()
  183. "Detect if this is context for a org-babel src-block and if so
  184. then run `org-babel-expand-src-block'."
  185. (interactive)
  186. (let ((info (org-babel-get-src-block-info)))
  187. (if info
  188. (progn (org-babel-expand-src-block current-prefix-arg info) t)
  189. nil)))
  190. ;;;###autoload
  191. (defun org-babel-load-in-session-maybe ()
  192. "Detect if this is context for a org-babel src-block and if so
  193. then run `org-babel-load-in-session'."
  194. (interactive)
  195. (let ((info (org-babel-get-src-block-info)))
  196. (if info
  197. (progn (org-babel-load-in-session current-prefix-arg info) t)
  198. nil)))
  199. (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
  200. ;;;###autoload
  201. (defun org-babel-pop-to-session-maybe ()
  202. "Detect if this is context for a org-babel src-block and if so
  203. then run `org-babel-pop-to-session'."
  204. (interactive)
  205. (let ((info (org-babel-get-src-block-info)))
  206. (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
  207. (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
  208. (defconst org-babel-header-arg-names
  209. '(cache cmdline colnames dir exports file noweb results
  210. session tangle var noeval)
  211. "Common header arguments used by org-babel. Note that
  212. individual languages may define their own language specific
  213. header arguments as well.")
  214. (defvar org-babel-default-header-args
  215. '((:session . "none") (:results . "replace") (:exports . "code")
  216. (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
  217. "Default arguments to use when evaluating a source block.")
  218. (defvar org-babel-default-inline-header-args
  219. '((:session . "none") (:results . "silent") (:exports . "results"))
  220. "Default arguments to use when evaluating an inline source block.")
  221. (defvar org-babel-current-buffer-properties)
  222. (make-variable-buffer-local 'org-babel-current-buffer-properties)
  223. (defvar org-babel-result-regexp
  224. "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:"
  225. "Regular expression used to match result lines. If the
  226. results are associated with a hash key then the hash will be
  227. saved in the second match data.")
  228. (defvar org-babel-min-lines-for-block-output 10
  229. "If number of lines of output is equal to or exceeds this
  230. value, the output is placed in a #+begin_example...#+end_example
  231. block. Otherwise the output is marked as literal by inserting
  232. colons at the starts of the lines. This variable only takes
  233. effect if the :results output option is in effect.")
  234. (defvar org-babel-noweb-error-langs nil
  235. "List of language for which errors should be raised when the
  236. source code block satisfying a noweb reference in this language
  237. can not be resolved.")
  238. (defvar org-babel-hash-show 4
  239. "Number of initial characters to show of a hidden results hash.")
  240. (defvar org-babel-after-execute-hook nil
  241. "Hook for functions to be called after `org-babel-execute-src-block'")
  242. (defun org-babel-named-src-block-regexp-for-name (name)
  243. "This generates a regexp used to match a src block named NAME."
  244. (concat org-babel-source-name-regexp (regexp-quote name) "[ \t\n]*"
  245. (substring org-babel-src-block-regexp 1)))
  246. ;;; functions
  247. (defvar call-process-region)
  248. ;;;###autoload
  249. (defun org-babel-execute-src-block (&optional arg info params)
  250. "Execute the current source code block, and insert the results
  251. into the buffer. Source code execution and the collection and
  252. formatting of results can be controlled through a variety of
  253. header arguments.
  254. Optionally supply a value for INFO in the form returned by
  255. `org-babel-get-src-block-info'.
  256. Optionally supply a value for PARAMS which will be merged with
  257. the header arguments specified at the front of the source code
  258. block."
  259. (interactive)
  260. (let* ((info (or info (org-babel-get-src-block-info)))
  261. ;; note the `evaluation-confirmed' variable is currently not
  262. ;; used, but could be used later to avoid the need for
  263. ;; chaining confirmations
  264. (evaluation-confirmed (org-babel-confirm-evaluate info))
  265. (lang (nth 0 info))
  266. (params (setf (nth 2 info)
  267. (sort (org-babel-merge-params (nth 2 info) params)
  268. (lambda (el1 el2) (string< (symbol-name (car el1))
  269. (symbol-name (car el2)))))))
  270. (new-hash
  271. (if (and (cdr (assoc :cache params))
  272. (string= "yes" (cdr (assoc :cache params))))
  273. (org-babel-sha1-hash info)))
  274. (old-hash (org-babel-result-hash info))
  275. (body (setf (nth 1 info)
  276. (if (and (cdr (assoc :noweb params))
  277. (string= "yes" (cdr (assoc :noweb params))))
  278. (org-babel-expand-noweb-references info)
  279. (nth 1 info))))
  280. (result-params (split-string (or (cdr (assoc :results params)) "")))
  281. (result-type (cond ((member "output" result-params) 'output)
  282. ((member "value" result-params) 'value)
  283. (t 'value)))
  284. (cmd (intern (concat "org-babel-execute:" lang)))
  285. (dir (cdr (assoc :dir params)))
  286. (default-directory
  287. (or (and dir (file-name-as-directory dir)) default-directory))
  288. (org-babel-call-process-region-original
  289. (if (boundp 'org-babel-call-process-region-original) org-babel-call-process-region-original
  290. (symbol-function 'call-process-region)))
  291. (indent (car (last info)))
  292. result)
  293. (unwind-protect
  294. (flet ((call-process-region (&rest args)
  295. (apply 'org-babel-tramp-handle-call-process-region args)))
  296. (unless (fboundp cmd)
  297. (error "No org-babel-execute function for %s!" lang))
  298. (if (and (not arg) new-hash (equal new-hash old-hash))
  299. (save-excursion ;; return cached result
  300. (goto-char (org-babel-where-is-src-block-result nil info))
  301. (end-of-line 1) (forward-char 1)
  302. (setq result (org-babel-read-result))
  303. (message (replace-regexp-in-string "%" "%%"
  304. (format "%S" result))) result)
  305. (setq result (funcall cmd body params))
  306. (if (eq result-type 'value)
  307. (setq result (if (and (or (member "vector" result-params)
  308. (member "table" result-params))
  309. (not (listp result)))
  310. (list (list result))
  311. result)))
  312. (org-babel-insert-result
  313. result result-params info new-hash indent lang)
  314. (run-hooks 'org-babel-after-execute-hook)
  315. result))
  316. (setq call-process-region 'org-babel-call-process-region-original))))
  317. (defun org-babel-expand-body:generic (body params &optional processed-params)
  318. "Expand a block of code with org-babel according to it's header
  319. arguments. This generic implementation of body expansion is
  320. called for languages which have not defined their own specific
  321. org-babel-expand-body:lang function." body)
  322. ;;;###autoload
  323. (defun org-babel-expand-src-block (&optional arg info params)
  324. "Expand the current source code block according to it's header
  325. arguments, and pop open the results in a preview buffer."
  326. (interactive)
  327. (let* ((info (or info (org-babel-get-src-block-info)))
  328. (lang (nth 0 info))
  329. (params (setf (nth 2 info)
  330. (sort (org-babel-merge-params (nth 2 info) params)
  331. (lambda (el1 el2) (string< (symbol-name (car el1))
  332. (symbol-name (car el2)))))))
  333. (body (setf (nth 1 info)
  334. (if (and (cdr (assoc :noweb params))
  335. (string= "yes" (cdr (assoc :noweb params))))
  336. (org-babel-expand-noweb-references info) (nth 1 info))))
  337. (cmd (intern (concat "org-babel-expand-body:" lang)))
  338. (expanded (funcall (if (fboundp cmd) cmd 'org-babel-expand-body:generic)
  339. body params)))
  340. (org-edit-src-code
  341. nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
  342. ;;;###autoload
  343. (defun org-babel-load-in-session (&optional arg info)
  344. "Load the body of the current source-code block. Evaluate the
  345. header arguments for the source block before entering the
  346. session. After loading the body this pops open the session."
  347. (interactive)
  348. (let* ((info (or info (org-babel-get-src-block-info)))
  349. (lang (nth 0 info))
  350. (body (nth 1 info))
  351. (params (nth 2 info))
  352. (session (cdr (assoc :session params)))
  353. (cmd (intern (concat "org-babel-load-session:" lang))))
  354. (unless (fboundp cmd)
  355. (error "No org-babel-load-session function for %s!" lang))
  356. (pop-to-buffer (funcall cmd session body params))
  357. (end-of-line 1)))
  358. ;;;###autoload
  359. (defun org-babel-switch-to-session (&optional arg info)
  360. "Switch to the session of the current source-code block.
  361. If called with a prefix argument then evaluate the header arguments
  362. for the source block before entering the session. Copy the body
  363. of the source block to the kill ring."
  364. (interactive)
  365. (let* ((info (or info (org-babel-get-src-block-info)))
  366. (lang (nth 0 info))
  367. (body (nth 1 info))
  368. (params (nth 2 info))
  369. (session (cdr (assoc :session params)))
  370. (dir (cdr (assoc :dir params)))
  371. (default-directory
  372. (or (and dir (file-name-as-directory dir)) default-directory))
  373. (cmd (intern (format "org-babel-%s-initiate-session" lang)))
  374. (cmd2 (intern (concat "org-babel-prep-session:" lang))))
  375. (unless (fboundp cmd)
  376. (error "No org-babel-initiate-session function for %s!" lang))
  377. ;; copy body to the kill ring
  378. (with-temp-buffer (insert (org-babel-trim body))
  379. (copy-region-as-kill (point-min) (point-max)))
  380. ;; if called with a prefix argument, then process header arguments
  381. (unless (fboundp cmd2)
  382. (error "No org-babel-prep-session function for %s!" lang))
  383. (when arg (funcall cmd2 session params))
  384. ;; just to the session using pop-to-buffer
  385. (pop-to-buffer (funcall cmd session params))
  386. (end-of-line 1)))
  387. (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
  388. (defvar org-bracket-link-regexp)
  389. ;;;###autoload
  390. (defun org-babel-open-src-block-result (&optional re-run)
  391. "If `point' is on a src block then open the results of the
  392. source code block, otherwise return nil. With optional prefix
  393. argument RE-RUN the source-code block is evaluated even if
  394. results already exist."
  395. (interactive "P")
  396. (when (org-babel-get-src-block-info)
  397. (save-excursion
  398. ;; go to the results, if there aren't any then run the block
  399. (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
  400. (progn (org-babel-execute-src-block)
  401. (org-babel-where-is-src-block-result))))
  402. (end-of-line 1)
  403. (while (looking-at "[\n\r\t\f ]") (forward-char 1))
  404. ;; open the results
  405. (if (looking-at org-bracket-link-regexp)
  406. ;; file results
  407. (org-open-at-point)
  408. (let ((results (org-babel-read-result)))
  409. (flet ((echo-res (result)
  410. (if (stringp result) result (format "%S" result))))
  411. (pop-to-buffer (get-buffer-create "org-babel-results"))
  412. (delete-region (point-min) (point-max))
  413. (if (listp results)
  414. ;; table result
  415. (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
  416. ;; scalar result
  417. (insert (echo-res results))))))
  418. t)))
  419. ;;;###autoload
  420. (defun org-babel-execute-buffer (&optional arg)
  421. "Call `org-babel-execute-src-block' on every source block in
  422. the current buffer."
  423. (interactive "P")
  424. (save-excursion
  425. (org-save-outline-visibility t
  426. (goto-char (point-min))
  427. (show-all)
  428. (while (re-search-forward org-babel-src-block-regexp nil t)
  429. (let ((pos-end (match-end 0)))
  430. (goto-char (match-beginning 0))
  431. (org-babel-execute-src-block arg)
  432. (goto-char pos-end))))))
  433. ;;;###autoload
  434. (defun org-babel-execute-subtree (&optional arg)
  435. "Call `org-babel-execute-src-block' on every source block in
  436. the current subtree."
  437. (interactive "P")
  438. (save-restriction
  439. (save-excursion
  440. (org-narrow-to-subtree)
  441. (org-babel-execute-buffer)
  442. (widen))))
  443. ;;;###autoload
  444. (defun org-babel-sha1-hash (&optional info)
  445. "Generate an sha1 hash based on the value of info."
  446. (interactive)
  447. (let* ((info (or info (org-babel-get-src-block-info)))
  448. (hash (sha1 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
  449. (nth 2 info) ":")
  450. (nth 1 info)))))
  451. (when (interactive-p) (message hash))
  452. hash))
  453. (defun org-babel-result-hash (&optional info)
  454. "Return the in-buffer hash associated with the results
  455. specified in INFO."
  456. (org-babel-where-is-src-block-result nil info)
  457. (org-babel-clean-text-properties (match-string 3)))
  458. (defun org-babel-hide-hash ()
  459. "Hide the hash in the current results line. Only the initial
  460. `org-babel-hash-show' characters of the hash will remain
  461. visible."
  462. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  463. (save-excursion
  464. (when (and (re-search-forward org-babel-result-regexp nil t)
  465. (match-string 3))
  466. (let* ((start (match-beginning 3))
  467. (hide-start (+ org-babel-hash-show start))
  468. (end (match-end 3))
  469. (hash (match-string 3))
  470. ov1 ov2)
  471. (setq ov1 (make-overlay start hide-start))
  472. (setq ov2 (make-overlay hide-start end))
  473. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  474. (overlay-put ov1 'babel-hash hash)))))
  475. (defun org-babel-hide-all-hashes ()
  476. "Hide the hash in the current buffer. Only the initial
  477. `org-babel-hash-show' characters of each hash will remain
  478. visible. This function should be called as part of the
  479. `org-mode-hook'."
  480. (save-excursion
  481. (while (re-search-forward org-babel-result-regexp nil t)
  482. (goto-char (match-beginning 0))
  483. (org-babel-hide-hash)
  484. (goto-char (match-end 0)))))
  485. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  486. (defun org-babel-hash-at-point (&optional point)
  487. "Return the value of the hash at `point'. The hash is also
  488. added as the last element of the kill ring. This can be called
  489. with C-c C-c."
  490. (interactive)
  491. (let ((hash (car (delq nil (mapcar
  492. (lambda (ol) (overlay-get ol 'babel-hash))
  493. (overlays-at (or point (point))))))))
  494. (when hash (kill-new hash) (message hash))))
  495. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  496. (defun org-babel-result-hide-spec ()
  497. "Add `org-babel-hide-result' as an invisibility spec for hiding
  498. portions of results lines."
  499. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  500. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  501. (defvar org-babel-hide-result-overlays nil
  502. "Overlays hiding results.")
  503. (defun org-babel-result-hide-all ()
  504. "Fold all results in the current buffer."
  505. (interactive)
  506. (org-babel-show-result-all)
  507. (save-excursion
  508. (while (re-search-forward org-babel-result-regexp nil t)
  509. (save-excursion (goto-char (match-beginning 0))
  510. (org-babel-hide-result-toggle-maybe)))))
  511. (defun org-babel-show-result-all ()
  512. "Unfold all results in the current buffer."
  513. (mapc 'delete-overlay org-babel-hide-result-overlays)
  514. (setq org-babel-hide-result-overlays nil))
  515. ;;;###autoload
  516. (defun org-babel-hide-result-toggle-maybe ()
  517. "Toggle visibility of result at point."
  518. (interactive)
  519. (let ((case-fold-search t))
  520. (if (save-excursion
  521. (beginning-of-line 1)
  522. (looking-at org-babel-result-regexp))
  523. (progn (org-babel-hide-result-toggle)
  524. t) ;; to signal that we took action
  525. nil))) ;; to signal that we did not
  526. (defun org-babel-hide-result-toggle (&optional force)
  527. "Toggle the visibility of the current result."
  528. (interactive)
  529. (save-excursion
  530. (beginning-of-line)
  531. (if (re-search-forward org-babel-result-regexp nil t)
  532. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  533. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  534. ov)
  535. (if (memq t (mapcar (lambda (overlay)
  536. (eq (overlay-get overlay 'invisible)
  537. 'org-babel-hide-result))
  538. (overlays-at start)))
  539. (if (or (not force) (eq force 'off))
  540. (mapc (lambda (ov)
  541. (when (member ov org-babel-hide-result-overlays)
  542. (setq org-babel-hide-result-overlays
  543. (delq ov org-babel-hide-result-overlays)))
  544. (when (eq (overlay-get ov 'invisible)
  545. 'org-babel-hide-result)
  546. (delete-overlay ov)))
  547. (overlays-at start)))
  548. (setq ov (make-overlay start end))
  549. (overlay-put ov 'invisible 'org-babel-hide-result)
  550. ;; make the block accessible to isearch
  551. (overlay-put
  552. ov 'isearch-open-invisible
  553. (lambda (ov)
  554. (when (member ov org-babel-hide-result-overlays)
  555. (setq org-babel-hide-result-overlays
  556. (delq ov org-babel-hide-result-overlays)))
  557. (when (eq (overlay-get ov 'invisible)
  558. 'org-babel-hide-result)
  559. (delete-overlay ov))))
  560. (push ov org-babel-hide-result-overlays)))
  561. (error "Not looking at a result line"))))
  562. ;; org-tab-after-check-for-cycling-hook
  563. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  564. ;; Remove overlays when changing major mode
  565. (add-hook 'org-mode-hook
  566. (lambda () (org-add-hook 'change-major-mode-hook
  567. 'org-babel-show-result-all 'append 'local)))
  568. (defmacro org-babel-map-source-blocks (file &rest body)
  569. "Evaluate BODY forms on each source-block in FILE."
  570. (declare (indent 1))
  571. `(let ((visited-p (get-file-buffer (expand-file-name ,file)))
  572. to-be-removed)
  573. (save-window-excursion
  574. (find-file ,file)
  575. (setq to-be-removed (current-buffer))
  576. (goto-char (point-min))
  577. (while (re-search-forward org-babel-src-block-regexp nil t)
  578. (goto-char (match-beginning 0))
  579. (save-match-data ,@body)
  580. (goto-char (match-end 0))))
  581. (unless visited-p
  582. (kill-buffer to-be-removed))))
  583. (defvar org-file-properties)
  584. (defun org-babel-params-from-properties (&optional lang)
  585. "Return an association list of any source block params which
  586. may be specified in the properties of the current outline entry."
  587. (save-match-data
  588. (let (val sym)
  589. (delq nil
  590. (mapcar
  591. (lambda (header-arg)
  592. (and (setq val
  593. (or (condition-case nil
  594. (org-entry-get (point) header-arg t)
  595. (error nil))
  596. (cdr (assoc header-arg org-file-properties))))
  597. (cons (intern (concat ":" header-arg)) val)))
  598. (mapcar
  599. 'symbol-name
  600. (append
  601. org-babel-header-arg-names
  602. (progn
  603. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  604. (and (boundp sym) (eval sym))))))))))
  605. (defun org-babel-params-from-buffer ()
  606. "Return an association list of any source block params which
  607. may be specified at the top of the current buffer."
  608. (or org-babel-current-buffer-properties
  609. (setq org-babel-current-buffer-properties
  610. (save-match-data
  611. (save-excursion
  612. (save-restriction
  613. (widen)
  614. (goto-char (point-min))
  615. (when (re-search-forward
  616. (org-make-options-regexp (list "BABEL")) nil t)
  617. (org-babel-parse-header-arguments
  618. (org-match-string-no-properties 2)))))))))
  619. (defvar org-src-preserve-indentation)
  620. (defun org-babel-parse-src-block-match ()
  621. "Parse the match data resulting from a match of the
  622. `org-babel-src-block-regexp'."
  623. (let* ((block-indentation (length (match-string 1)))
  624. (lang (org-babel-clean-text-properties (match-string 2)))
  625. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  626. (switches (match-string 3))
  627. (body (org-babel-clean-text-properties (match-string 5)))
  628. (preserve-indentation (or org-src-preserve-indentation
  629. (string-match "-i\\>" switches))))
  630. (list lang
  631. ;; get block body less properties, protective commas, and indentation
  632. (with-temp-buffer
  633. (save-match-data
  634. (insert (org-babel-strip-protective-commas body))
  635. (unless preserve-indentation (org-do-remove-indentation))
  636. (buffer-string)))
  637. (org-babel-merge-params
  638. org-babel-default-header-args
  639. (org-babel-params-from-buffer)
  640. (org-babel-params-from-properties lang)
  641. (if (boundp lang-headers) (eval lang-headers) nil)
  642. (org-babel-parse-header-arguments
  643. (org-babel-clean-text-properties (or (match-string 4) ""))))
  644. switches
  645. block-indentation)))
  646. (defun org-babel-parse-inline-src-block-match ()
  647. "Parse the match data resulting from a match of the
  648. `org-babel-inline-src-block-regexp'."
  649. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  650. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  651. (list lang
  652. (org-babel-strip-protective-commas
  653. (org-babel-clean-text-properties (match-string 5)))
  654. (org-babel-merge-params
  655. org-babel-default-inline-header-args
  656. (org-babel-params-from-buffer)
  657. (org-babel-params-from-properties lang)
  658. (if (boundp lang-headers) (eval lang-headers) nil)
  659. (org-babel-parse-header-arguments
  660. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  661. (defun org-babel-parse-header-arguments (arg-string)
  662. "Parse a string of header arguments returning an alist."
  663. (if (> (length arg-string) 0)
  664. (delq nil
  665. (mapcar
  666. (lambda (arg)
  667. (if (string-match
  668. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  669. arg)
  670. (cons (intern (concat ":" (match-string 1 arg)))
  671. (let ((raw (org-babel-chomp (match-string 2 arg))))
  672. (if (org-babel-number-p raw)
  673. raw (org-babel-read raw))))
  674. (cons (intern (concat ":" arg)) nil)))
  675. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  676. (defun org-babel-process-params (params)
  677. "Parse params and resolve references.
  678. Return a list (session vars result-params result-type colnames rownames)."
  679. (let* ((session (cdr (assoc :session params)))
  680. (vars-and-names (org-babel-disassemble-tables
  681. (org-babel-ref-variables params)
  682. (cdr (assoc :hlines params))
  683. (cdr (assoc :colnames params))
  684. (cdr (assoc :rownames params))))
  685. (vars (car vars-and-names))
  686. (colnames (cadr vars-and-names))
  687. (rownames (caddr vars-and-names))
  688. (result-params (split-string (or (cdr (assoc :results params)) "")))
  689. (result-type (cond ((member "output" result-params) 'output)
  690. ((member "value" result-params) 'value)
  691. (t 'value))))
  692. (list session vars result-params result-type colnames rownames)))
  693. ;; row and column names
  694. (defun org-babel-del-hlines (table)
  695. "Remove all 'hlines from TABLE."
  696. (remove 'hline table))
  697. (defun org-babel-get-colnames (table)
  698. "Return a cons cell, the `car' of which contains the TABLE less
  699. colnames, and the `cdr' of which contains a list of the column
  700. names."
  701. (if (equal 'hline (nth 1 table))
  702. (cons (cddr table) (car table))
  703. (cons (cdr table) (car table))))
  704. (defun org-babel-get-rownames (table)
  705. "Return a cons cell, the `car' of which contains the TABLE less
  706. colnames, and the `cdr' of which contains a list of the column
  707. names. Note: this function removes any hlines in TABLE."
  708. (flet ((trans (table) (apply #'mapcar* #'list table)))
  709. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  710. (table (trans (mapcar (lambda (row)
  711. (if (not (equal row 'hline))
  712. row
  713. (setq row '())
  714. (dotimes (n width) (setq row (cons 'hline row)))
  715. row))
  716. table))))
  717. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  718. (trans (cdr table)))
  719. (remove 'hline (car table))))))
  720. (defun org-babel-put-colnames (table colnames)
  721. "Add COLNAMES to TABLE if they exist."
  722. (if colnames (apply 'list colnames 'hline table) table))
  723. (defun org-babel-put-rownames (table rownames)
  724. "Add ROWNAMES to TABLE if they exist."
  725. (if rownames
  726. (mapcar (lambda (row)
  727. (if (listp row)
  728. (cons (or (pop rownames) "") row)
  729. row)) table)
  730. table))
  731. (defun org-babel-pick-name (names selector)
  732. "Select one out of an alist of row or column names."
  733. (when names
  734. (if (and selector (symbolp selector) (not (equal t selector)))
  735. (cdr (assoc selector names))
  736. (if (integerp selector)
  737. (nth (- selector 1) names)
  738. (cdr (car (last names)))))))
  739. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  740. "Process the variables in VARS according to the HLINES,
  741. ROWNAMES and COLNAMES header arguments. Return a list consisting
  742. of the vars, cnames and rnames."
  743. (let (cnames rnames)
  744. (list
  745. (mapcar
  746. (lambda (var)
  747. (when (listp (cdr var))
  748. (when (and (not (equal colnames "no"))
  749. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  750. (not (member 'hline (cddr (cdr var)))))))
  751. (let ((both (org-babel-get-colnames (cdr var))))
  752. (setq cnames (cons (cons (car var) (cdr both))
  753. cnames))
  754. (setq var (cons (car var) (car both)))))
  755. (when (and rownames (not (equal rownames "no")))
  756. (let ((both (org-babel-get-rownames (cdr var))))
  757. (setq rnames (cons (cons (car var) (cdr both))
  758. rnames))
  759. (setq var (cons (car var) (car both)))))
  760. (when (and hlines (not (equal hlines "yes")))
  761. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  762. var)
  763. vars)
  764. cnames rnames)))
  765. (defun org-babel-reassemble-table (table colnames rownames)
  766. "Given a TABLE and set of COLNAMES and ROWNAMES add the names
  767. to the table for reinsertion to org-mode."
  768. (if (listp table)
  769. ((lambda (table)
  770. (if (and colnames (listp (car table)) (= (length (car table))
  771. (length colnames)))
  772. (org-babel-put-colnames table colnames) table))
  773. (if (and rownames (= (length table) (length rownames)))
  774. (org-babel-put-rownames table rownames) table))
  775. table))
  776. (defun org-babel-where-is-src-block-head ()
  777. "Return the point at the beginning of the current source
  778. block. Specifically at the beginning of the #+BEGIN_SRC line.
  779. If the point is not on a source block then return nil."
  780. (let ((initial (point)) top bottom)
  781. (or
  782. (save-excursion ;; on a source name line
  783. (beginning-of-line 1)
  784. (and (looking-at org-babel-source-name-regexp) (forward-line 1)
  785. (looking-at org-babel-src-block-regexp)
  786. (point)))
  787. (save-excursion ;; on a #+begin_src line
  788. (beginning-of-line 1)
  789. (and (looking-at org-babel-src-block-regexp)
  790. (point)))
  791. (save-excursion ;; inside a src block
  792. (and
  793. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  794. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  795. (< top initial) (< initial bottom)
  796. (progn (goto-char top) (beginning-of-line 1)
  797. (looking-at org-babel-src-block-regexp))
  798. (point))))))
  799. ;;;###autoload
  800. (defun org-babel-goto-named-source-block (&optional name)
  801. "Go to a named source-code block."
  802. (interactive "ssource-block name: ")
  803. (let ((point (org-babel-find-named-block name)))
  804. (if point
  805. ;; taken from `org-open-at-point'
  806. (progn (goto-char point) (org-show-context))
  807. (message "source-code block '%s' not found in this buffer" name))))
  808. (defun org-babel-find-named-block (name)
  809. "Find a named source-code block.
  810. Return the location of the source block identified by source
  811. NAME, or nil if no such block exists. Set match data according to
  812. org-babel-named-src-block-regexp."
  813. (save-excursion
  814. (let ((case-fold-search t)
  815. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  816. (goto-char (point-min))
  817. (when (or (re-search-forward regexp nil t)
  818. (re-search-backward regexp nil t))
  819. (match-beginning 0)))))
  820. (defun org-babel-find-named-result (name)
  821. "Return the location of the result named NAME in the current
  822. buffer or nil if no such result exists."
  823. (save-excursion
  824. (goto-char (point-min))
  825. (when (re-search-forward
  826. (concat org-babel-result-regexp
  827. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  828. (beginning-of-line 0) (point))))
  829. (defvar org-babel-lob-one-liner-regexp)
  830. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  831. "Return the point at the beginning of the result of the current
  832. source block. Specifically at the beginning of the results line.
  833. If no result exists for this block then create a results line
  834. following the source block."
  835. (save-excursion
  836. (let* ((on-lob-line (progn (beginning-of-line 1)
  837. (looking-at org-babel-lob-one-liner-regexp)))
  838. (name (if on-lob-line
  839. (nth 0 (org-babel-lob-get-info))
  840. (nth 4 (or info (org-babel-get-src-block-info)))))
  841. (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
  842. (when head (goto-char head))
  843. (or (and name (org-babel-find-named-result name))
  844. (and (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  845. (progn (end-of-line 1)
  846. (if (eobp) (insert "\n") (forward-char 1))
  847. (setq end (point))
  848. (or (and (not name)
  849. (progn ;; unnamed results line already exists
  850. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  851. (beginning-of-line 1)
  852. (looking-at
  853. (concat org-babel-result-regexp "\n"))))
  854. ;; or (with optional insert) back up and
  855. ;; make one ourselves
  856. (when insert
  857. (goto-char end)
  858. (if (looking-at "[\n\r]")
  859. (forward-char 1) (insert "\n"))
  860. (insert (concat
  861. (if indent
  862. (mapconcat
  863. (lambda (el) " ")
  864. (number-sequence 1 indent) "")
  865. "")
  866. "#+results"
  867. (when hash (concat "["hash"]"))
  868. ":"
  869. (when name (concat " " name)) "\n\n"))
  870. (backward-char)
  871. (beginning-of-line 0)
  872. (if hash (org-babel-hide-hash)) t)))
  873. (point))))))
  874. (defvar org-block-regexp)
  875. (defun org-babel-read-result ()
  876. "Read the result at `point' into emacs-lisp."
  877. (let ((case-fold-search t) result-string)
  878. (cond
  879. ((org-at-table-p) (org-babel-read-table))
  880. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  881. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  882. ((looking-at "^[ \t]*: ")
  883. (setq result-string
  884. (org-babel-trim
  885. (mapconcat (lambda (line)
  886. (if (and (> (length line) 1)
  887. (string-match "^[ \t]*: \\(.+\\)" line))
  888. (match-string 1 line)
  889. line))
  890. (split-string
  891. (buffer-substring
  892. (point) (org-babel-result-end)) "[\r\n]+")
  893. "\n")))
  894. (or (org-babel-number-p result-string) result-string))
  895. ((looking-at org-babel-result-regexp)
  896. (save-excursion (forward-line 1) (org-babel-read-result))))))
  897. (defun org-babel-read-table ()
  898. "Read the table at `point' into emacs-lisp."
  899. (mapcar (lambda (row)
  900. (if (and (symbolp row) (equal row 'hline)) row
  901. (mapcar #'org-babel-read row)))
  902. (org-table-to-lisp)))
  903. (defvar org-link-types-re)
  904. (defun org-babel-read-link ()
  905. "Read the link at `point' into emacs-lisp. If the path of the
  906. link is a file path it is expanded using `expand-file-name'."
  907. (let* ((case-fold-search t)
  908. (raw (and (looking-at org-bracket-link-regexp)
  909. (org-babel-clean-text-properties (match-string 1))))
  910. (type (and (string-match org-link-types-re raw)
  911. (match-string 1 raw))))
  912. (cond
  913. ((not type) (expand-file-name raw))
  914. ((string= type "file")
  915. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  916. (expand-file-name (match-string 2 raw))))
  917. (t raw))))
  918. (defun org-babel-insert-result
  919. (result &optional result-params info hash indent lang)
  920. "Insert RESULT into the current buffer after the end of the
  921. current source block. With optional argument RESULT-PARAMS
  922. controls insertion of results in the org-mode file.
  923. RESULT-PARAMS can take the following values...
  924. replace - (default option) insert results after the source block
  925. replacing any previously inserted results
  926. silent -- no results are inserted
  927. file ---- the results are interpreted as a file path, and are
  928. inserted into the buffer using the Org-mode file syntax
  929. raw ----- results are added directly to the org-mode file. This
  930. is a good option if you code block will output org-mode
  931. formatted text.
  932. org ----- this is the same as the 'raw' option
  933. html ---- results are added inside of a #+BEGIN_HTML block. This
  934. is a good option if you code block will output html
  935. formatted text.
  936. latex --- results are added inside of a #+BEGIN_LATEX block.
  937. This is a good option if you code block will output
  938. latex formatted text.
  939. code ---- the results are extracted in the syntax of the source
  940. code of the language being evaluated and are added
  941. inside of a #+BEGIN_SRC block with the source-code
  942. language set appropriately. Note this relies on the
  943. optional LANG argument."
  944. (if (stringp result)
  945. (progn
  946. (setq result (org-babel-clean-text-properties result))
  947. (when (member "file" result-params)
  948. (setq result (org-babel-result-to-file result))))
  949. (unless (listp result) (setq result (format "%S" result))))
  950. (if (= (length result) 0)
  951. (if (member "value" result-params)
  952. (message "No result returned by source block")
  953. (message "Source block produced no output"))
  954. (if (and result-params (member "silent" result-params))
  955. (progn
  956. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  957. result)
  958. (when (and (stringp result) ;; ensure results end in a newline
  959. (not (or (string-equal (substring result -1) "\n")
  960. (string-equal (substring result -1) "\r"))))
  961. (setq result (concat result "\n")))
  962. (save-excursion
  963. (let ((existing-result (org-babel-where-is-src-block-result
  964. t info hash indent))
  965. (results-switches
  966. (cdr (assoc :results_switches (nth 2 info))))
  967. beg end)
  968. (when existing-result
  969. (goto-char existing-result)
  970. (save-excursion
  971. (re-search-forward "#" nil t)
  972. (setq indent (- (current-column) 1)))
  973. (forward-line 1)
  974. (setq beg (point))
  975. (cond
  976. ((member "replace" result-params)
  977. (delete-region (point) (org-babel-result-end)))
  978. ((member "append" result-params)
  979. (goto-char (org-babel-result-end)) (setq beg (point)))
  980. ((member "prepend" result-params) ;; already there
  981. )))
  982. (setq results-switches
  983. (if results-switches (concat " " results-switches) ""))
  984. (cond
  985. ;; assume the result is a table if it's not a string
  986. ((not (stringp result))
  987. (insert (concat (orgtbl-to-orgtbl
  988. (if (or (eq 'hline (car result))
  989. (and (listp (car result))
  990. (listp (cdr (car result)))))
  991. result (list result))
  992. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  993. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  994. ((member "file" result-params)
  995. (insert result))
  996. ((member "html" result-params)
  997. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  998. results-switches result)))
  999. ((member "latex" result-params)
  1000. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1001. results-switches result)))
  1002. ((member "code" result-params)
  1003. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1004. (or lang "none") results-switches result)))
  1005. ((or (member "raw" result-params) (member "org" result-params))
  1006. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1007. (t
  1008. (org-babel-examplize-region
  1009. (point) (progn (insert result) (point)) results-switches)))
  1010. ;; possibly indent the results to match the #+results line
  1011. (setq end (if (listp result) (org-table-end) (point)))
  1012. (when (and indent (> indent 0)
  1013. ;; in this case `table-align' does the work for us
  1014. (not (and (listp result)
  1015. (member "append" result-params))))
  1016. (indent-rigidly beg end indent))))
  1017. (message "finished"))))
  1018. (defun org-babel-remove-result (&optional info)
  1019. "Remove the result of the current source block."
  1020. (interactive)
  1021. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1022. (when location
  1023. (save-excursion
  1024. (goto-char location) (setq start (point)) (forward-line 1)
  1025. (delete-region start (org-babel-result-end))))))
  1026. (defun org-babel-result-end ()
  1027. "Return the point at the end of the current set of results"
  1028. (save-excursion
  1029. (if (org-at-table-p)
  1030. (progn (goto-char (org-table-end)) (point))
  1031. (let ((case-fold-search t))
  1032. (cond
  1033. ((looking-at "[ \t]*#\\+begin_latex")
  1034. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1035. (forward-line 1))
  1036. ((looking-at "[ \t]*#\\+begin_html")
  1037. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1038. (forward-line 1))
  1039. ((looking-at "[ \t]*#\\+begin_example")
  1040. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1041. (forward-line 1))
  1042. ((looking-at "[ \t]*#\\+begin_src")
  1043. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1044. (forward-line 1))
  1045. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1046. (forward-line 1))))))
  1047. (point))))
  1048. (defun org-babel-result-to-file (result)
  1049. "Convert RESULT into an `org-mode' link. If the
  1050. `default-directory' is different from the containing file's
  1051. directory then expand relative links."
  1052. (format
  1053. "[[file:%s]]"
  1054. (if (and default-directory
  1055. buffer-file-name
  1056. (not (string= (expand-file-name default-directory)
  1057. (expand-file-name
  1058. (file-name-directory buffer-file-name)))))
  1059. (expand-file-name result default-directory)
  1060. result)))
  1061. (defun org-babel-examplize-region (beg end &optional results-switches)
  1062. "Comment out region using the ': ' org example quote."
  1063. (interactive "*r")
  1064. (let ((size (count-lines beg end)))
  1065. (save-excursion
  1066. (cond ((= size 0)
  1067. (error (concat "This should be impossible:"
  1068. "a newline was appended to result if missing")))
  1069. ((< size org-babel-min-lines-for-block-output)
  1070. (goto-char beg)
  1071. (dotimes (n size)
  1072. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1073. (t
  1074. (goto-char beg)
  1075. (insert (if results-switches
  1076. (format "#+begin_example%s\n" results-switches)
  1077. "#+begin_example\n"))
  1078. (forward-char (- end beg))
  1079. (insert "#+end_example\n"))))))
  1080. (defun org-babel-merge-params (&rest plists)
  1081. "Combine all parameter association lists in PLISTS. Later
  1082. elements of PLISTS override the values of previous element. This
  1083. takes into account some special considerations for certain
  1084. parameters when merging lists."
  1085. (let ((results-exclusive-groups
  1086. '(("file" "vector" "table" "scalar" "raw" "org"
  1087. "html" "latex" "code" "pp")
  1088. ("replace" "silent" "append" "prepend")
  1089. ("output" "value")))
  1090. (exports-exclusive-groups
  1091. '(("code" "results" "both" "none")))
  1092. params results exports tangle noweb cache vars var ref shebang comments)
  1093. (flet ((e-merge (exclusive-groups &rest result-params)
  1094. ;; maintain exclusivity of mutually exclusive parameters
  1095. (let (output)
  1096. (mapc (lambda (new-params)
  1097. (mapc (lambda (new-param)
  1098. (mapc (lambda (exclusive-group)
  1099. (when (member new-param exclusive-group)
  1100. (mapcar (lambda (excluded-param)
  1101. (setq output
  1102. (delete
  1103. excluded-param
  1104. output)))
  1105. exclusive-group)))
  1106. exclusive-groups)
  1107. (setq output (org-uniquify
  1108. (cons new-param output))))
  1109. new-params))
  1110. result-params)
  1111. output)))
  1112. (mapc (lambda (plist)
  1113. (mapc (lambda (pair)
  1114. (case (car pair)
  1115. (:var
  1116. ;; we want only one specification per variable
  1117. (when (string-match
  1118. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1119. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1120. ;; TODO: When is this not true?
  1121. (setq var (intern (match-string 1 (cdr pair)))
  1122. ref (match-string 2 (cdr pair))
  1123. vars (cons (cons var ref)
  1124. (assq-delete-all var vars)))))
  1125. (:results
  1126. (setq results
  1127. (e-merge results-exclusive-groups
  1128. results (split-string (cdr pair)))))
  1129. (:file
  1130. (when (cdr pair)
  1131. (setq results (e-merge results-exclusive-groups
  1132. results '("file")))
  1133. (unless (or (member "both" exports)
  1134. (member "none" exports)
  1135. (member "code" exports))
  1136. (setq exports (e-merge exports-exclusive-groups
  1137. exports '("results"))))
  1138. (setq params
  1139. (cons pair
  1140. (assq-delete-all (car pair) params)))))
  1141. (:exports
  1142. (setq exports
  1143. (e-merge exports-exclusive-groups
  1144. exports (split-string (cdr pair)))))
  1145. (:tangle ;; take the latest -- always overwrite
  1146. (setq tangle (or (list (cdr pair)) tangle)))
  1147. (:noweb
  1148. (setq noweb
  1149. (e-merge '(("yes" "no")) noweb
  1150. (split-string (or (cdr pair) "")))))
  1151. (:cache
  1152. (setq cache
  1153. (e-merge '(("yes" "no")) cache
  1154. (split-string (or (cdr pair) "")))))
  1155. (:shebang ;; take the latest -- always overwrite
  1156. (setq shebang (or (list (cdr pair)) shebang)))
  1157. (:comments
  1158. (setq comments
  1159. (e-merge '(("yes" "no")) comments
  1160. (split-string (or (cdr pair) "")))))
  1161. (t ;; replace: this covers e.g. :session
  1162. (setq params
  1163. (cons pair
  1164. (assq-delete-all (car pair) params))))))
  1165. plist))
  1166. plists))
  1167. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1168. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1169. (cons (cons :comments (mapconcat 'identity comments " "))
  1170. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1171. (cons (cons :cache (mapconcat 'identity cache " "))
  1172. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1173. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1174. (cons (cons :exports
  1175. (mapconcat 'identity exports " "))
  1176. (cons
  1177. (cons :results
  1178. (mapconcat 'identity results " "))
  1179. params)))))))))
  1180. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1181. "This function expands Noweb style references in the body of
  1182. the current source-code block. For example the following
  1183. reference would be replaced with the body of the source-code
  1184. block named 'example-block'.
  1185. <<example-block>>
  1186. Note that any text preceding the <<foo>> construct on a line will
  1187. be interposed between the lines of the replacement text. So for
  1188. example if <<foo>> is placed behind a comment, then the entire
  1189. replacement text will also be commented.
  1190. This function must be called from inside of the buffer containing
  1191. the source-code block which holds BODY.
  1192. In addition the following syntax can be used to insert the
  1193. results of evaluating the source-code block named 'example-block'.
  1194. <<example-block()>>
  1195. Any optional arguments can be passed to example-block by placing
  1196. the arguments inside the parenthesis following the convention
  1197. defined by `org-babel-lob'. For example
  1198. <<example-block(a=9)>>
  1199. would set the value of argument \"a\" equal to \"9\". Note that
  1200. these arguments are not evaluated in the current source-code
  1201. block but are passed literally to the \"example-block\"."
  1202. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1203. (info (or info (org-babel-get-src-block-info)))
  1204. (lang (nth 0 info))
  1205. (body (nth 1 info))
  1206. (new-body "") index source-name evaluate prefix)
  1207. (flet ((nb-add (text)
  1208. (setq new-body (concat new-body text))))
  1209. (with-temp-buffer
  1210. (insert body) (goto-char (point-min))
  1211. (setq index (point))
  1212. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1213. (save-match-data (setf source-name (match-string 1)))
  1214. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1215. (save-match-data
  1216. (setq prefix
  1217. (buffer-substring (match-beginning 0)
  1218. (save-excursion
  1219. (beginning-of-line 1) (point)))))
  1220. ;; add interval to new-body (removing noweb reference)
  1221. (goto-char (match-beginning 0))
  1222. (nb-add (buffer-substring index (point)))
  1223. (goto-char (match-end 0))
  1224. (setq index (point))
  1225. (nb-add (with-current-buffer parent-buffer
  1226. (mapconcat ;; interpose PREFIX between every line
  1227. #'identity
  1228. (split-string
  1229. (if evaluate
  1230. (let ((raw (org-babel-ref-resolve-reference
  1231. source-name nil)))
  1232. (if (stringp raw) raw (format "%S" raw)))
  1233. (save-restriction
  1234. (widen)
  1235. (let ((point (org-babel-find-named-block
  1236. source-name)))
  1237. (if point
  1238. (save-excursion
  1239. (goto-char point)
  1240. (org-babel-trim
  1241. (org-babel-expand-noweb-references
  1242. (org-babel-get-src-block-info))))
  1243. ;; optionally raise an error if named
  1244. ;; source-block doesn't exist
  1245. (if (member lang org-babel-noweb-error-langs)
  1246. (error "%s"
  1247. (concat
  1248. "<<" source-name ">> "
  1249. "could not be resolved (see "
  1250. "`org-babel-noweb-error-langs')"))
  1251. "")))))
  1252. "[\n\r]") (concat "\n" prefix)))))
  1253. (nb-add (buffer-substring index (point-max)))))
  1254. new-body))
  1255. (defun org-babel-clean-text-properties (text)
  1256. "Strip all properties from text return."
  1257. (when text
  1258. (set-text-properties 0 (length text) nil text) text))
  1259. (defun org-babel-strip-protective-commas (body)
  1260. "Strip protective commas from bodies of source blocks."
  1261. (replace-regexp-in-string "^,#" "#" body))
  1262. (defun org-babel-read (cell)
  1263. "Convert the string value of CELL to a number if appropriate.
  1264. Otherwise if cell looks like lisp (meaning it starts with a
  1265. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1266. unmodified as a string.
  1267. This is taken almost directly from `org-read-prop'."
  1268. (if (and (stringp cell) (not (equal cell "")))
  1269. (or (org-babel-number-p cell)
  1270. (if (or (equal "(" (substring cell 0 1))
  1271. (equal "'" (substring cell 0 1))
  1272. (equal "`" (substring cell 0 1)))
  1273. (eval (read cell))
  1274. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1275. cell))
  1276. (defun org-babel-number-p (string)
  1277. "Return t if STRING represents a number."
  1278. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1279. (= (length (substring string (match-beginning 0)
  1280. (match-end 0)))
  1281. (length string)))
  1282. (string-to-number string)))
  1283. (defun org-babel-import-elisp-from-file (file-name)
  1284. "Read the results located at FILE-NAME into an elisp table. If
  1285. the table is trivial, then return it as a scalar."
  1286. (let (result)
  1287. (save-window-excursion
  1288. (with-temp-buffer
  1289. (condition-case nil
  1290. (progn
  1291. (org-table-import file-name nil)
  1292. (delete-file file-name)
  1293. (setq result (mapcar (lambda (row)
  1294. (mapcar #'org-babel-string-read row))
  1295. (org-table-to-lisp))))
  1296. (error nil)))
  1297. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1298. (if (consp (car result))
  1299. (if (null (cdr (car result)))
  1300. (caar result)
  1301. result)
  1302. (car result))
  1303. result))))
  1304. (defun org-babel-string-read (cell)
  1305. "Strip nested \"s from around strings."
  1306. (org-babel-read (or (and (stringp cell)
  1307. (string-match "\\\"\\(.+\\)\\\"" cell)
  1308. (match-string 1 cell))
  1309. cell)))
  1310. (defun org-babel-reverse-string (string)
  1311. "Return the reverse of STRING."
  1312. (apply 'string (reverse (string-to-list string))))
  1313. (defun org-babel-chomp (string &optional regexp)
  1314. "Remove any trailing space or carriage returns characters from
  1315. STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1316. overwritten by specifying a regexp as a second argument."
  1317. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1318. (while (and (> (length string) 0)
  1319. (string-match regexp (substring string -1)))
  1320. (setq string (substring string 0 -1)))
  1321. string))
  1322. (defun org-babel-trim (string &optional regexp)
  1323. "Like `org-babel-chomp' only it runs on both the front and back
  1324. of the string."
  1325. (org-babel-chomp (org-babel-reverse-string
  1326. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1327. regexp))
  1328. (defvar org-babel-org-babel-call-process-region-original nil)
  1329. (defun org-babel-tramp-handle-call-process-region
  1330. (start end program &optional delete buffer display &rest args)
  1331. "Use tramp to handle call-process-region. Fixes a bug in
  1332. `tramp-handle-call-process-region'."
  1333. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1334. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1335. (write-region start end tmpfile)
  1336. (when delete (delete-region start end))
  1337. (unwind-protect
  1338. ;; (apply 'call-process program tmpfile buffer display args)
  1339. ;; bug in tramp
  1340. (apply 'process-file program tmpfile buffer display args)
  1341. (delete-file tmpfile)))
  1342. ;; org-babel-call-process-region-original is the original emacs definition. It
  1343. ;; is in scope from the let binding in org-babel-execute-src-block
  1344. (apply org-babel-call-process-region-original
  1345. start end program delete buffer display args)))
  1346. (defun org-babel-maybe-remote-file (file)
  1347. "If FILE specifies a remove file, then parse the information on
  1348. the remote connection."
  1349. (if (file-remote-p default-directory)
  1350. (let* ((vec (tramp-dissect-file-name default-directory))
  1351. (user (tramp-file-name-user vec))
  1352. (host (tramp-file-name-host vec)))
  1353. (concat "/" user (when user "@") host ":" file))
  1354. file))
  1355. (provide 'ob)
  1356. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1357. ;;; ob.el ends here