ob.el 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  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-current-result-hash)))
  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-current-result-hash ()
  720. "Return the in-buffer hash associated with INFO."
  721. (org-babel-where-is-src-block-result)
  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
  882. (let* ((body (match-string 5))
  883. (sub-length (- (length body) 1)))
  884. (if (string= "\n" (substring body sub-length))
  885. (substring body 0 sub-length)
  886. body))))
  887. (preserve-indentation (or org-src-preserve-indentation
  888. (string-match "-i\\>" switches))))
  889. (list lang
  890. ;; get block body less properties, protective commas, and indentation
  891. (with-temp-buffer
  892. (save-match-data
  893. (insert (org-babel-strip-protective-commas body))
  894. (unless preserve-indentation (org-do-remove-indentation))
  895. (buffer-string)))
  896. (org-babel-merge-params
  897. org-babel-default-header-args
  898. (org-babel-params-from-buffer)
  899. (org-babel-params-from-properties lang)
  900. (if (boundp lang-headers) (eval lang-headers) nil)
  901. (org-babel-parse-header-arguments
  902. (org-babel-clean-text-properties (or (match-string 4) ""))))
  903. switches
  904. block-indentation)))
  905. (defun org-babel-parse-inline-src-block-match ()
  906. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  907. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  908. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  909. (list lang
  910. (org-babel-strip-protective-commas
  911. (org-babel-clean-text-properties (match-string 5)))
  912. (org-babel-merge-params
  913. org-babel-default-inline-header-args
  914. (org-babel-params-from-buffer)
  915. (org-babel-params-from-properties lang)
  916. (if (boundp lang-headers) (eval lang-headers) nil)
  917. (org-babel-parse-header-arguments
  918. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  919. (defun org-babel-parse-header-arguments (arg-string)
  920. "Parse a string of header arguments returning an alist."
  921. (when (> (length arg-string) 0)
  922. (delq nil
  923. (mapcar
  924. (lambda (arg)
  925. (if (string-match
  926. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  927. arg)
  928. (cons (intern (match-string 1 arg))
  929. (org-babel-read (org-babel-chomp (match-string 2 arg))))
  930. (cons (intern (org-babel-chomp arg)) nil)))
  931. (let ((balance 0) (partial nil) (lst nil) (last 0))
  932. (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
  933. (setq balance (+ balance
  934. (cond ((equal 91 ch) 1)
  935. ((equal 93 ch) -1)
  936. (t 0))))
  937. (setq partial (cons ch partial))
  938. (when (and (= ch 58) (= balance 0)
  939. (or (= last 32) (= last 9)))
  940. (setq lst (cons (apply #'string (nreverse (cddr partial)))
  941. lst))
  942. (setq partial (list ch)))
  943. (setq last ch))
  944. (string-to-list arg-string))
  945. (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
  946. (defun org-babel-process-params (params)
  947. "Expand variables in PARAMS and add summary parameters."
  948. (let* ((vars-and-names (org-babel-disassemble-tables
  949. (mapcar (lambda (el)
  950. (if (consp (cdr el))
  951. (cdr el) (org-babel-ref-parse (cdr el))))
  952. (org-babel-get-header params :var))
  953. (cdr (assoc :hlines params))
  954. (cdr (assoc :colnames params))
  955. (cdr (assoc :rownames params))))
  956. (raw-result (or (cdr (assoc :results params)) ""))
  957. (result-params (append
  958. (split-string (if (stringp raw-result)
  959. raw-result
  960. (eval raw-result)))
  961. (cdr (assoc :result-params params)))))
  962. (append
  963. (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
  964. (list
  965. (cons :colname-names (or (cdr (assoc :colname-names params))
  966. (cadr vars-and-names)))
  967. (cons :rowname-names (or (cdr (assoc :rowname-names params))
  968. (caddr vars-and-names)))
  969. (cons :result-params result-params)
  970. (cons :result-type (cond ((member "output" result-params) 'output)
  971. ((member "value" result-params) 'value)
  972. (t 'value))))
  973. (org-babel-get-header params :var 'other))))
  974. ;; row and column names
  975. (defun org-babel-del-hlines (table)
  976. "Remove all 'hlines from TABLE."
  977. (remove 'hline table))
  978. (defun org-babel-get-colnames (table)
  979. "Return the column names of TABLE.
  980. Return a cons cell, the `car' of which contains the TABLE less
  981. colnames, and the `cdr' of which contains a list of the column
  982. names."
  983. (if (equal 'hline (nth 1 table))
  984. (cons (cddr table) (car table))
  985. (cons (cdr table) (car table))))
  986. (defun org-babel-get-rownames (table)
  987. "Return the row names of TABLE.
  988. Return a cons cell, the `car' of which contains the TABLE less
  989. colnames, and the `cdr' of which contains a list of the column
  990. names. Note: this function removes any hlines in TABLE."
  991. (flet ((trans (table) (apply #'mapcar* #'list table)))
  992. (let* ((width (apply 'max
  993. (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  994. (table (trans (mapcar (lambda (row)
  995. (if (not (equal row 'hline))
  996. row
  997. (setq row '())
  998. (dotimes (n width)
  999. (setq row (cons 'hline row)))
  1000. row))
  1001. table))))
  1002. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  1003. (trans (cdr table)))
  1004. (remove 'hline (car table))))))
  1005. (defun org-babel-put-colnames (table colnames)
  1006. "Add COLNAMES to TABLE if they exist."
  1007. (if colnames (apply 'list colnames 'hline table) table))
  1008. (defun org-babel-put-rownames (table rownames)
  1009. "Add ROWNAMES to TABLE if they exist."
  1010. (if rownames
  1011. (mapcar (lambda (row)
  1012. (if (listp row)
  1013. (cons (or (pop rownames) "") row)
  1014. row)) table)
  1015. table))
  1016. (defun org-babel-pick-name (names selector)
  1017. "Select one out of an alist of row or column names.
  1018. SELECTOR can be either a list of names in which case those names
  1019. will be returned directly, or an index into the list NAMES in
  1020. which case the indexed names will be return."
  1021. (if (listp selector)
  1022. selector
  1023. (when names
  1024. (if (and selector (symbolp selector) (not (equal t selector)))
  1025. (cdr (assoc selector names))
  1026. (if (integerp selector)
  1027. (nth (- selector 1) names)
  1028. (cdr (car (last names))))))))
  1029. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  1030. "Parse tables for further processing.
  1031. Process the variables in VARS according to the HLINES,
  1032. ROWNAMES and COLNAMES header arguments. Return a list consisting
  1033. of the vars, cnames and rnames."
  1034. (let (cnames rnames)
  1035. (list
  1036. (mapcar
  1037. (lambda (var)
  1038. (when (listp (cdr var))
  1039. (when (and (not (equal colnames "no"))
  1040. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  1041. (not (member 'hline (cddr (cdr var)))))))
  1042. (let ((both (org-babel-get-colnames (cdr var))))
  1043. (setq cnames (cons (cons (car var) (cdr both))
  1044. cnames))
  1045. (setq var (cons (car var) (car both)))))
  1046. (when (and rownames (not (equal rownames "no")))
  1047. (let ((both (org-babel-get-rownames (cdr var))))
  1048. (setq rnames (cons (cons (car var) (cdr both))
  1049. rnames))
  1050. (setq var (cons (car var) (car both)))))
  1051. (when (and hlines (not (equal hlines "yes")))
  1052. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  1053. var)
  1054. vars)
  1055. cnames rnames)))
  1056. (defun org-babel-reassemble-table (table colnames rownames)
  1057. "Add column and row names to a table.
  1058. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  1059. to the table for reinsertion to org-mode."
  1060. (if (listp table)
  1061. ((lambda (table)
  1062. (if (and colnames (listp (car table)) (= (length (car table))
  1063. (length colnames)))
  1064. (org-babel-put-colnames table colnames) table))
  1065. (if (and rownames (= (length table) (length rownames)))
  1066. (org-babel-put-rownames table rownames) table))
  1067. table))
  1068. (defun org-babel-where-is-src-block-head ()
  1069. "Find where the current source block begins.
  1070. Return the point at the beginning of the current source
  1071. block. Specifically at the beginning of the #+BEGIN_SRC line.
  1072. If the point is not on a source block then return nil."
  1073. (let ((initial (point)) top bottom)
  1074. (or
  1075. (save-excursion ;; on a source name line or a #+header line
  1076. (beginning-of-line 1)
  1077. (and (or (looking-at org-babel-src-name-regexp)
  1078. (looking-at org-babel-multi-line-header-regexp))
  1079. (progn
  1080. (while (and (forward-line 1)
  1081. (looking-at org-babel-multi-line-header-regexp)))
  1082. (looking-at org-babel-src-block-regexp))
  1083. (point)))
  1084. (save-excursion ;; on a #+begin_src line
  1085. (beginning-of-line 1)
  1086. (and (looking-at org-babel-src-block-regexp)
  1087. (point)))
  1088. (save-excursion ;; inside a src block
  1089. (and
  1090. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  1091. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  1092. (< top initial) (< initial bottom)
  1093. (progn (goto-char top) (beginning-of-line 1)
  1094. (looking-at org-babel-src-block-regexp))
  1095. (point))))))
  1096. ;;;###autoload
  1097. (defun org-babel-goto-src-block-head ()
  1098. "Go to the beginning of the current code block."
  1099. (interactive)
  1100. ((lambda (head)
  1101. (if head (goto-char head) (error "not currently in a code block")))
  1102. (org-babel-where-is-src-block-head)))
  1103. ;;;###autoload
  1104. (defun org-babel-goto-named-src-block (name)
  1105. "Go to a named source-code block."
  1106. (interactive
  1107. (let ((completion-ignore-case t))
  1108. (list (org-icompleting-read "source-block name: "
  1109. (org-babel-src-block-names) nil t))))
  1110. (let ((point (org-babel-find-named-block name)))
  1111. (if point
  1112. ;; taken from `org-open-at-point'
  1113. (progn (goto-char point) (org-show-context))
  1114. (message "source-code block '%s' not found in this buffer" name))))
  1115. (defun org-babel-find-named-block (name)
  1116. "Find a named source-code block.
  1117. Return the location of the source block identified by source
  1118. NAME, or nil if no such block exists. Set match data according to
  1119. org-babel-named-src-block-regexp."
  1120. (save-excursion
  1121. (let ((case-fold-search t)
  1122. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  1123. (goto-char (point-min))
  1124. (when (or (re-search-forward regexp nil t)
  1125. (re-search-backward regexp nil t))
  1126. (match-beginning 0)))))
  1127. (defun org-babel-src-block-names (&optional file)
  1128. "Returns the names of source blocks in FILE or the current buffer."
  1129. (save-excursion
  1130. (when file (find-file file)) (goto-char (point-min))
  1131. (let (names)
  1132. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  1133. (setq names (cons (match-string 4) names)))
  1134. names)))
  1135. ;;;###autoload
  1136. (defun org-babel-goto-named-result (name)
  1137. "Go to a named result."
  1138. (interactive
  1139. (let ((completion-ignore-case t))
  1140. (list (org-icompleting-read "source-block name: "
  1141. (org-babel-result-names) nil t))))
  1142. (let ((point (org-babel-find-named-result name)))
  1143. (if point
  1144. ;; taken from `org-open-at-point'
  1145. (progn (goto-char point) (org-show-context))
  1146. (message "result '%s' not found in this buffer" name))))
  1147. (defun org-babel-find-named-result (name)
  1148. "Find a named result.
  1149. Return the location of the result named NAME in the current
  1150. buffer or nil if no such result exists."
  1151. (save-excursion
  1152. (goto-char (point-min))
  1153. (when (re-search-forward
  1154. (concat org-babel-result-regexp
  1155. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  1156. (beginning-of-line 0) (point))))
  1157. (defun org-babel-result-names (&optional file)
  1158. "Returns the names of results in FILE or the current buffer."
  1159. (save-excursion
  1160. (when file (find-file file)) (goto-char (point-min))
  1161. (let (names)
  1162. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1163. (setq names (cons (match-string 4) names)))
  1164. names)))
  1165. ;;;###autoload
  1166. (defun org-babel-next-src-block (&optional arg)
  1167. "Jump to the next source block.
  1168. With optional prefix argument ARG, jump forward ARG many source blocks."
  1169. (interactive "P")
  1170. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1171. (condition-case nil
  1172. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1173. (error (error "No further code blocks")))
  1174. (goto-char (match-beginning 0)) (org-show-context))
  1175. ;;;###autoload
  1176. (defun org-babel-previous-src-block (&optional arg)
  1177. "Jump to the previous source block.
  1178. With optional prefix argument ARG, jump backward ARG many source blocks."
  1179. (interactive "P")
  1180. (condition-case nil
  1181. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1182. (error (error "No previous code blocks")))
  1183. (goto-char (match-beginning 0)) (org-show-context))
  1184. (defvar org-babel-load-languages)
  1185. ;;;###autoload
  1186. (defun org-babel-mark-block ()
  1187. "Mark current src block"
  1188. (interactive)
  1189. ((lambda (head)
  1190. (when head
  1191. (save-excursion
  1192. (goto-char head)
  1193. (looking-at org-babel-src-block-regexp))
  1194. (push-mark (match-end 5) nil t)
  1195. (goto-char (match-beginning 5))))
  1196. (org-babel-where-is-src-block-head)))
  1197. (defun org-babel-demarcate-block (&optional arg)
  1198. "Wrap or split the code in the region or on the point.
  1199. When called from inside of a code block the current block is
  1200. split. When called from outside of a code block a new code block
  1201. is created. In both cases if the region is demarcated and if the
  1202. region is not active then the point is demarcated."
  1203. (interactive "P")
  1204. (let ((info (org-babel-get-src-block-info 'light))
  1205. (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
  1206. (if info
  1207. (mapc
  1208. (lambda (place)
  1209. (save-excursion
  1210. (goto-char place)
  1211. (let ((lang (nth 0 info))
  1212. (indent (make-string (nth 5 info) ? )))
  1213. (when (string-match "^[[:space:]]*$"
  1214. (buffer-substring (point-at-bol)
  1215. (point-at-eol)))
  1216. (delete-region (point-at-bol) (point-at-eol)))
  1217. (insert (concat (if (looking-at "^") "" "\n")
  1218. indent "#+end_src\n"
  1219. (if arg stars indent) "\n"
  1220. indent "#+begin_src " lang
  1221. (if (looking-at "[\n\r]") "" "\n")))))
  1222. (move-end-of-line 2))
  1223. (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
  1224. (let ((start (point))
  1225. (lang (org-icompleting-read "Lang: "
  1226. (mapcar (lambda (el) (symbol-name (car el)))
  1227. org-babel-load-languages)))
  1228. (body (delete-and-extract-region
  1229. (if (region-active-p) (mark) (point)) (point))))
  1230. (insert (concat (if (looking-at "^") "" "\n")
  1231. (if arg (concat stars "\n") "")
  1232. "#+begin_src " lang "\n"
  1233. body
  1234. (if (or (= (length body) 0)
  1235. (string-match "[\r\n]$" body)) "" "\n")
  1236. "#+end_src\n"))
  1237. (goto-char start) (move-end-of-line 1)))))
  1238. (defvar org-babel-lob-one-liner-regexp)
  1239. (defvar org-babel-inline-lob-one-liner-regexp)
  1240. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1241. "Find where the current source block results begin.
  1242. Return the point at the beginning of the result of the current
  1243. source block. Specifically at the beginning of the results line.
  1244. If no result exists for this block then create a results line
  1245. following the source block."
  1246. (save-excursion
  1247. (let* ((on-lob-line (save-excursion
  1248. (beginning-of-line 1)
  1249. (looking-at org-babel-lob-one-liner-regexp)))
  1250. (inlinep (save-excursion
  1251. (re-search-backward "[ \f\t\n\r\v]" nil t)
  1252. (when (looking-at org-babel-inline-src-block-regexp)
  1253. (match-end 0))))
  1254. (name (if on-lob-line
  1255. (nth 0 (org-babel-lob-get-info))
  1256. (nth 4 (or info (org-babel-get-src-block-info)))))
  1257. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1258. found beg end)
  1259. (when head (goto-char head))
  1260. (setq
  1261. found ;; was there a result (before we potentially insert one)
  1262. (or
  1263. inlinep
  1264. (and
  1265. ;; named results:
  1266. ;; - return t if it is found, else return nil
  1267. ;; - if it does not need to be rebuilt, then don't set end
  1268. ;; - if it does need to be rebuilt then do set end
  1269. name (setq beg (org-babel-find-named-result name))
  1270. (prog1 beg
  1271. (when (and hash (not (string= hash (match-string 3))))
  1272. (goto-char beg) (setq end beg) ;; beginning of result
  1273. (forward-line 1)
  1274. (delete-region end (org-babel-result-end)) nil)))
  1275. (and
  1276. ;; unnamed results:
  1277. ;; - return t if it is found, else return nil
  1278. ;; - if it is found, and the hash doesn't match, delete and set end
  1279. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1280. (progn (end-of-line 1)
  1281. (if (eobp) (insert "\n") (forward-char 1))
  1282. (setq end (point))
  1283. (or (and (not name)
  1284. (progn ;; unnamed results line already exists
  1285. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1286. (beginning-of-line 1)
  1287. (looking-at
  1288. (concat org-babel-result-regexp "\n")))
  1289. (prog1 (point)
  1290. ;; must remove and rebuild if hash!=old-hash
  1291. (if (and hash (not (string= hash (match-string 3))))
  1292. (prog1 nil
  1293. (forward-line 1)
  1294. (delete-region
  1295. end (org-babel-result-end)))
  1296. (setq end nil)))))))))
  1297. (if (and insert end)
  1298. (progn
  1299. (goto-char end)
  1300. (unless beg
  1301. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1302. (insert (concat
  1303. (if indent
  1304. (mapconcat
  1305. (lambda (el) " ")
  1306. (org-number-sequence 1 indent) "")
  1307. "")
  1308. "#+results"
  1309. (when hash (concat "["hash"]"))
  1310. ":"
  1311. (when name (concat " " name)) "\n"))
  1312. (unless beg (insert "\n") (backward-char))
  1313. (beginning-of-line 0)
  1314. (if hash (org-babel-hide-hash))
  1315. (point))
  1316. found))))
  1317. (defvar org-block-regexp)
  1318. (defun org-babel-read-result ()
  1319. "Read the result at `point' into emacs-lisp."
  1320. (let ((case-fold-search t) result-string)
  1321. (cond
  1322. ((org-at-table-p) (org-babel-read-table))
  1323. ((org-at-item-p) (org-babel-read-list))
  1324. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1325. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1326. ((looking-at "^[ \t]*: ")
  1327. (setq result-string
  1328. (org-babel-trim
  1329. (mapconcat (lambda (line)
  1330. (if (and (> (length line) 1)
  1331. (string-match "^[ \t]*: \\(.+\\)" line))
  1332. (match-string 1 line)
  1333. line))
  1334. (split-string
  1335. (buffer-substring
  1336. (point) (org-babel-result-end)) "[\r\n]+")
  1337. "\n")))
  1338. (or (org-babel-number-p result-string) result-string))
  1339. ((looking-at org-babel-result-regexp)
  1340. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1341. (defun org-babel-read-table ()
  1342. "Read the table at `point' into emacs-lisp."
  1343. (mapcar (lambda (row)
  1344. (if (and (symbolp row) (equal row 'hline)) row
  1345. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
  1346. (org-table-to-lisp)))
  1347. (defun org-babel-read-list ()
  1348. "Read the list at `point' into emacs-lisp."
  1349. (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
  1350. (mapcar #'cadr (cdr (org-list-parse-list)))))
  1351. (defvar org-link-types-re)
  1352. (defun org-babel-read-link ()
  1353. "Read the link at `point' into emacs-lisp.
  1354. If the path of the link is a file path it is expanded using
  1355. `expand-file-name'."
  1356. (let* ((case-fold-search t)
  1357. (raw (and (looking-at org-bracket-link-regexp)
  1358. (org-babel-clean-text-properties (match-string 1))))
  1359. (type (and (string-match org-link-types-re raw)
  1360. (match-string 1 raw))))
  1361. (cond
  1362. ((not type) (expand-file-name raw))
  1363. ((string= type "file")
  1364. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1365. (expand-file-name (match-string 2 raw))))
  1366. (t raw))))
  1367. (defun org-babel-format-result (result &optional sep)
  1368. "Format RESULT for writing to file."
  1369. (flet ((echo-res (result)
  1370. (if (stringp result) result (format "%S" result))))
  1371. (if (listp result)
  1372. ;; table result
  1373. (orgtbl-to-generic
  1374. result
  1375. (list
  1376. :sep (or sep "\t")
  1377. :fmt 'echo-res))
  1378. ;; scalar result
  1379. (echo-res result))))
  1380. (defun org-babel-insert-result
  1381. (result &optional result-params info hash indent lang)
  1382. "Insert RESULT into the current buffer.
  1383. By default RESULT is inserted after the end of the
  1384. current source block. With optional argument RESULT-PARAMS
  1385. controls insertion of results in the org-mode file.
  1386. RESULT-PARAMS can take the following values...
  1387. replace - (default option) insert results after the source block
  1388. replacing any previously inserted results
  1389. silent -- no results are inserted
  1390. file ---- the results are interpreted as a file path, and are
  1391. inserted into the buffer using the Org-mode file syntax
  1392. list ---- the results are interpreted as an Org-mode list.
  1393. raw ----- results are added directly to the Org-mode file. This
  1394. is a good option if you code block will output org-mode
  1395. formatted text.
  1396. org ----- similar in effect to raw, only the results are wrapped
  1397. in an org code block. Similar to the raw option, on
  1398. export the results will be interpreted as org-formatted
  1399. text, however by wrapping the results in an org code
  1400. block they can be replaced upon re-execution of the
  1401. code block.
  1402. html ---- results are added inside of a #+BEGIN_HTML block. This
  1403. is a good option if you code block will output html
  1404. formatted text.
  1405. latex --- results are added inside of a #+BEGIN_LATEX block.
  1406. This is a good option if you code block will output
  1407. latex formatted text.
  1408. code ---- the results are extracted in the syntax of the source
  1409. code of the language being evaluated and are added
  1410. inside of a #+BEGIN_SRC block with the source-code
  1411. language set appropriately. Note this relies on the
  1412. optional LANG argument."
  1413. (if (stringp result)
  1414. (progn
  1415. (setq result (org-babel-clean-text-properties result))
  1416. (when (member "file" result-params)
  1417. (setq result (org-babel-result-to-file result))))
  1418. (unless (listp result) (setq result (format "%S" result))))
  1419. (if (and result-params (member "silent" result-params))
  1420. (progn
  1421. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1422. result)
  1423. (save-excursion
  1424. (let* ((inlinep
  1425. (save-excursion
  1426. (or (= (point) (point-at-bol))
  1427. (re-search-backward "[ \f\t\n\r\v]" nil t))
  1428. (when (or (looking-at org-babel-inline-src-block-regexp)
  1429. (looking-at org-babel-inline-lob-one-liner-regexp))
  1430. (goto-char (match-end 0))
  1431. (insert (if (listp result) "\n" " "))
  1432. (point))))
  1433. (existing-result (unless inlinep
  1434. (org-babel-where-is-src-block-result
  1435. t info hash indent)))
  1436. (results-switches
  1437. (cdr (assoc :results_switches (nth 2 info))))
  1438. beg end)
  1439. (when (and (stringp result) ; ensure results end in a newline
  1440. (not inlinep)
  1441. (> (length result) 0)
  1442. (not (or (string-equal (substring result -1) "\n")
  1443. (string-equal (substring result -1) "\r"))))
  1444. (setq result (concat result "\n")))
  1445. (if (not existing-result)
  1446. (setq beg (or inlinep (point)))
  1447. (goto-char existing-result)
  1448. (save-excursion
  1449. (re-search-forward "#" nil t)
  1450. (setq indent (- (current-column) 1)))
  1451. (forward-line 1)
  1452. (setq beg (point))
  1453. (cond
  1454. ((member "replace" result-params)
  1455. (delete-region (point) (org-babel-result-end)))
  1456. ((member "append" result-params)
  1457. (goto-char (org-babel-result-end)) (setq beg (point-marker)))
  1458. ((member "prepend" result-params)))) ; already there
  1459. (setq results-switches
  1460. (if results-switches (concat " " results-switches) ""))
  1461. ;; insert results based on type
  1462. (cond
  1463. ;; do nothing for an empty result
  1464. ((= (length result) 0))
  1465. ;; insert a list if preferred
  1466. ((member "list" result-params)
  1467. (insert
  1468. (org-babel-trim
  1469. (org-list-to-generic
  1470. (cons 'unordered
  1471. (mapcar
  1472. (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
  1473. (if (listp result) result (list result))))
  1474. '(:splicep nil :istart "- " :iend "\n")))
  1475. "\n"))
  1476. ;; assume the result is a table if it's not a string
  1477. ((not (stringp result))
  1478. (goto-char beg)
  1479. (insert (concat (orgtbl-to-orgtbl
  1480. (if (or (eq 'hline (car result))
  1481. (and (listp (car result))
  1482. (listp (cdr (car result)))))
  1483. result (list result))
  1484. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1485. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1486. ((member "file" result-params)
  1487. (insert result))
  1488. (t (goto-char beg) (insert result)))
  1489. (when (listp result) (goto-char (org-table-end)))
  1490. (setq end (point-marker))
  1491. ;; possibly wrap result
  1492. (flet ((wrap (start finish)
  1493. (goto-char beg) (insert (concat start "\n"))
  1494. (goto-char end) (insert (concat finish "\n"))
  1495. (setq end (point-marker))))
  1496. (cond
  1497. ((member "html" result-params)
  1498. (wrap "#+BEGIN_HTML" "#+END_HTML"))
  1499. ((member "latex" result-params)
  1500. (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
  1501. ((member "code" result-params)
  1502. (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
  1503. "#+END_SRC"))
  1504. ((member "org" result-params)
  1505. (wrap "#+BEGIN_ORG" "#+END_ORG"))
  1506. ((member "raw" result-params)
  1507. (goto-char beg) (if (org-at-table-p) (org-cycle)))
  1508. ((member "wrap" result-params)
  1509. (when (and (stringp result) (not (member "file" result-params)))
  1510. (org-babel-examplize-region beg end results-switches))
  1511. (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
  1512. ((and (stringp result) (not (member "file" result-params)))
  1513. (org-babel-examplize-region beg end results-switches)
  1514. (setq end (point)))))
  1515. ;; possibly indent the results to match the #+results line
  1516. (when (and (not inlinep) (numberp indent) indent (> indent 0)
  1517. ;; in this case `table-align' does the work for us
  1518. (not (and (listp result)
  1519. (member "append" result-params))))
  1520. (indent-rigidly beg end indent))))
  1521. (if (= (length result) 0)
  1522. (if (member "value" result-params)
  1523. (message "Code block returned no value.")
  1524. (message "Code block produced no output."))
  1525. (message "Code block evaluation complete."))))
  1526. (defun org-babel-remove-result (&optional info)
  1527. "Remove the result of the current source block."
  1528. (interactive)
  1529. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1530. (when location
  1531. (save-excursion
  1532. (goto-char location) (setq start (point)) (forward-line 1)
  1533. (delete-region start (org-babel-result-end))))))
  1534. (defun org-babel-result-end ()
  1535. "Return the point at the end of the current set of results"
  1536. (save-excursion
  1537. (cond
  1538. ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
  1539. ((org-at-item-p) (let* ((struct (org-list-struct))
  1540. (prvs (org-list-prevs-alist struct)))
  1541. (org-list-get-list-end (point-at-bol) struct prvs)))
  1542. (t
  1543. (let ((case-fold-search t)
  1544. (blocks-re (regexp-opt
  1545. (list "latex" "html" "example" "src" "result" "org"))))
  1546. (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
  1547. (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
  1548. (forward-char 1))
  1549. (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1550. (forward-line 1))))
  1551. (point)))))
  1552. (defun org-babel-result-to-file (result)
  1553. "Convert RESULT into an `org-mode' link.
  1554. If the `default-directory' is different from the containing
  1555. file's directory then expand relative links."
  1556. (flet ((cond-exp (file)
  1557. (if (and default-directory
  1558. buffer-file-name
  1559. (not (string= (expand-file-name default-directory)
  1560. (expand-file-name
  1561. (file-name-directory buffer-file-name)))))
  1562. (expand-file-name file default-directory)
  1563. file)))
  1564. (if (stringp result)
  1565. (format "[[file:%s]]" (cond-exp result))
  1566. (when (and (listp result) (= 2 (length result))
  1567. (stringp (car result)) (stringp (cadr result)))
  1568. (format "[[file:%s][%s]]" (car result) (cadr result))))))
  1569. (defun org-babel-examplize-region (beg end &optional results-switches)
  1570. "Comment out region using the inline '==' or ': ' org example quote."
  1571. (interactive "*r")
  1572. (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
  1573. (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
  1574. (chars-between end (save-excursion (goto-char end) (point-at-eol))))
  1575. (save-excursion
  1576. (goto-char beg)
  1577. (insert (format "=%s=" (prog1 (buffer-substring beg end)
  1578. (delete-region beg end)))))
  1579. (let ((size (count-lines beg end)))
  1580. (save-excursion
  1581. (cond ((= size 0)) ; do nothing for an empty result
  1582. ((< size org-babel-min-lines-for-block-output)
  1583. (goto-char beg)
  1584. (dotimes (n size)
  1585. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1586. (t
  1587. (goto-char beg)
  1588. (insert (if results-switches
  1589. (format "#+begin_example%s\n" results-switches)
  1590. "#+begin_example\n"))
  1591. (if (markerp end) (goto-char end) (forward-char (- end beg)))
  1592. (insert "#+end_example\n"))))))))
  1593. (defun org-babel-update-block-body (new-body)
  1594. "Update the body of the current code block to NEW-BODY."
  1595. (if (not (org-babel-where-is-src-block-head))
  1596. (error "not in source block")
  1597. (save-match-data
  1598. (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
  1599. (indent-rigidly (match-beginning 5) (match-end 5) 2)))
  1600. (defun org-babel-merge-params (&rest plists)
  1601. "Combine all parameter association lists in PLISTS.
  1602. Later elements of PLISTS override the values of previous elements.
  1603. This takes into account some special considerations for certain
  1604. parameters when merging lists."
  1605. (let ((results-exclusive-groups
  1606. '(("file" "list" "vector" "table" "scalar" "verbatim" "raw" "org"
  1607. "html" "latex" "code" "pp" "wrap")
  1608. ("replace" "silent" "append" "prepend")
  1609. ("output" "value")))
  1610. (exports-exclusive-groups
  1611. '(("code" "results" "both" "none")))
  1612. (variable-index 0)
  1613. params results exports tangle noweb cache vars shebang comments padline)
  1614. (flet ((e-merge (exclusive-groups &rest result-params)
  1615. ;; maintain exclusivity of mutually exclusive parameters
  1616. (let (output)
  1617. (mapc (lambda (new-params)
  1618. (mapc (lambda (new-param)
  1619. (mapc (lambda (exclusive-group)
  1620. (when (member new-param exclusive-group)
  1621. (mapcar (lambda (excluded-param)
  1622. (setq output
  1623. (delete
  1624. excluded-param
  1625. output)))
  1626. exclusive-group)))
  1627. exclusive-groups)
  1628. (setq output (org-uniquify
  1629. (cons new-param output))))
  1630. new-params))
  1631. result-params)
  1632. output)))
  1633. (mapc
  1634. (lambda (plist)
  1635. (mapc
  1636. (lambda (pair)
  1637. (case (car pair)
  1638. (:var
  1639. (let ((name (if (listp (cdr pair))
  1640. (cadr pair)
  1641. (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1642. (cdr pair))
  1643. (intern (match-string 1 (cdr pair)))))))
  1644. (if name
  1645. (setq vars
  1646. (append
  1647. (if (member name (mapcar #'car vars))
  1648. (delq nil
  1649. (mapcar
  1650. (lambda (p)
  1651. (unless (equal (car p) name) p))
  1652. vars))
  1653. vars)
  1654. (list (cons name pair))))
  1655. ;; if no name is given, then assign to variables in order
  1656. (prog1 (setf (cddr (nth variable-index vars))
  1657. (concat (symbol-name
  1658. (car (nth variable-index vars)))
  1659. "=" (cdr pair)))
  1660. (incf variable-index)))))
  1661. (:results
  1662. (setq results (e-merge results-exclusive-groups
  1663. results
  1664. (split-string
  1665. (let ((r (cdr pair)))
  1666. (if (stringp r) r (eval r)))))))
  1667. (:file
  1668. (when (cdr pair)
  1669. (setq results (e-merge results-exclusive-groups
  1670. results '("file")))
  1671. (unless (or (member "both" exports)
  1672. (member "none" exports)
  1673. (member "code" exports))
  1674. (setq exports (e-merge exports-exclusive-groups
  1675. exports '("results"))))
  1676. (setq params (cons pair (assq-delete-all (car pair) params)))))
  1677. (:exports
  1678. (setq exports (e-merge exports-exclusive-groups
  1679. exports (split-string (cdr pair)))))
  1680. (:tangle ;; take the latest -- always overwrite
  1681. (setq tangle (or (list (cdr pair)) tangle)))
  1682. (:noweb
  1683. (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
  1684. (split-string (or (cdr pair) "")))))
  1685. (:cache
  1686. (setq cache (e-merge '(("yes" "no")) cache
  1687. (split-string (or (cdr pair) "")))))
  1688. (:padline
  1689. (setq padline (e-merge '(("yes" "no")) padline
  1690. (split-string (or (cdr pair) "")))))
  1691. (:shebang ;; take the latest -- always overwrite
  1692. (setq shebang (or (list (cdr pair)) shebang)))
  1693. (:comments
  1694. (setq comments (e-merge '(("yes" "no")) comments
  1695. (split-string (or (cdr pair) "")))))
  1696. (t ;; replace: this covers e.g. :session
  1697. (setq params (cons pair (assq-delete-all (car pair) params))))))
  1698. plist))
  1699. plists))
  1700. (setq vars (reverse vars))
  1701. (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
  1702. (mapc
  1703. (lambda (hd)
  1704. (let ((key (intern (concat ":" (symbol-name hd))))
  1705. (val (eval hd)))
  1706. (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
  1707. '(results exports tangle noweb padline cache shebang comments))
  1708. params))
  1709. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1710. "Expand Noweb references in the body of the current source code block.
  1711. For example the following reference would be replaced with the
  1712. body of the source-code block named 'example-block'.
  1713. <<example-block>>
  1714. Note that any text preceding the <<foo>> construct on a line will
  1715. be interposed between the lines of the replacement text. So for
  1716. example if <<foo>> is placed behind a comment, then the entire
  1717. replacement text will also be commented.
  1718. This function must be called from inside of the buffer containing
  1719. the source-code block which holds BODY.
  1720. In addition the following syntax can be used to insert the
  1721. results of evaluating the source-code block named 'example-block'.
  1722. <<example-block()>>
  1723. Any optional arguments can be passed to example-block by placing
  1724. the arguments inside the parenthesis following the convention
  1725. defined by `org-babel-lob'. For example
  1726. <<example-block(a=9)>>
  1727. would set the value of argument \"a\" equal to \"9\". Note that
  1728. these arguments are not evaluated in the current source-code
  1729. block but are passed literally to the \"example-block\"."
  1730. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1731. (info (or info (org-babel-get-src-block-info)))
  1732. (lang (nth 0 info))
  1733. (body (nth 1 info))
  1734. (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
  1735. (new-body "") index source-name evaluate prefix blocks-in-buffer)
  1736. (flet ((nb-add (text) (setq new-body (concat new-body text)))
  1737. (c-wrap (text)
  1738. (with-temp-buffer
  1739. (funcall (intern (concat lang "-mode")))
  1740. (comment-region (point) (progn (insert text) (point)))
  1741. (org-babel-trim (buffer-string))))
  1742. (blocks () ;; return the info lists of all blocks in this buffer
  1743. (let (infos)
  1744. (save-restriction
  1745. (widen)
  1746. (org-babel-map-src-blocks nil
  1747. (setq infos (cons (org-babel-get-src-block-info 'light)
  1748. infos))))
  1749. (reverse infos))))
  1750. (with-temp-buffer
  1751. (insert body) (goto-char (point-min))
  1752. (setq index (point))
  1753. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1754. (save-match-data (setf source-name (match-string 1)))
  1755. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1756. (save-match-data
  1757. (setq prefix
  1758. (buffer-substring (match-beginning 0)
  1759. (save-excursion
  1760. (beginning-of-line 1) (point)))))
  1761. ;; add interval to new-body (removing noweb reference)
  1762. (goto-char (match-beginning 0))
  1763. (nb-add (buffer-substring index (point)))
  1764. (goto-char (match-end 0))
  1765. (setq index (point))
  1766. (nb-add
  1767. (with-current-buffer parent-buffer
  1768. (mapconcat ;; interpose PREFIX between every line
  1769. #'identity
  1770. (split-string
  1771. (if evaluate
  1772. (let ((raw (org-babel-ref-resolve source-name)))
  1773. (if (stringp raw) raw (format "%S" raw)))
  1774. (or
  1775. ;; retrieve from the library of babel
  1776. (nth 2 (assoc (intern source-name)
  1777. org-babel-library-of-babel))
  1778. ;; return the contents of headlines literally
  1779. (save-excursion
  1780. (when (org-babel-ref-goto-headline-id source-name)
  1781. (org-babel-ref-headline-body)))
  1782. ;; find the expansion of reference in this buffer
  1783. (mapconcat
  1784. (lambda (i)
  1785. (when (string= source-name
  1786. (or (cdr (assoc :noweb-ref (nth 2 i)))
  1787. (nth 4 i)))
  1788. (let ((body (org-babel-expand-noweb-references i)))
  1789. (if comment
  1790. ((lambda (cs)
  1791. (concat (c-wrap (car cs)) "\n"
  1792. body "\n" (c-wrap (cadr cs))))
  1793. (org-babel-tangle-comment-links i))
  1794. body))))
  1795. (or blocks-in-buffer
  1796. (setq blocks-in-buffer (blocks)))
  1797. "")
  1798. ;; possibly raise an error if named block doesn't exist
  1799. (if (member lang org-babel-noweb-error-langs)
  1800. (error "%s" (concat
  1801. "<<" source-name ">> "
  1802. "could not be resolved (see "
  1803. "`org-babel-noweb-error-langs')"))
  1804. "")))
  1805. "[\n\r]") (concat "\n" prefix)))))
  1806. (nb-add (buffer-substring index (point-max)))))
  1807. new-body))
  1808. (defun org-babel-clean-text-properties (text)
  1809. "Strip all properties from text return."
  1810. (when text
  1811. (set-text-properties 0 (length text) nil text) text))
  1812. (defun org-babel-strip-protective-commas (body)
  1813. "Strip protective commas from bodies of source blocks."
  1814. (when body
  1815. (replace-regexp-in-string "^,#" "#" body)))
  1816. (defun org-babel-script-escape (str &optional force)
  1817. "Safely convert tables into elisp lists."
  1818. (let (in-single in-double out)
  1819. ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
  1820. (if (or force
  1821. (and (stringp str)
  1822. (> (length str) 2)
  1823. (or (and (string-equal "[" (substring str 0 1))
  1824. (string-equal "]" (substring str -1)))
  1825. (and (string-equal "{" (substring str 0 1))
  1826. (string-equal "}" (substring str -1)))
  1827. (and (string-equal "(" (substring str 0 1))
  1828. (string-equal ")" (substring str -1))))))
  1829. (org-babel-read
  1830. (concat
  1831. "'"
  1832. (progn
  1833. (mapc
  1834. (lambda (ch)
  1835. (setq
  1836. out
  1837. (case ch
  1838. (91 (if (or in-double in-single) ; [
  1839. (cons 91 out)
  1840. (cons 40 out)))
  1841. (93 (if (or in-double in-single) ; ]
  1842. (cons 93 out)
  1843. (cons 41 out)))
  1844. (123 (if (or in-double in-single) ; {
  1845. (cons 123 out)
  1846. (cons 40 out)))
  1847. (125 (if (or in-double in-single) ; }
  1848. (cons 125 out)
  1849. (cons 41 out)))
  1850. (44 (if (or in-double in-single) ; ,
  1851. (cons 44 out) (cons 32 out)))
  1852. (39 (if in-double ; '
  1853. (cons 39 out)
  1854. (setq in-single (not in-single)) (cons 34 out)))
  1855. (34 (if in-single ; "
  1856. (append (list 34 32) out)
  1857. (setq in-double (not in-double)) (cons 34 out)))
  1858. (t (cons ch out)))))
  1859. (string-to-list str))
  1860. (apply #'string (reverse out)))))
  1861. str))))
  1862. (defun org-babel-read (cell &optional inhibit-lisp-eval)
  1863. "Convert the string value of CELL to a number if appropriate.
  1864. Otherwise if cell looks like lisp (meaning it starts with a
  1865. \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
  1866. return it unmodified as a string. Optional argument NO-LISP-EVAL
  1867. inhibits lisp evaluation for situations in which is it not
  1868. appropriate."
  1869. (if (and (stringp cell) (not (equal cell "")))
  1870. (or (org-babel-number-p cell)
  1871. (if (and (not inhibit-lisp-eval)
  1872. (member (substring cell 0 1) '("(" "'" "`" "[")))
  1873. (eval (read cell))
  1874. (if (string= (substring cell 0 1) "\"")
  1875. (read cell)
  1876. (progn (set-text-properties 0 (length cell) nil cell) cell))))
  1877. cell))
  1878. (defun org-babel-number-p (string)
  1879. "If STRING represents a number return it's value."
  1880. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1881. (= (length (substring string (match-beginning 0)
  1882. (match-end 0)))
  1883. (length string)))
  1884. (string-to-number string)))
  1885. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1886. "Read the results located at FILE-NAME into an elisp table.
  1887. If the table is trivial, then return it as a scalar."
  1888. (let (result)
  1889. (save-window-excursion
  1890. (with-temp-buffer
  1891. (condition-case nil
  1892. (progn
  1893. (org-table-import file-name separator)
  1894. (delete-file file-name)
  1895. (setq result (mapcar (lambda (row)
  1896. (mapcar #'org-babel-string-read row))
  1897. (org-table-to-lisp))))
  1898. (error nil)))
  1899. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1900. (if (consp (car result))
  1901. (if (null (cdr (car result)))
  1902. (caar result)
  1903. result)
  1904. (car result))
  1905. result))))
  1906. (defun org-babel-string-read (cell)
  1907. "Strip nested \"s from around strings."
  1908. (org-babel-read (or (and (stringp cell)
  1909. (string-match "\\\"\\(.+\\)\\\"" cell)
  1910. (match-string 1 cell))
  1911. cell)))
  1912. (defun org-babel-reverse-string (string)
  1913. "Return the reverse of STRING."
  1914. (apply 'string (reverse (string-to-list string))))
  1915. (defun org-babel-chomp (string &optional regexp)
  1916. "Strip trailing spaces and carriage returns from STRING.
  1917. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1918. overwritten by specifying a regexp as a second argument."
  1919. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1920. (while (and (> (length string) 0)
  1921. (string-match regexp (substring string -1)))
  1922. (setq string (substring string 0 -1)))
  1923. string))
  1924. (defun org-babel-trim (string &optional regexp)
  1925. "Strip leading and trailing spaces and carriage returns from STRING.
  1926. Like `org-babel-chomp' only it runs on both the front and back
  1927. of the string."
  1928. (org-babel-chomp (org-babel-reverse-string
  1929. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1930. regexp))
  1931. (defvar org-babel-org-babel-call-process-region-original nil)
  1932. (defun org-babel-tramp-handle-call-process-region
  1933. (start end program &optional delete buffer display &rest args)
  1934. "Use tramp to handle call-process-region.
  1935. Fixes a bug in `tramp-handle-call-process-region'."
  1936. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1937. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1938. (write-region start end tmpfile)
  1939. (when delete (delete-region start end))
  1940. (unwind-protect
  1941. ;; (apply 'call-process program tmpfile buffer display args)
  1942. ;; bug in tramp
  1943. (apply 'process-file program tmpfile buffer display args)
  1944. (delete-file tmpfile)))
  1945. ;; org-babel-call-process-region-original is the original emacs
  1946. ;; definition. It is in scope from the let binding in
  1947. ;; org-babel-execute-src-block
  1948. (apply org-babel-call-process-region-original
  1949. start end program delete buffer display args)))
  1950. (defun org-babel-local-file-name (file)
  1951. "Return the local name component of FILE."
  1952. (if (file-remote-p file)
  1953. (let (localname)
  1954. (with-parsed-tramp-file-name file nil
  1955. localname))
  1956. file))
  1957. (defun org-babel-process-file-name (name &optional no-quote-p)
  1958. "Prepare NAME to be used in an external process.
  1959. If NAME specifies a remote location, the remote portion of the
  1960. name is removed, since in that case the process will be executing
  1961. remotely. The file name is then processed by
  1962. `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
  1963. the file name is additionally processed by
  1964. `shell-quote-argument'"
  1965. ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
  1966. (expand-file-name (org-babel-local-file-name name))))
  1967. (defvar org-babel-temporary-directory)
  1968. (unless (or noninteractive (boundp 'org-babel-temporary-directory))
  1969. (defvar org-babel-temporary-directory
  1970. (or (and (boundp 'org-babel-temporary-directory)
  1971. (file-exists-p org-babel-temporary-directory)
  1972. org-babel-temporary-directory)
  1973. (make-temp-file "babel-" t))
  1974. "Directory to hold temporary files created to execute code blocks.
  1975. Used by `org-babel-temp-file'. This directory will be removed on
  1976. Emacs shutdown."))
  1977. (defun org-babel-temp-file (prefix &optional suffix)
  1978. "Create a temporary file in the `org-babel-temporary-directory'.
  1979. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1980. value of `temporary-file-directory' temporarily set to the value
  1981. of `org-babel-temporary-directory'."
  1982. (if (file-remote-p default-directory)
  1983. (make-temp-file
  1984. (concat (file-remote-p default-directory)
  1985. (expand-file-name
  1986. prefix temporary-file-directory)
  1987. nil suffix))
  1988. (let ((temporary-file-directory
  1989. (or (and (boundp 'org-babel-temporary-directory)
  1990. (file-exists-p org-babel-temporary-directory)
  1991. org-babel-temporary-directory)
  1992. temporary-file-directory)))
  1993. (make-temp-file prefix nil suffix))))
  1994. (defun org-babel-remove-temporary-directory ()
  1995. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1996. (when (and (boundp 'org-babel-temporary-directory)
  1997. (file-exists-p org-babel-temporary-directory))
  1998. ;; taken from `delete-directory' in files.el
  1999. (condition-case nil
  2000. (progn
  2001. (mapc (lambda (file)
  2002. ;; This test is equivalent to
  2003. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  2004. ;; but more efficient
  2005. (if (eq t (car (file-attributes file)))
  2006. (delete-directory file)
  2007. (delete-file file)))
  2008. ;; We do not want to delete "." and "..".
  2009. (directory-files org-babel-temporary-directory 'full
  2010. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  2011. (delete-directory org-babel-temporary-directory))
  2012. (error
  2013. (message "Failed to remove temporary Org-babel directory %s"
  2014. (if (boundp 'org-babel-temporary-directory)
  2015. org-babel-temporary-directory
  2016. "[directory not defined]"))))))
  2017. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  2018. (provide 'ob)
  2019. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  2020. ;;; ob.el ends here