ob.el 80 KB

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