ob.el 71 KB

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