ob-core.el 100 KB

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