ob.el 73 KB

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