ob.el 80 KB

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