ob-core.el 100 KB

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