ob.el 82 KB

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