ob.el 63 KB

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