ob.el 72 KB

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