ob.el 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  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. (org-save-outline-visibility t
  517. (org-babel-map-src-blocks nil
  518. (org-babel-execute-src-block arg))))
  519. ;;;###autoload
  520. (defun org-babel-execute-subtree (&optional arg)
  521. "Execute source code blocks in a subtree.
  522. Call `org-babel-execute-src-block' on every source block in
  523. the current subtree."
  524. (interactive "P")
  525. (save-restriction
  526. (save-excursion
  527. (org-narrow-to-subtree)
  528. (org-babel-execute-buffer arg)
  529. (widen))))
  530. ;;;###autoload
  531. (defun org-babel-sha1-hash (&optional info)
  532. "Generate an sha1 hash based on the value of info."
  533. (interactive)
  534. (let* ((info (or info (org-babel-get-src-block-info)))
  535. (hash (sha1
  536. (format "%s-%s"
  537. (mapconcat
  538. (lambda (arg)
  539. (if (stringp (cdr arg))
  540. (mapconcat
  541. #'identity
  542. (sort (split-string (cdr arg)) #'string<) " ")
  543. (cdr arg)))
  544. (nth 2 info) ":")
  545. (nth 1 info)))))
  546. (when (interactive-p) (message hash))
  547. hash))
  548. (defun org-babel-result-hash (&optional info)
  549. "Return the in-buffer hash associated with INFO."
  550. (org-babel-where-is-src-block-result nil info)
  551. (org-babel-clean-text-properties (match-string 3)))
  552. (defun org-babel-hide-hash ()
  553. "Hide the hash in the current results line.
  554. Only the initial `org-babel-hash-show' characters of the hash
  555. will remain visible."
  556. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  557. (save-excursion
  558. (when (and (re-search-forward org-babel-result-regexp nil t)
  559. (match-string 3))
  560. (let* ((start (match-beginning 3))
  561. (hide-start (+ org-babel-hash-show start))
  562. (end (match-end 3))
  563. (hash (match-string 3))
  564. ov1 ov2)
  565. (setq ov1 (make-overlay start hide-start))
  566. (setq ov2 (make-overlay hide-start end))
  567. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  568. (overlay-put ov1 'babel-hash hash)))))
  569. (defun org-babel-hide-all-hashes ()
  570. "Hide the hash in the current buffer.
  571. Only the initial `org-babel-hash-show' characters of each hash
  572. will remain visible. This function should be called as part of
  573. the `org-mode-hook'."
  574. (save-excursion
  575. (while (re-search-forward org-babel-result-regexp nil t)
  576. (goto-char (match-beginning 0))
  577. (org-babel-hide-hash)
  578. (goto-char (match-end 0)))))
  579. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  580. (defun org-babel-hash-at-point (&optional point)
  581. "Return the value of the hash at POINT.
  582. The hash is also added as the last element of the kill ring.
  583. This can be called with C-c C-c."
  584. (interactive)
  585. (let ((hash (car (delq nil (mapcar
  586. (lambda (ol) (overlay-get ol 'babel-hash))
  587. (overlays-at (or point (point))))))))
  588. (when hash (kill-new hash) (message hash))))
  589. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  590. (defun org-babel-result-hide-spec ()
  591. "Hide portions of results lines.
  592. Add `org-babel-hide-result' as an invisibility spec for hiding
  593. portions of results lines."
  594. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  595. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  596. (defvar org-babel-hide-result-overlays nil
  597. "Overlays hiding results.")
  598. (defun org-babel-result-hide-all ()
  599. "Fold all results in the current buffer."
  600. (interactive)
  601. (org-babel-show-result-all)
  602. (save-excursion
  603. (while (re-search-forward org-babel-result-regexp nil t)
  604. (save-excursion (goto-char (match-beginning 0))
  605. (org-babel-hide-result-toggle-maybe)))))
  606. (defun org-babel-show-result-all ()
  607. "Unfold all results in the current buffer."
  608. (mapc 'delete-overlay org-babel-hide-result-overlays)
  609. (setq org-babel-hide-result-overlays nil))
  610. ;;;###autoload
  611. (defun org-babel-hide-result-toggle-maybe ()
  612. "Toggle visibility of result at point."
  613. (interactive)
  614. (let ((case-fold-search t))
  615. (if (save-excursion
  616. (beginning-of-line 1)
  617. (looking-at org-babel-result-regexp))
  618. (progn (org-babel-hide-result-toggle)
  619. t) ;; to signal that we took action
  620. nil))) ;; to signal that we did not
  621. (defun org-babel-hide-result-toggle (&optional force)
  622. "Toggle the visibility of the current result."
  623. (interactive)
  624. (save-excursion
  625. (beginning-of-line)
  626. (if (re-search-forward org-babel-result-regexp nil t)
  627. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  628. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  629. ov)
  630. (if (memq t (mapcar (lambda (overlay)
  631. (eq (overlay-get overlay 'invisible)
  632. 'org-babel-hide-result))
  633. (overlays-at start)))
  634. (if (or (not force) (eq force 'off))
  635. (mapc (lambda (ov)
  636. (when (member ov org-babel-hide-result-overlays)
  637. (setq org-babel-hide-result-overlays
  638. (delq ov org-babel-hide-result-overlays)))
  639. (when (eq (overlay-get ov 'invisible)
  640. 'org-babel-hide-result)
  641. (delete-overlay ov)))
  642. (overlays-at start)))
  643. (setq ov (make-overlay start end))
  644. (overlay-put ov 'invisible 'org-babel-hide-result)
  645. ;; make the block accessible to isearch
  646. (overlay-put
  647. ov 'isearch-open-invisible
  648. (lambda (ov)
  649. (when (member ov org-babel-hide-result-overlays)
  650. (setq org-babel-hide-result-overlays
  651. (delq ov org-babel-hide-result-overlays)))
  652. (when (eq (overlay-get ov 'invisible)
  653. 'org-babel-hide-result)
  654. (delete-overlay ov))))
  655. (push ov org-babel-hide-result-overlays)))
  656. (error "Not looking at a result line"))))
  657. ;; org-tab-after-check-for-cycling-hook
  658. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  659. ;; Remove overlays when changing major mode
  660. (add-hook 'org-mode-hook
  661. (lambda () (org-add-hook 'change-major-mode-hook
  662. 'org-babel-show-result-all 'append 'local)))
  663. (defmacro org-babel-map-src-blocks (file &rest body)
  664. "Evaluate BODY forms on each source-block in FILE.
  665. If FILE is nil evaluate BODY forms on source blocks in current
  666. buffer. During evaluation of BODY the following local variables
  667. are set relative to the currently matched code block.
  668. full-block ------- string holding the entirety of the code block
  669. beg-block -------- point at the beginning of the code block
  670. end-block -------- point at the end of the matched code block
  671. lang ------------- string holding the language of the code block
  672. beg-lang --------- point at the beginning of the lang
  673. end-lang --------- point at the end of the lang
  674. switches --------- string holding the switches
  675. beg-switches ----- point at the beginning of the switches
  676. end-switches ----- point at the end of the switches
  677. header-args ------ string holding the header-args
  678. beg-header-args -- point at the beginning of the header-args
  679. end-header-args -- point at the end of the header-args
  680. body ------------- string holding the body of the code block
  681. beg-body --------- point at the beginning of the body
  682. end-body --------- point at the end of the body"
  683. (declare (indent 1))
  684. `(let ((visited-p (or (null ,file)
  685. (get-file-buffer (expand-file-name ,file))))
  686. (point (point)) to-be-removed)
  687. (save-window-excursion
  688. (when ,file (find-file ,file))
  689. (setq to-be-removed (current-buffer))
  690. (goto-char (point-min))
  691. (while (re-search-forward org-babel-src-block-regexp nil t)
  692. (goto-char (match-beginning 0))
  693. (let ((full-block (match-string 0))
  694. (beg-block (match-beginning 0))
  695. (end-block (match-beginning 0))
  696. (lang (match-string 2))
  697. (beg-lang (match-beginning 2))
  698. (end-lang (match-end 2))
  699. (switches (match-string 3))
  700. (beg-switches (match-beginning 3))
  701. (end-switches (match-end 3))
  702. (header-args (match-string 4))
  703. (beg-header-args (match-beginning 4))
  704. (end-header-args (match-end 4))
  705. (body (match-string 5))
  706. (beg-body (match-beginning 5))
  707. (end-body (match-end 5)))
  708. (save-match-data ,@body))
  709. (goto-char (match-end 0))))
  710. (unless visited-p
  711. (kill-buffer to-be-removed))
  712. (goto-char point)))
  713. (defvar org-file-properties)
  714. (defun org-babel-params-from-properties (&optional lang)
  715. "Retrieve parameters specified as properties.
  716. Return an association list of any source block params which
  717. may be specified in the properties of the current outline entry."
  718. (save-match-data
  719. (let (val sym)
  720. (delq nil
  721. (mapcar
  722. (lambda (header-arg)
  723. (and (setq val
  724. (or (condition-case nil
  725. (org-entry-get (point) header-arg t)
  726. (error nil))
  727. (cdr (assoc header-arg org-file-properties))))
  728. (cons (intern (concat ":" header-arg)) val)))
  729. (mapcar
  730. 'symbol-name
  731. (append
  732. org-babel-header-arg-names
  733. (progn
  734. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  735. (and (boundp sym) (eval sym))))))))))
  736. (defun org-babel-params-from-buffer ()
  737. "Retrieve per-buffer parameters.
  738. Return an association list of any source block params which
  739. may be specified at the top of the current buffer."
  740. (or org-babel-current-buffer-properties
  741. (setq org-babel-current-buffer-properties
  742. (save-match-data
  743. (save-excursion
  744. (save-restriction
  745. (widen)
  746. (goto-char (point-min))
  747. (when (re-search-forward
  748. (org-make-options-regexp (list "BABEL")) nil t)
  749. (org-babel-parse-header-arguments
  750. (org-match-string-no-properties 2)))))))))
  751. (defvar org-src-preserve-indentation)
  752. (defun org-babel-parse-src-block-match ()
  753. "Parse the results from a match of the `org-babel-src-block-regexp'."
  754. (let* ((block-indentation (length (match-string 1)))
  755. (lang (org-babel-clean-text-properties (match-string 2)))
  756. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  757. (switches (match-string 3))
  758. (body (org-babel-clean-text-properties (match-string 5)))
  759. (preserve-indentation (or org-src-preserve-indentation
  760. (string-match "-i\\>" switches))))
  761. (list lang
  762. ;; get block body less properties, protective commas, and indentation
  763. (with-temp-buffer
  764. (save-match-data
  765. (insert (org-babel-strip-protective-commas body))
  766. (unless preserve-indentation (org-do-remove-indentation))
  767. (buffer-string)))
  768. (org-babel-merge-params
  769. org-babel-default-header-args
  770. (org-babel-params-from-buffer)
  771. (org-babel-params-from-properties lang)
  772. (if (boundp lang-headers) (eval lang-headers) nil)
  773. (org-babel-parse-header-arguments
  774. (org-babel-clean-text-properties (or (match-string 4) ""))))
  775. switches
  776. block-indentation)))
  777. (defun org-babel-parse-inline-src-block-match ()
  778. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  779. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  780. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  781. (list lang
  782. (org-babel-strip-protective-commas
  783. (org-babel-clean-text-properties (match-string 5)))
  784. (org-babel-merge-params
  785. org-babel-default-inline-header-args
  786. (org-babel-params-from-buffer)
  787. (org-babel-params-from-properties lang)
  788. (if (boundp lang-headers) (eval lang-headers) nil)
  789. (org-babel-parse-header-arguments
  790. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  791. (defun org-babel-parse-header-arguments (arg-string)
  792. "Parse a string of header arguments returning an alist."
  793. (if (> (length arg-string) 0)
  794. (delq nil
  795. (mapcar
  796. (lambda (arg)
  797. (if (string-match
  798. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  799. arg)
  800. (cons (intern (concat ":" (match-string 1 arg)))
  801. (let ((raw (org-babel-chomp (match-string 2 arg))))
  802. (if (org-babel-number-p raw)
  803. raw (org-babel-read raw))))
  804. (cons (intern (concat ":" arg)) nil)))
  805. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  806. (defun org-babel-process-params (params)
  807. "Parse params and resolve references.
  808. Return a list (session vars result-params result-type colnames rownames)."
  809. (let* ((session (cdr (assoc :session params)))
  810. (vars-and-names (org-babel-disassemble-tables
  811. (org-babel-ref-variables params)
  812. (cdr (assoc :hlines params))
  813. (cdr (assoc :colnames params))
  814. (cdr (assoc :rownames params))))
  815. (vars (car vars-and-names))
  816. (colnames (cadr vars-and-names))
  817. (rownames (caddr vars-and-names))
  818. (result-params (split-string (or (cdr (assoc :results params)) "")))
  819. (result-type (cond ((member "output" result-params) 'output)
  820. ((member "value" result-params) 'value)
  821. (t 'value))))
  822. (list session vars result-params result-type colnames rownames)))
  823. ;; row and column names
  824. (defun org-babel-del-hlines (table)
  825. "Remove all 'hlines from TABLE."
  826. (remove 'hline table))
  827. (defun org-babel-get-colnames (table)
  828. "Return the column names of TABLE.
  829. Return a cons cell, the `car' of which contains the TABLE less
  830. colnames, and the `cdr' of which contains a list of the column
  831. names."
  832. (if (equal 'hline (nth 1 table))
  833. (cons (cddr table) (car table))
  834. (cons (cdr table) (car table))))
  835. (defun org-babel-get-rownames (table)
  836. "Return the row names of TABLE.
  837. Return a cons cell, the `car' of which contains the TABLE less
  838. colnames, and the `cdr' of which contains a list of the column
  839. names. Note: this function removes any hlines in TABLE."
  840. (flet ((trans (table) (apply #'mapcar* #'list table)))
  841. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  842. (table (trans (mapcar (lambda (row)
  843. (if (not (equal row 'hline))
  844. row
  845. (setq row '())
  846. (dotimes (n width) (setq row (cons 'hline row)))
  847. row))
  848. table))))
  849. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  850. (trans (cdr table)))
  851. (remove 'hline (car table))))))
  852. (defun org-babel-put-colnames (table colnames)
  853. "Add COLNAMES to TABLE if they exist."
  854. (if colnames (apply 'list colnames 'hline table) table))
  855. (defun org-babel-put-rownames (table rownames)
  856. "Add ROWNAMES to TABLE if they exist."
  857. (if rownames
  858. (mapcar (lambda (row)
  859. (if (listp row)
  860. (cons (or (pop rownames) "") row)
  861. row)) table)
  862. table))
  863. (defun org-babel-pick-name (names selector)
  864. "Select one out of an alist of row or column names.
  865. SELECTOR can be either a list of names in which case those names
  866. will be returned directly, or an index into the list NAMES in
  867. which case the indexed names will be return."
  868. (if (listp selector)
  869. selector
  870. (when names
  871. (if (and selector (symbolp selector) (not (equal t selector)))
  872. (cdr (assoc selector names))
  873. (if (integerp selector)
  874. (nth (- selector 1) names)
  875. (cdr (car (last names))))))))
  876. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  877. "Parse tables for further processing.
  878. Process the variables in VARS according to the HLINES,
  879. ROWNAMES and COLNAMES header arguments. Return a list consisting
  880. of the vars, cnames and rnames."
  881. (let (cnames rnames)
  882. (list
  883. (mapcar
  884. (lambda (var)
  885. (when (listp (cdr var))
  886. (when (and (not (equal colnames "no"))
  887. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  888. (not (member 'hline (cddr (cdr var)))))))
  889. (let ((both (org-babel-get-colnames (cdr var))))
  890. (setq cnames (cons (cons (car var) (cdr both))
  891. cnames))
  892. (setq var (cons (car var) (car both)))))
  893. (when (and rownames (not (equal rownames "no")))
  894. (let ((both (org-babel-get-rownames (cdr var))))
  895. (setq rnames (cons (cons (car var) (cdr both))
  896. rnames))
  897. (setq var (cons (car var) (car both)))))
  898. (when (and hlines (not (equal hlines "yes")))
  899. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  900. var)
  901. vars)
  902. cnames rnames)))
  903. (defun org-babel-reassemble-table (table colnames rownames)
  904. "Add column and row names to a table.
  905. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  906. to the table for reinsertion to org-mode."
  907. (if (listp table)
  908. ((lambda (table)
  909. (if (and colnames (listp (car table)) (= (length (car table))
  910. (length colnames)))
  911. (org-babel-put-colnames table colnames) table))
  912. (if (and rownames (= (length table) (length rownames)))
  913. (org-babel-put-rownames table rownames) table))
  914. table))
  915. (defun org-babel-where-is-src-block-head ()
  916. "Find where the current source block begins.
  917. Return the point at the beginning of the current source
  918. block. Specifically at the beginning of the #+BEGIN_SRC line.
  919. If the point is not on a source block then return nil."
  920. (let ((initial (point)) top bottom)
  921. (or
  922. (save-excursion ;; on a source name line
  923. (beginning-of-line 1)
  924. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  925. (looking-at org-babel-src-block-regexp)
  926. (point)))
  927. (save-excursion ;; on a #+begin_src line
  928. (beginning-of-line 1)
  929. (and (looking-at org-babel-src-block-regexp)
  930. (point)))
  931. (save-excursion ;; inside a src block
  932. (and
  933. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  934. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  935. (< top initial) (< initial bottom)
  936. (progn (goto-char top) (beginning-of-line 1)
  937. (looking-at org-babel-src-block-regexp))
  938. (point))))))
  939. ;;;###autoload
  940. (defun org-babel-goto-src-block-head ()
  941. "Go to the beginning of the current code block."
  942. (interactive)
  943. ((lambda (head)
  944. (if head (goto-char head) (error "not currently in a code block")))
  945. (org-babel-where-is-src-block-head)))
  946. ;;;###autoload
  947. (defun org-babel-goto-named-src-block (name)
  948. "Go to a named source-code block."
  949. (interactive
  950. (let ((completion-ignore-case t))
  951. (list (org-icompleting-read "source-block name: "
  952. (org-babel-src-block-names) nil t))))
  953. (let ((point (org-babel-find-named-block name)))
  954. (if point
  955. ;; taken from `org-open-at-point'
  956. (progn (goto-char point) (org-show-context))
  957. (message "source-code block '%s' not found in this buffer" name))))
  958. (defun org-babel-find-named-block (name)
  959. "Find a named source-code block.
  960. Return the location of the source block identified by source
  961. NAME, or nil if no such block exists. Set match data according to
  962. org-babel-named-src-block-regexp."
  963. (save-excursion
  964. (let ((case-fold-search t)
  965. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  966. (goto-char (point-min))
  967. (when (or (re-search-forward regexp nil t)
  968. (re-search-backward regexp nil t))
  969. (match-beginning 0)))))
  970. (defun org-babel-src-block-names (&optional file)
  971. "Returns the names of source blocks in FILE or the current buffer."
  972. (save-excursion
  973. (when file (find-file file)) (goto-char (point-min))
  974. (let (names)
  975. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  976. (setq names (cons (org-babel-clean-text-properties (match-string 2))
  977. names)))
  978. names)))
  979. ;;;###autoload
  980. (defun org-babel-goto-named-result (name)
  981. "Go to a named result."
  982. (interactive
  983. (let ((completion-ignore-case t))
  984. (list (org-icompleting-read "source-block name: "
  985. (org-babel-result-names) nil t))))
  986. (let ((point (org-babel-find-named-result name)))
  987. (if point
  988. ;; taken from `org-open-at-point'
  989. (progn (goto-char point) (org-show-context))
  990. (message "result '%s' not found in this buffer" name))))
  991. (defun org-babel-find-named-result (name)
  992. "Find a named result.
  993. Return the location of the result named NAME in the current
  994. buffer or nil if no such result exists."
  995. (save-excursion
  996. (goto-char (point-min))
  997. (when (re-search-forward
  998. (concat org-babel-result-regexp
  999. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  1000. (beginning-of-line 0) (point))))
  1001. (defun org-babel-result-names (&optional file)
  1002. "Returns the names of results in FILE or the current buffer."
  1003. (save-excursion
  1004. (when file (find-file file)) (goto-char (point-min))
  1005. (let (names)
  1006. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1007. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  1008. names)))
  1009. names)))
  1010. ;;;###autoload
  1011. (defun org-babel-next-src-block (&optional arg)
  1012. "Jump to the next source block.
  1013. With optional prefix argument ARG, jump forward ARG many source blocks."
  1014. (interactive "P")
  1015. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1016. (condition-case nil
  1017. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1018. (error (error "No further code blocks")))
  1019. (goto-char (match-beginning 0)) (org-show-context))
  1020. ;;;###autoload
  1021. (defun org-babel-previous-src-block (&optional arg)
  1022. "Jump to the previous source block.
  1023. With optional prefix argument ARG, jump backward ARG many source blocks."
  1024. (interactive "P")
  1025. (condition-case nil
  1026. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1027. (error (error "No previous code blocks")))
  1028. (goto-char (match-beginning 0)) (org-show-context))
  1029. ;;;###autoload
  1030. (defun org-babel-demarcate-block (&optional arg)
  1031. "Wrap or split the code in the region or on the point.
  1032. When called from inside of a code block the current block is
  1033. split. When called from outside of a code block a new code block
  1034. is created. In both cases if the region is demarcated and if the
  1035. region is not active then the point is demarcated."
  1036. (interactive "P")
  1037. (let ((info (org-babel-get-src-block-info))
  1038. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1039. (if info
  1040. (mapc
  1041. (lambda (place)
  1042. (save-excursion
  1043. (goto-char place)
  1044. (let ((lang (nth 0 info))
  1045. (indent (make-string (nth 6 info) ? )))
  1046. (when (string-match "^[[:space:]]*$"
  1047. (buffer-substring (point-at-bol)
  1048. (point-at-eol)))
  1049. (delete-region (point-at-bol) (point-at-eol)))
  1050. (insert (concat (if (looking-at "^") "" "\n")
  1051. indent "#+end_src\n"
  1052. (if arg stars indent) "\n"
  1053. indent "#+begin_src " lang
  1054. (if (looking-at "[\n\r]") "" "\n")))))
  1055. (move-end-of-line 2))
  1056. (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
  1057. (let ((start (point))
  1058. (body (delete-and-extract-region
  1059. (if (region-active-p) (mark) (point)) (point))))
  1060. (insert (concat (if (looking-at "^") "" "\n")
  1061. (if arg (concat stars "\n") "")
  1062. "#+begin_src " (read-from-minibuffer "Lang: ") "\n"
  1063. body
  1064. (if (or (= (length body) 0)
  1065. (string-match "[\r\n]$" body)) "" "\n")
  1066. "#+end_src\n"))
  1067. (goto-char start) (move-end-of-line 1)))))
  1068. (defvar org-babel-lob-one-liner-regexp)
  1069. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1070. "Find where the current source block results begin.
  1071. Return the point at the beginning of the result of the current
  1072. source block. Specifically at the beginning of the results line.
  1073. If no result exists for this block then create a results line
  1074. following the source block."
  1075. (save-excursion
  1076. (let* ((on-lob-line (progn (beginning-of-line 1)
  1077. (looking-at org-babel-lob-one-liner-regexp)))
  1078. (name (if on-lob-line
  1079. (nth 0 (org-babel-lob-get-info))
  1080. (nth 4 (or info (org-babel-get-src-block-info)))))
  1081. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1082. found beg end)
  1083. (when head (goto-char head))
  1084. (setq
  1085. found ;; was there a result (before we potentially insert one)
  1086. (or
  1087. (and
  1088. ;; named results:
  1089. ;; - return t if it is found, else return nil
  1090. ;; - if it does not need to be rebuilt, then don't set end
  1091. ;; - if it does need to be rebuilt then do set end
  1092. name (setq beg (org-babel-find-named-result name))
  1093. (prog1 beg
  1094. (when (and hash (not (string= hash (match-string 3))))
  1095. (goto-char beg) (setq end beg) ;; beginning of result
  1096. (forward-line 1)
  1097. (delete-region end (org-babel-result-end)) nil)))
  1098. (and
  1099. ;; unnamed results:
  1100. ;; - return t if it is found, else return nil
  1101. ;; - if it is found, and the hash doesn't match, delete and set end
  1102. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1103. (progn (end-of-line 1)
  1104. (if (eobp) (insert "\n") (forward-char 1))
  1105. (setq end (point))
  1106. (or (and (not name)
  1107. (progn ;; unnamed results line already exists
  1108. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1109. (beginning-of-line 1)
  1110. (looking-at
  1111. (concat org-babel-result-regexp "\n")))
  1112. (prog1 (point)
  1113. ;; must remove and rebuild if hash!=old-hash
  1114. (if (and hash (not (string= hash (match-string 3))))
  1115. (prog1 nil
  1116. (forward-line 1)
  1117. (delete-region
  1118. end (org-babel-result-end)))
  1119. (setq end nil)))))))))
  1120. (if (and insert end)
  1121. (progn
  1122. (goto-char end)
  1123. (unless beg
  1124. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1125. (insert (concat
  1126. (if indent
  1127. (mapconcat
  1128. (lambda (el) " ")
  1129. (number-sequence 1 indent) "")
  1130. "")
  1131. "#+results"
  1132. (when hash (concat "["hash"]"))
  1133. ":"
  1134. (when name (concat " " name)) "\n"))
  1135. (unless beg (insert "\n") (backward-char))
  1136. (beginning-of-line 0)
  1137. (if hash (org-babel-hide-hash))
  1138. (point))
  1139. found))))
  1140. (defvar org-block-regexp)
  1141. (defun org-babel-read-result ()
  1142. "Read the result at `point' into emacs-lisp."
  1143. (let ((case-fold-search t) result-string)
  1144. (cond
  1145. ((org-at-table-p) (org-babel-read-table))
  1146. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1147. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1148. ((looking-at "^[ \t]*: ")
  1149. (setq result-string
  1150. (org-babel-trim
  1151. (mapconcat (lambda (line)
  1152. (if (and (> (length line) 1)
  1153. (string-match "^[ \t]*: \\(.+\\)" line))
  1154. (match-string 1 line)
  1155. line))
  1156. (split-string
  1157. (buffer-substring
  1158. (point) (org-babel-result-end)) "[\r\n]+")
  1159. "\n")))
  1160. (or (org-babel-number-p result-string) result-string))
  1161. ((looking-at org-babel-result-regexp)
  1162. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1163. (defun org-babel-read-table ()
  1164. "Read the table at `point' into emacs-lisp."
  1165. (mapcar (lambda (row)
  1166. (if (and (symbolp row) (equal row 'hline)) row
  1167. (mapcar #'org-babel-read row)))
  1168. (org-table-to-lisp)))
  1169. (defvar org-link-types-re)
  1170. (defun org-babel-read-link ()
  1171. "Read the link at `point' into emacs-lisp.
  1172. If the path of the link is a file path it is expanded using
  1173. `expand-file-name'."
  1174. (let* ((case-fold-search t)
  1175. (raw (and (looking-at org-bracket-link-regexp)
  1176. (org-babel-clean-text-properties (match-string 1))))
  1177. (type (and (string-match org-link-types-re raw)
  1178. (match-string 1 raw))))
  1179. (cond
  1180. ((not type) (expand-file-name raw))
  1181. ((string= type "file")
  1182. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1183. (expand-file-name (match-string 2 raw))))
  1184. (t raw))))
  1185. (defun org-babel-insert-result
  1186. (result &optional result-params info hash indent lang)
  1187. "Insert RESULT into the current buffer.
  1188. By default RESULT is inserted after the end of the
  1189. current source block. With optional argument RESULT-PARAMS
  1190. controls insertion of results in the org-mode file.
  1191. RESULT-PARAMS can take the following values...
  1192. replace - (default option) insert results after the source block
  1193. replacing any previously inserted results
  1194. silent -- no results are inserted
  1195. file ---- the results are interpreted as a file path, and are
  1196. inserted into the buffer using the Org-mode file syntax
  1197. raw ----- results are added directly to the org-mode file. This
  1198. is a good option if you code block will output org-mode
  1199. formatted text.
  1200. org ----- similar in effect to raw, only the results are wrapped
  1201. in an org code block. Similar to the raw option, on
  1202. export the results will be interpreted as org-formatted
  1203. text, however by wrapping the results in an org code
  1204. block they can be replaced upon re-execution of the
  1205. code block.
  1206. html ---- results are added inside of a #+BEGIN_HTML block. This
  1207. is a good option if you code block will output html
  1208. formatted text.
  1209. latex --- results are added inside of a #+BEGIN_LATEX block.
  1210. This is a good option if you code block will output
  1211. latex formatted text.
  1212. code ---- the results are extracted in the syntax of the source
  1213. code of the language being evaluated and are added
  1214. inside of a #+BEGIN_SRC block with the source-code
  1215. language set appropriately. Note this relies on the
  1216. optional LANG argument."
  1217. (if (stringp result)
  1218. (progn
  1219. (setq result (org-babel-clean-text-properties result))
  1220. (when (member "file" result-params)
  1221. (setq result (org-babel-result-to-file result))))
  1222. (unless (listp result) (setq result (format "%S" result))))
  1223. (if (and result-params (member "silent" result-params))
  1224. (progn
  1225. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1226. result)
  1227. (when (and (stringp result) ;; ensure results end in a newline
  1228. (> (length result) 0)
  1229. (not (or (string-equal (substring result -1) "\n")
  1230. (string-equal (substring result -1) "\r"))))
  1231. (setq result (concat result "\n")))
  1232. (save-excursion
  1233. (let ((existing-result (org-babel-where-is-src-block-result
  1234. t info hash indent))
  1235. (results-switches
  1236. (cdr (assoc :results_switches (nth 2 info))))
  1237. beg end)
  1238. (if (not existing-result)
  1239. (setq beg (point))
  1240. (goto-char existing-result)
  1241. (save-excursion
  1242. (re-search-forward "#" nil t)
  1243. (setq indent (- (current-column) 1)))
  1244. (forward-line 1)
  1245. (setq beg (point))
  1246. (cond
  1247. ((member "replace" result-params)
  1248. (delete-region (point) (org-babel-result-end)))
  1249. ((member "append" result-params)
  1250. (goto-char (org-babel-result-end)) (setq beg (point)))
  1251. ((member "prepend" result-params) ;; already there
  1252. )))
  1253. (setq results-switches
  1254. (if results-switches (concat " " results-switches) ""))
  1255. (cond
  1256. ;; do nothing for an empty result
  1257. ((= (length result) 0))
  1258. ;; assume the result is a table if it's not a string
  1259. ((not (stringp result))
  1260. (insert (concat (orgtbl-to-orgtbl
  1261. (if (or (eq 'hline (car result))
  1262. (and (listp (car result))
  1263. (listp (cdr (car result)))))
  1264. result (list result))
  1265. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1266. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1267. ((member "file" result-params)
  1268. (insert result))
  1269. ((member "html" result-params)
  1270. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  1271. results-switches result)))
  1272. ((member "latex" result-params)
  1273. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1274. results-switches result)))
  1275. ((member "code" result-params)
  1276. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1277. (or lang "none") results-switches result)))
  1278. ((member "org" result-params)
  1279. (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
  1280. ((member "raw" result-params)
  1281. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1282. (t
  1283. (org-babel-examplize-region
  1284. (point) (progn (insert result) (point)) results-switches)))
  1285. ;; possibly indent the results to match the #+results line
  1286. (setq end (if (listp result) (org-table-end) (point)))
  1287. (when (and indent (> indent 0)
  1288. ;; in this case `table-align' does the work for us
  1289. (not (and (listp result)
  1290. (member "append" result-params))))
  1291. (indent-rigidly beg end indent))))
  1292. (if (= (length result) 0)
  1293. (if (member "value" result-params)
  1294. (message "No result returned by source block")
  1295. (message "Source block produced no output"))
  1296. (message "finished"))))
  1297. (defun org-babel-remove-result (&optional info)
  1298. "Remove the result of the current source block."
  1299. (interactive)
  1300. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1301. (when location
  1302. (save-excursion
  1303. (goto-char location) (setq start (point)) (forward-line 1)
  1304. (delete-region start (org-babel-result-end))))))
  1305. (defun org-babel-result-end ()
  1306. "Return the point at the end of the current set of results"
  1307. (save-excursion
  1308. (if (org-at-table-p)
  1309. (progn (goto-char (org-table-end)) (point))
  1310. (let ((case-fold-search t))
  1311. (cond
  1312. ((looking-at "[ \t]*#\\+begin_latex")
  1313. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1314. (forward-line 1))
  1315. ((looking-at "[ \t]*#\\+begin_html")
  1316. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1317. (forward-line 1))
  1318. ((looking-at "[ \t]*#\\+begin_example")
  1319. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1320. (forward-line 1))
  1321. ((looking-at "[ \t]*#\\+begin_src")
  1322. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1323. (forward-line 1))
  1324. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1325. (forward-line 1))))))
  1326. (point))))
  1327. (defun org-babel-result-to-file (result)
  1328. "Convert RESULT into an `org-mode' link.
  1329. If the `default-directory' is different from the containing
  1330. file's directory then expand relative links."
  1331. (format
  1332. "[[file:%s]]"
  1333. (if (and default-directory
  1334. buffer-file-name
  1335. (not (string= (expand-file-name default-directory)
  1336. (expand-file-name
  1337. (file-name-directory buffer-file-name)))))
  1338. (expand-file-name result default-directory)
  1339. result)))
  1340. (defun org-babel-examplize-region (beg end &optional results-switches)
  1341. "Comment out region using the ': ' org example quote."
  1342. (interactive "*r")
  1343. (let ((size (count-lines beg end)))
  1344. (save-excursion
  1345. (cond ((= size 0)
  1346. (error (concat "This should not be impossible:"
  1347. "a newline was appended to result if missing")))
  1348. ((< size org-babel-min-lines-for-block-output)
  1349. (goto-char beg)
  1350. (dotimes (n size)
  1351. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1352. (t
  1353. (goto-char beg)
  1354. (insert (if results-switches
  1355. (format "#+begin_example%s\n" results-switches)
  1356. "#+begin_example\n"))
  1357. (forward-char (- end beg))
  1358. (insert "#+end_example\n"))))))
  1359. (defun org-babel-merge-params (&rest plists)
  1360. "Combine all parameter association lists in PLISTS.
  1361. Later elements of PLISTS override the values of previous element.
  1362. This takes into account some special considerations for certain
  1363. parameters when merging lists."
  1364. (let ((results-exclusive-groups
  1365. '(("file" "vector" "table" "scalar" "raw" "org"
  1366. "html" "latex" "code" "pp")
  1367. ("replace" "silent" "append" "prepend")
  1368. ("output" "value")))
  1369. (exports-exclusive-groups
  1370. '(("code" "results" "both" "none")))
  1371. params results exports tangle noweb cache vars var ref shebang comments)
  1372. (flet ((e-merge (exclusive-groups &rest result-params)
  1373. ;; maintain exclusivity of mutually exclusive parameters
  1374. (let (output)
  1375. (mapc (lambda (new-params)
  1376. (mapc (lambda (new-param)
  1377. (mapc (lambda (exclusive-group)
  1378. (when (member new-param exclusive-group)
  1379. (mapcar (lambda (excluded-param)
  1380. (setq output
  1381. (delete
  1382. excluded-param
  1383. output)))
  1384. exclusive-group)))
  1385. exclusive-groups)
  1386. (setq output (org-uniquify
  1387. (cons new-param output))))
  1388. new-params))
  1389. result-params)
  1390. output)))
  1391. (mapc (lambda (plist)
  1392. (mapc (lambda (pair)
  1393. (case (car pair)
  1394. (:var
  1395. ;; we want only one specification per variable
  1396. (when (string-match
  1397. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1398. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1399. ;; TODO: When is this not true?
  1400. (setq var (intern (match-string 1 (cdr pair)))
  1401. ref (match-string 2 (cdr pair))
  1402. vars (cons (cons var ref)
  1403. (assq-delete-all var vars)))))
  1404. (:results
  1405. (setq results
  1406. (e-merge results-exclusive-groups
  1407. results (split-string (cdr pair)))))
  1408. (:file
  1409. (when (cdr pair)
  1410. (setq results (e-merge results-exclusive-groups
  1411. results '("file")))
  1412. (unless (or (member "both" exports)
  1413. (member "none" exports)
  1414. (member "code" exports))
  1415. (setq exports (e-merge exports-exclusive-groups
  1416. exports '("results"))))
  1417. (setq params
  1418. (cons pair
  1419. (assq-delete-all (car pair) params)))))
  1420. (:exports
  1421. (setq exports
  1422. (e-merge exports-exclusive-groups
  1423. exports (split-string (cdr pair)))))
  1424. (:tangle ;; take the latest -- always overwrite
  1425. (setq tangle (or (list (cdr pair)) tangle)))
  1426. (:noweb
  1427. (setq noweb
  1428. (e-merge '(("yes" "no")) noweb
  1429. (split-string (or (cdr pair) "")))))
  1430. (:cache
  1431. (setq cache
  1432. (e-merge '(("yes" "no")) cache
  1433. (split-string (or (cdr pair) "")))))
  1434. (:shebang ;; take the latest -- always overwrite
  1435. (setq shebang (or (list (cdr pair)) shebang)))
  1436. (:comments
  1437. (setq comments
  1438. (e-merge '(("yes" "no")) comments
  1439. (split-string (or (cdr pair) "")))))
  1440. (t ;; replace: this covers e.g. :session
  1441. (setq params
  1442. (cons pair
  1443. (assq-delete-all (car pair) params))))))
  1444. plist))
  1445. plists))
  1446. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1447. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1448. (cons (cons :comments (mapconcat 'identity comments " "))
  1449. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1450. (cons (cons :cache (mapconcat 'identity cache " "))
  1451. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1452. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1453. (cons (cons :exports
  1454. (mapconcat 'identity exports " "))
  1455. (cons
  1456. (cons :results
  1457. (mapconcat 'identity results " "))
  1458. params)))))))))
  1459. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1460. "Expand Noweb references in the body of the current source code block.
  1461. For example the following reference would be replaced with the
  1462. body of the source-code block named 'example-block'.
  1463. <<example-block>>
  1464. Note that any text preceding the <<foo>> construct on a line will
  1465. be interposed between the lines of the replacement text. So for
  1466. example if <<foo>> is placed behind a comment, then the entire
  1467. replacement text will also be commented.
  1468. This function must be called from inside of the buffer containing
  1469. the source-code block which holds BODY.
  1470. In addition the following syntax can be used to insert the
  1471. results of evaluating the source-code block named 'example-block'.
  1472. <<example-block()>>
  1473. Any optional arguments can be passed to example-block by placing
  1474. the arguments inside the parenthesis following the convention
  1475. defined by `org-babel-lob'. For example
  1476. <<example-block(a=9)>>
  1477. would set the value of argument \"a\" equal to \"9\". Note that
  1478. these arguments are not evaluated in the current source-code
  1479. block but are passed literally to the \"example-block\"."
  1480. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1481. (info (or info (org-babel-get-src-block-info)))
  1482. (lang (nth 0 info))
  1483. (body (nth 1 info))
  1484. (new-body "") index source-name evaluate prefix)
  1485. (flet ((nb-add (text)
  1486. (setq new-body (concat new-body text))))
  1487. (with-temp-buffer
  1488. (insert body) (goto-char (point-min))
  1489. (setq index (point))
  1490. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1491. (save-match-data (setf source-name (match-string 1)))
  1492. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1493. (save-match-data
  1494. (setq prefix
  1495. (buffer-substring (match-beginning 0)
  1496. (save-excursion
  1497. (beginning-of-line 1) (point)))))
  1498. ;; add interval to new-body (removing noweb reference)
  1499. (goto-char (match-beginning 0))
  1500. (nb-add (buffer-substring index (point)))
  1501. (goto-char (match-end 0))
  1502. (setq index (point))
  1503. (nb-add (with-current-buffer parent-buffer
  1504. (mapconcat ;; interpose PREFIX between every line
  1505. #'identity
  1506. (split-string
  1507. (if evaluate
  1508. (let ((raw (org-babel-ref-resolve-reference
  1509. source-name nil)))
  1510. (if (stringp raw) raw (format "%S" raw)))
  1511. (save-restriction
  1512. (widen)
  1513. (let ((point (org-babel-find-named-block
  1514. source-name)))
  1515. (if point
  1516. (save-excursion
  1517. (goto-char point)
  1518. (org-babel-trim
  1519. (org-babel-expand-noweb-references
  1520. (org-babel-get-src-block-info))))
  1521. ;; optionally raise an error if named
  1522. ;; source-block doesn't exist
  1523. (if (member lang org-babel-noweb-error-langs)
  1524. (error "%s"
  1525. (concat
  1526. "<<" source-name ">> "
  1527. "could not be resolved (see "
  1528. "`org-babel-noweb-error-langs')"))
  1529. "")))))
  1530. "[\n\r]") (concat "\n" prefix)))))
  1531. (nb-add (buffer-substring index (point-max)))))
  1532. new-body))
  1533. (defun org-babel-clean-text-properties (text)
  1534. "Strip all properties from text return."
  1535. (when text
  1536. (set-text-properties 0 (length text) nil text) text))
  1537. (defun org-babel-strip-protective-commas (body)
  1538. "Strip protective commas from bodies of source blocks."
  1539. (replace-regexp-in-string "^,#" "#" body))
  1540. (defun org-babel-read (cell)
  1541. "Convert the string value of CELL to a number if appropriate.
  1542. Otherwise if cell looks like lisp (meaning it starts with a
  1543. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1544. unmodified as a string.
  1545. This is taken almost directly from `org-read-prop'."
  1546. (if (and (stringp cell) (not (equal cell "")))
  1547. (or (org-babel-number-p cell)
  1548. (if (or (equal "(" (substring cell 0 1))
  1549. (equal "'" (substring cell 0 1))
  1550. (equal "`" (substring cell 0 1)))
  1551. (eval (read cell))
  1552. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1553. cell))
  1554. (defun org-babel-number-p (string)
  1555. "Return t if STRING represents a number."
  1556. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1557. (= (length (substring string (match-beginning 0)
  1558. (match-end 0)))
  1559. (length string)))
  1560. (string-to-number string)))
  1561. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1562. "Read the results located at FILE-NAME into an elisp table.
  1563. If the table is trivial, then return it as a scalar."
  1564. (let (result)
  1565. (save-window-excursion
  1566. (with-temp-buffer
  1567. (condition-case nil
  1568. (progn
  1569. (org-table-import file-name separator)
  1570. (delete-file file-name)
  1571. (setq result (mapcar (lambda (row)
  1572. (mapcar #'org-babel-string-read row))
  1573. (org-table-to-lisp))))
  1574. (error nil)))
  1575. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1576. (if (consp (car result))
  1577. (if (null (cdr (car result)))
  1578. (caar result)
  1579. result)
  1580. (car result))
  1581. result))))
  1582. (defun org-babel-string-read (cell)
  1583. "Strip nested \"s from around strings."
  1584. (org-babel-read (or (and (stringp cell)
  1585. (string-match "\\\"\\(.+\\)\\\"" cell)
  1586. (match-string 1 cell))
  1587. cell)))
  1588. (defun org-babel-reverse-string (string)
  1589. "Return the reverse of STRING."
  1590. (apply 'string (reverse (string-to-list string))))
  1591. (defun org-babel-chomp (string &optional regexp)
  1592. "Strip trailing spaces and carriage returns from STRING.
  1593. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1594. overwritten by specifying a regexp as a second argument."
  1595. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1596. (while (and (> (length string) 0)
  1597. (string-match regexp (substring string -1)))
  1598. (setq string (substring string 0 -1)))
  1599. string))
  1600. (defun org-babel-trim (string &optional regexp)
  1601. "Strip leading and trailing spaces and carriage returns from STRING.
  1602. Like `org-babel-chomp' only it runs on both the front and back
  1603. of the string."
  1604. (org-babel-chomp (org-babel-reverse-string
  1605. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1606. regexp))
  1607. (defvar org-babel-org-babel-call-process-region-original nil)
  1608. (defun org-babel-tramp-handle-call-process-region
  1609. (start end program &optional delete buffer display &rest args)
  1610. "Use tramp to handle call-process-region.
  1611. Fixes a bug in `tramp-handle-call-process-region'."
  1612. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1613. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1614. (write-region start end tmpfile)
  1615. (when delete (delete-region start end))
  1616. (unwind-protect
  1617. ;; (apply 'call-process program tmpfile buffer display args)
  1618. ;; bug in tramp
  1619. (apply 'process-file program tmpfile buffer display args)
  1620. (delete-file tmpfile)))
  1621. ;; org-babel-call-process-region-original is the original emacs definition. It
  1622. ;; is in scope from the let binding in org-babel-execute-src-block
  1623. (apply org-babel-call-process-region-original
  1624. start end program delete buffer display args)))
  1625. (defun org-babel-local-file-name (file)
  1626. "Return the local name component of FILE."
  1627. (if (file-remote-p file)
  1628. (let (localname)
  1629. (with-parsed-tramp-file-name file nil
  1630. localname))
  1631. file))
  1632. (defun org-babel-process-file-name (name &optional no-quote-p)
  1633. "Prepare NAME to be used in an external process.
  1634. If NAME specifies a remote location, the remote portion of the
  1635. name is removed, since in that case the process will be executing
  1636. remotely. The file name is then processed by
  1637. `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
  1638. the file name is additionally processed by
  1639. `shell-quote-argument'"
  1640. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  1641. (expand-file-name (org-babel-local-file-name name))))
  1642. ;; (defvar org-babel-temporary-directory
  1643. ;; (or (and (boundp 'org-babel-temporary-directory)
  1644. ;; org-babel-temporary-directory)
  1645. ;; (make-temp-file "babel-" t))
  1646. ;; "Directory to hold temporary files created to execute code blocks.
  1647. ;; Used by `org-babel-temp-file'. This directory will be removed on
  1648. ;; Emacs shutdown.")
  1649. (defun org-babel-temp-file (prefix &optional suffix)
  1650. "Create a temporary file in the `org-babel-temporary-directory'.
  1651. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1652. value of `temporary-file-directory' temporarily set to the value
  1653. of `org-babel-temporary-directory'."
  1654. (if (file-remote-p default-directory)
  1655. (make-temp-file
  1656. (concat (file-remote-p default-directory)
  1657. (expand-file-name
  1658. prefix temporary-file-directory)
  1659. nil suffix))
  1660. ;; (let ((temporary-file-directory (expand-file-name
  1661. ;; org-babel-temporary-directory
  1662. ;; temporary-file-directory)))
  1663. ;; (make-temp-file prefix nil suffix))
  1664. (make-temp-file prefix nil suffix)))
  1665. ;; (defun org-babel-remove-temporary-directory ()
  1666. ;; "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1667. ;; (when (boundp 'org-babel-temporary-directory)
  1668. ;; ;; taken from `delete-directory' in files.el
  1669. ;; (mapc (lambda (file)
  1670. ;; ;; This test is equivalent to
  1671. ;; ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1672. ;; ;; but more efficient
  1673. ;; (if (eq t (car (file-attributes file)))
  1674. ;; (delete-directory file)
  1675. ;; (delete-file file)))
  1676. ;; ;; We do not want to delete "." and "..".
  1677. ;; (directory-files org-babel-temporary-directory 'full
  1678. ;; "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1679. ;; (delete-directory org-babel-temporary-directory)))
  1680. ;; (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1681. (provide 'ob)
  1682. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1683. ;;; ob.el ends here