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