ob-core.el 100 KB

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