ob.el 84 KB

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