ob-core.el 100 KB

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