ob-core.el 99 KB

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