ob.el 69 KB

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