ob.el 99 KB

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