ob.el 67 KB

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