ob.el 83 KB

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