ob-core.el 100 KB

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