ob-core.el 101 KB

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