ob.el 73 KB

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