ob.el 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  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 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
  541. (nth 2 info) ":")
  542. (nth 1 info)))))
  543. (when (interactive-p) (message hash))
  544. hash))
  545. (defun org-babel-result-hash (&optional info)
  546. "Return the in-buffer hash associated with INFO."
  547. (org-babel-where-is-src-block-result nil info)
  548. (org-babel-clean-text-properties (match-string 3)))
  549. (defun org-babel-hide-hash ()
  550. "Hide the hash in the current results line.
  551. Only the initial `org-babel-hash-show' characters of the hash
  552. will remain visible."
  553. (add-to-invisibility-spec '(org-babel-hide-hash . t))
  554. (save-excursion
  555. (when (and (re-search-forward org-babel-result-regexp nil t)
  556. (match-string 3))
  557. (let* ((start (match-beginning 3))
  558. (hide-start (+ org-babel-hash-show start))
  559. (end (match-end 3))
  560. (hash (match-string 3))
  561. ov1 ov2)
  562. (setq ov1 (make-overlay start hide-start))
  563. (setq ov2 (make-overlay hide-start end))
  564. (overlay-put ov2 'invisible 'org-babel-hide-hash)
  565. (overlay-put ov1 'babel-hash hash)))))
  566. (defun org-babel-hide-all-hashes ()
  567. "Hide the hash in the current buffer.
  568. Only the initial `org-babel-hash-show' characters of each hash
  569. will remain visible. This function should be called as part of
  570. the `org-mode-hook'."
  571. (save-excursion
  572. (while (re-search-forward org-babel-result-regexp nil t)
  573. (goto-char (match-beginning 0))
  574. (org-babel-hide-hash)
  575. (goto-char (match-end 0)))))
  576. (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
  577. (defun org-babel-hash-at-point (&optional point)
  578. "Return the value of the hash at POINT.
  579. The hash is also added as the last element of the kill ring.
  580. This can be called with C-c C-c."
  581. (interactive)
  582. (let ((hash (car (delq nil (mapcar
  583. (lambda (ol) (overlay-get ol 'babel-hash))
  584. (overlays-at (or point (point))))))))
  585. (when hash (kill-new hash) (message hash))))
  586. (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
  587. (defun org-babel-result-hide-spec ()
  588. "Hide portions of results lines.
  589. Add `org-babel-hide-result' as an invisibility spec for hiding
  590. portions of results lines."
  591. (add-to-invisibility-spec '(org-babel-hide-result . t)))
  592. (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
  593. (defvar org-babel-hide-result-overlays nil
  594. "Overlays hiding results.")
  595. (defun org-babel-result-hide-all ()
  596. "Fold all results in the current buffer."
  597. (interactive)
  598. (org-babel-show-result-all)
  599. (save-excursion
  600. (while (re-search-forward org-babel-result-regexp nil t)
  601. (save-excursion (goto-char (match-beginning 0))
  602. (org-babel-hide-result-toggle-maybe)))))
  603. (defun org-babel-show-result-all ()
  604. "Unfold all results in the current buffer."
  605. (mapc 'delete-overlay org-babel-hide-result-overlays)
  606. (setq org-babel-hide-result-overlays nil))
  607. ;;;###autoload
  608. (defun org-babel-hide-result-toggle-maybe ()
  609. "Toggle visibility of result at point."
  610. (interactive)
  611. (let ((case-fold-search t))
  612. (if (save-excursion
  613. (beginning-of-line 1)
  614. (looking-at org-babel-result-regexp))
  615. (progn (org-babel-hide-result-toggle)
  616. t) ;; to signal that we took action
  617. nil))) ;; to signal that we did not
  618. (defun org-babel-hide-result-toggle (&optional force)
  619. "Toggle the visibility of the current result."
  620. (interactive)
  621. (save-excursion
  622. (beginning-of-line)
  623. (if (re-search-forward org-babel-result-regexp nil t)
  624. (let ((start (progn (beginning-of-line 2) (- (point) 1)))
  625. (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
  626. ov)
  627. (if (memq t (mapcar (lambda (overlay)
  628. (eq (overlay-get overlay 'invisible)
  629. 'org-babel-hide-result))
  630. (overlays-at start)))
  631. (if (or (not force) (eq force 'off))
  632. (mapc (lambda (ov)
  633. (when (member ov org-babel-hide-result-overlays)
  634. (setq org-babel-hide-result-overlays
  635. (delq ov org-babel-hide-result-overlays)))
  636. (when (eq (overlay-get ov 'invisible)
  637. 'org-babel-hide-result)
  638. (delete-overlay ov)))
  639. (overlays-at start)))
  640. (setq ov (make-overlay start end))
  641. (overlay-put ov 'invisible 'org-babel-hide-result)
  642. ;; make the block accessible to isearch
  643. (overlay-put
  644. ov 'isearch-open-invisible
  645. (lambda (ov)
  646. (when (member ov org-babel-hide-result-overlays)
  647. (setq org-babel-hide-result-overlays
  648. (delq ov org-babel-hide-result-overlays)))
  649. (when (eq (overlay-get ov 'invisible)
  650. 'org-babel-hide-result)
  651. (delete-overlay ov))))
  652. (push ov org-babel-hide-result-overlays)))
  653. (error "Not looking at a result line"))))
  654. ;; org-tab-after-check-for-cycling-hook
  655. (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
  656. ;; Remove overlays when changing major mode
  657. (add-hook 'org-mode-hook
  658. (lambda () (org-add-hook 'change-major-mode-hook
  659. 'org-babel-show-result-all 'append 'local)))
  660. (defmacro org-babel-map-src-blocks (file &rest body)
  661. "Evaluate BODY forms on each source-block in FILE.
  662. If FILE is nil evaluate BODY forms on source blocks in current
  663. buffer. During evaluation of BODY the following local variables
  664. are set relative to the currently matched code block.
  665. full-block ------- string holding the entirety of the code block
  666. beg-block -------- point at the beginning of the code block
  667. end-block -------- point at the end of the matched code block
  668. lang ------------- string holding the language of the code block
  669. beg-lang --------- point at the beginning of the lang
  670. end-lang --------- point at the end of the lang
  671. switches --------- string holding the switches
  672. beg-switches ----- point at the beginning of the switches
  673. end-switches ----- point at the end of the switches
  674. header-args ------ string holding the header-args
  675. beg-header-args -- point at the beginning of the header-args
  676. end-header-args -- point at the end of the header-args
  677. body ------------- string holding the body of the code block
  678. beg-body --------- point at the beginning of the body
  679. end-body --------- point at the end of the body"
  680. (declare (indent 1))
  681. `(let ((visited-p (or (null ,file)
  682. (get-file-buffer (expand-file-name ,file))))
  683. (point (point)) to-be-removed)
  684. (save-window-excursion
  685. (when ,file (find-file ,file))
  686. (setq to-be-removed (current-buffer))
  687. (goto-char (point-min))
  688. (while (re-search-forward org-babel-src-block-regexp nil t)
  689. (goto-char (match-beginning 0))
  690. (let ((full-block (match-string 0))
  691. (beg-block (match-beginning 0))
  692. (end-block (match-beginning 0))
  693. (lang (match-string 2))
  694. (beg-lang (match-beginning 2))
  695. (end-lang (match-end 2))
  696. (switches (match-string 3))
  697. (beg-switches (match-beginning 3))
  698. (end-switches (match-end 3))
  699. (header-args (match-string 4))
  700. (beg-header-args (match-beginning 4))
  701. (end-header-args (match-end 4))
  702. (body (match-string 5))
  703. (beg-body (match-beginning 5))
  704. (end-body (match-end 5)))
  705. (save-match-data ,@body))
  706. (goto-char (match-end 0))))
  707. (unless visited-p
  708. (kill-buffer to-be-removed))
  709. (goto-char point)))
  710. (defvar org-file-properties)
  711. (defun org-babel-params-from-properties (&optional lang)
  712. "Retrieve parameters specified as properties.
  713. Return an association list of any source block params which
  714. may be specified in the properties of the current outline entry."
  715. (save-match-data
  716. (let (val sym)
  717. (delq nil
  718. (mapcar
  719. (lambda (header-arg)
  720. (and (setq val
  721. (or (condition-case nil
  722. (org-entry-get (point) header-arg t)
  723. (error nil))
  724. (cdr (assoc header-arg org-file-properties))))
  725. (cons (intern (concat ":" header-arg)) val)))
  726. (mapcar
  727. 'symbol-name
  728. (append
  729. org-babel-header-arg-names
  730. (progn
  731. (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
  732. (and (boundp sym) (eval sym))))))))))
  733. (defun org-babel-params-from-buffer ()
  734. "Retrieve per-buffer parameters.
  735. Return an association list of any source block params which
  736. may be specified at the top of the current buffer."
  737. (or org-babel-current-buffer-properties
  738. (setq org-babel-current-buffer-properties
  739. (save-match-data
  740. (save-excursion
  741. (save-restriction
  742. (widen)
  743. (goto-char (point-min))
  744. (when (re-search-forward
  745. (org-make-options-regexp (list "BABEL")) nil t)
  746. (org-babel-parse-header-arguments
  747. (org-match-string-no-properties 2)))))))))
  748. (defvar org-src-preserve-indentation)
  749. (defun org-babel-parse-src-block-match ()
  750. "Parse the results from a match of the `org-babel-src-block-regexp'."
  751. (let* ((block-indentation (length (match-string 1)))
  752. (lang (org-babel-clean-text-properties (match-string 2)))
  753. (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
  754. (switches (match-string 3))
  755. (body (org-babel-clean-text-properties (match-string 5)))
  756. (preserve-indentation (or org-src-preserve-indentation
  757. (string-match "-i\\>" switches))))
  758. (list lang
  759. ;; get block body less properties, protective commas, and indentation
  760. (with-temp-buffer
  761. (save-match-data
  762. (insert (org-babel-strip-protective-commas body))
  763. (unless preserve-indentation (org-do-remove-indentation))
  764. (buffer-string)))
  765. (org-babel-merge-params
  766. org-babel-default-header-args
  767. (org-babel-params-from-buffer)
  768. (org-babel-params-from-properties lang)
  769. (if (boundp lang-headers) (eval lang-headers) nil)
  770. (org-babel-parse-header-arguments
  771. (org-babel-clean-text-properties (or (match-string 4) ""))))
  772. switches
  773. block-indentation)))
  774. (defun org-babel-parse-inline-src-block-match ()
  775. "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
  776. (let* ((lang (org-babel-clean-text-properties (match-string 2)))
  777. (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
  778. (list lang
  779. (org-babel-strip-protective-commas
  780. (org-babel-clean-text-properties (match-string 5)))
  781. (org-babel-merge-params
  782. org-babel-default-inline-header-args
  783. (org-babel-params-from-buffer)
  784. (org-babel-params-from-properties lang)
  785. (if (boundp lang-headers) (eval lang-headers) nil)
  786. (org-babel-parse-header-arguments
  787. (org-babel-clean-text-properties (or (match-string 4) "")))))))
  788. (defun org-babel-parse-header-arguments (arg-string)
  789. "Parse a string of header arguments returning an alist."
  790. (if (> (length arg-string) 0)
  791. (delq nil
  792. (mapcar
  793. (lambda (arg)
  794. (if (string-match
  795. "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
  796. arg)
  797. (cons (intern (concat ":" (match-string 1 arg)))
  798. (let ((raw (org-babel-chomp (match-string 2 arg))))
  799. (if (org-babel-number-p raw)
  800. raw (org-babel-read raw))))
  801. (cons (intern (concat ":" arg)) nil)))
  802. (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
  803. (defun org-babel-process-params (params)
  804. "Parse params and resolve references.
  805. Return a list (session vars result-params result-type colnames rownames)."
  806. (let* ((session (cdr (assoc :session params)))
  807. (vars-and-names (org-babel-disassemble-tables
  808. (org-babel-ref-variables params)
  809. (cdr (assoc :hlines params))
  810. (cdr (assoc :colnames params))
  811. (cdr (assoc :rownames params))))
  812. (vars (car vars-and-names))
  813. (colnames (cadr vars-and-names))
  814. (rownames (caddr vars-and-names))
  815. (result-params (split-string (or (cdr (assoc :results params)) "")))
  816. (result-type (cond ((member "output" result-params) 'output)
  817. ((member "value" result-params) 'value)
  818. (t 'value))))
  819. (list session vars result-params result-type colnames rownames)))
  820. ;; row and column names
  821. (defun org-babel-del-hlines (table)
  822. "Remove all 'hlines from TABLE."
  823. (remove 'hline table))
  824. (defun org-babel-get-colnames (table)
  825. "Return the column names of TABLE.
  826. Return a cons cell, the `car' of which contains the TABLE less
  827. colnames, and the `cdr' of which contains a list of the column
  828. names."
  829. (if (equal 'hline (nth 1 table))
  830. (cons (cddr table) (car table))
  831. (cons (cdr table) (car table))))
  832. (defun org-babel-get-rownames (table)
  833. "Return the row 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. Note: this function removes any hlines in TABLE."
  837. (flet ((trans (table) (apply #'mapcar* #'list table)))
  838. (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
  839. (table (trans (mapcar (lambda (row)
  840. (if (not (equal row 'hline))
  841. row
  842. (setq row '())
  843. (dotimes (n width) (setq row (cons 'hline row)))
  844. row))
  845. table))))
  846. (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
  847. (trans (cdr table)))
  848. (remove 'hline (car table))))))
  849. (defun org-babel-put-colnames (table colnames)
  850. "Add COLNAMES to TABLE if they exist."
  851. (if colnames (apply 'list colnames 'hline table) table))
  852. (defun org-babel-put-rownames (table rownames)
  853. "Add ROWNAMES to TABLE if they exist."
  854. (if rownames
  855. (mapcar (lambda (row)
  856. (if (listp row)
  857. (cons (or (pop rownames) "") row)
  858. row)) table)
  859. table))
  860. (defun org-babel-pick-name (names selector)
  861. "Select one out of an alist of row or column names.
  862. SELECTOR can be either a list of names in which case those names
  863. will be returned directly, or an index into the list NAMES in
  864. which case the indexed names will be return."
  865. (if (listp selector)
  866. selector
  867. (when names
  868. (if (and selector (symbolp selector) (not (equal t selector)))
  869. (cdr (assoc selector names))
  870. (if (integerp selector)
  871. (nth (- selector 1) names)
  872. (cdr (car (last names))))))))
  873. (defun org-babel-disassemble-tables (vars hlines colnames rownames)
  874. "Parse tables for further processing.
  875. Process the variables in VARS according to the HLINES,
  876. ROWNAMES and COLNAMES header arguments. Return a list consisting
  877. of the vars, cnames and rnames."
  878. (let (cnames rnames)
  879. (list
  880. (mapcar
  881. (lambda (var)
  882. (when (listp (cdr var))
  883. (when (and (not (equal colnames "no"))
  884. (or colnames (and (equal (nth 1 (cdr var)) 'hline)
  885. (not (member 'hline (cddr (cdr var)))))))
  886. (let ((both (org-babel-get-colnames (cdr var))))
  887. (setq cnames (cons (cons (car var) (cdr both))
  888. cnames))
  889. (setq var (cons (car var) (car both)))))
  890. (when (and rownames (not (equal rownames "no")))
  891. (let ((both (org-babel-get-rownames (cdr var))))
  892. (setq rnames (cons (cons (car var) (cdr both))
  893. rnames))
  894. (setq var (cons (car var) (car both)))))
  895. (when (and hlines (not (equal hlines "yes")))
  896. (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
  897. var)
  898. vars)
  899. cnames rnames)))
  900. (defun org-babel-reassemble-table (table colnames rownames)
  901. "Add column and row names to a table.
  902. Given a TABLE and set of COLNAMES and ROWNAMES add the names
  903. to the table for reinsertion to org-mode."
  904. (if (listp table)
  905. ((lambda (table)
  906. (if (and colnames (listp (car table)) (= (length (car table))
  907. (length colnames)))
  908. (org-babel-put-colnames table colnames) table))
  909. (if (and rownames (= (length table) (length rownames)))
  910. (org-babel-put-rownames table rownames) table))
  911. table))
  912. (defun org-babel-where-is-src-block-head ()
  913. "Find where the current source block begins.
  914. Return the point at the beginning of the current source
  915. block. Specifically at the beginning of the #+BEGIN_SRC line.
  916. If the point is not on a source block then return nil."
  917. (let ((initial (point)) top bottom)
  918. (or
  919. (save-excursion ;; on a source name line
  920. (beginning-of-line 1)
  921. (and (looking-at org-babel-src-name-regexp) (forward-line 1)
  922. (looking-at org-babel-src-block-regexp)
  923. (point)))
  924. (save-excursion ;; on a #+begin_src line
  925. (beginning-of-line 1)
  926. (and (looking-at org-babel-src-block-regexp)
  927. (point)))
  928. (save-excursion ;; inside a src block
  929. (and
  930. (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
  931. (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
  932. (< top initial) (< initial bottom)
  933. (progn (goto-char top) (beginning-of-line 1)
  934. (looking-at org-babel-src-block-regexp))
  935. (point))))))
  936. ;;;###autoload
  937. (defun org-babel-goto-src-block-head ()
  938. "Go to the beginning of the current code block."
  939. (interactive)
  940. ((lambda (head)
  941. (if head (goto-char head) (error "not currently in a code block")))
  942. (org-babel-where-is-src-block-head)))
  943. ;;;###autoload
  944. (defun org-babel-goto-named-src-block (name)
  945. "Go to a named source-code block."
  946. (interactive
  947. (let ((completion-ignore-case t))
  948. (list (org-icompleting-read "source-block name: "
  949. (org-babel-src-block-names) nil t))))
  950. (let ((point (org-babel-find-named-block name)))
  951. (if point
  952. ;; taken from `org-open-at-point'
  953. (progn (goto-char point) (org-show-context))
  954. (message "source-code block '%s' not found in this buffer" name))))
  955. (defun org-babel-find-named-block (name)
  956. "Find a named source-code block.
  957. Return the location of the source block identified by source
  958. NAME, or nil if no such block exists. Set match data according to
  959. org-babel-named-src-block-regexp."
  960. (save-excursion
  961. (let ((case-fold-search t)
  962. (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
  963. (goto-char (point-min))
  964. (when (or (re-search-forward regexp nil t)
  965. (re-search-backward regexp nil t))
  966. (match-beginning 0)))))
  967. (defun org-babel-src-block-names (&optional file)
  968. "Returns the names of source blocks in FILE or the current buffer."
  969. (save-excursion
  970. (when file (find-file file)) (goto-char (point-min))
  971. (let (names)
  972. (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
  973. (setq names (cons (org-babel-clean-text-properties (match-string 2))
  974. names)))
  975. names)))
  976. ;;;###autoload
  977. (defun org-babel-goto-named-result (name)
  978. "Go to a named result."
  979. (interactive
  980. (let ((completion-ignore-case t))
  981. (list (org-icompleting-read "source-block name: "
  982. (org-babel-result-names) nil t))))
  983. (let ((point (org-babel-find-named-result name)))
  984. (if point
  985. ;; taken from `org-open-at-point'
  986. (progn (goto-char point) (org-show-context))
  987. (message "result '%s' not found in this buffer" name))))
  988. (defun org-babel-find-named-result (name)
  989. "Find a named result.
  990. Return the location of the result named NAME in the current
  991. buffer or nil if no such result exists."
  992. (save-excursion
  993. (goto-char (point-min))
  994. (when (re-search-forward
  995. (concat org-babel-result-regexp
  996. "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
  997. (beginning-of-line 0) (point))))
  998. (defun org-babel-result-names (&optional file)
  999. "Returns the names of results in FILE or the current buffer."
  1000. (save-excursion
  1001. (when file (find-file file)) (goto-char (point-min))
  1002. (let (names)
  1003. (while (re-search-forward org-babel-result-w-name-regexp nil t)
  1004. (setq names (cons (org-babel-clean-text-properties (match-string 4))
  1005. names)))
  1006. names)))
  1007. ;;;###autoload
  1008. (defun org-babel-next-src-block (&optional arg)
  1009. "Jump to the next source block.
  1010. With optional prefix argument ARG, jump forward ARG many source blocks."
  1011. (interactive "P")
  1012. (when (looking-at org-babel-src-block-regexp) (forward-char 1))
  1013. (condition-case nil
  1014. (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
  1015. (error (error "No further code blocks")))
  1016. (goto-char (match-beginning 0)) (org-show-context))
  1017. ;;;###autoload
  1018. (defun org-babel-previous-src-block (&optional arg)
  1019. "Jump to the previous source block.
  1020. With optional prefix argument ARG, jump backward ARG many source blocks."
  1021. (interactive "P")
  1022. (condition-case nil
  1023. (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
  1024. (error (error "No previous code blocks")))
  1025. (goto-char (match-beginning 0)) (org-show-context))
  1026. (defvar org-babel-lob-one-liner-regexp)
  1027. (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
  1028. "Find where the current source block results begin.
  1029. Return the point at the beginning of the result of the current
  1030. source block. Specifically at the beginning of the results line.
  1031. If no result exists for this block then create a results line
  1032. following the source block."
  1033. (save-excursion
  1034. (let* ((on-lob-line (progn (beginning-of-line 1)
  1035. (looking-at org-babel-lob-one-liner-regexp)))
  1036. (name (if on-lob-line
  1037. (nth 0 (org-babel-lob-get-info))
  1038. (nth 4 (or info (org-babel-get-src-block-info)))))
  1039. (head (unless on-lob-line (org-babel-where-is-src-block-head)))
  1040. found beg end)
  1041. (when head (goto-char head))
  1042. (setq
  1043. found ;; was there a result (before we potentially insert one)
  1044. (or
  1045. (and
  1046. ;; named results:
  1047. ;; - return t if it is found, else return nil
  1048. ;; - if it does not need to be rebuilt, then don't set end
  1049. ;; - if it does need to be rebuilt then do set end
  1050. name (setq beg (org-babel-find-named-result name))
  1051. (prog1 beg
  1052. (when (and hash (not (string= hash (match-string 3))))
  1053. (goto-char beg) (setq end beg) ;; beginning of result
  1054. (forward-line 1)
  1055. (delete-region end (org-babel-result-end)) nil)))
  1056. (and
  1057. ;; unnamed results:
  1058. ;; - return t if it is found, else return nil
  1059. ;; - if it is found, and the hash doesn't match, delete and set end
  1060. (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
  1061. (progn (end-of-line 1)
  1062. (if (eobp) (insert "\n") (forward-char 1))
  1063. (setq end (point))
  1064. (or (and (not name)
  1065. (progn ;; unnamed results line already exists
  1066. (re-search-forward "[^ \f\t\n\r\v]" nil t)
  1067. (beginning-of-line 1)
  1068. (looking-at
  1069. (concat org-babel-result-regexp "\n")))
  1070. (prog1 (point)
  1071. ;; must remove and rebuild if hash!=old-hash
  1072. (if (and hash (not (string= hash (match-string 3))))
  1073. (prog1 nil
  1074. (forward-line 1)
  1075. (delete-region
  1076. end (org-babel-result-end)))
  1077. (setq end nil)))))))))
  1078. (if (and insert end)
  1079. (progn
  1080. (goto-char end)
  1081. (unless beg
  1082. (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
  1083. (insert (concat
  1084. (if indent
  1085. (mapconcat
  1086. (lambda (el) " ")
  1087. (number-sequence 1 indent) "")
  1088. "")
  1089. "#+results"
  1090. (when hash (concat "["hash"]"))
  1091. ":"
  1092. (when name (concat " " name)) "\n"))
  1093. (unless beg (insert "\n") (backward-char))
  1094. (beginning-of-line 0)
  1095. (if hash (org-babel-hide-hash))
  1096. (point))
  1097. found))))
  1098. (defvar org-block-regexp)
  1099. (defun org-babel-read-result ()
  1100. "Read the result at `point' into emacs-lisp."
  1101. (let ((case-fold-search t) result-string)
  1102. (cond
  1103. ((org-at-table-p) (org-babel-read-table))
  1104. ((looking-at org-bracket-link-regexp) (org-babel-read-link))
  1105. ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
  1106. ((looking-at "^[ \t]*: ")
  1107. (setq result-string
  1108. (org-babel-trim
  1109. (mapconcat (lambda (line)
  1110. (if (and (> (length line) 1)
  1111. (string-match "^[ \t]*: \\(.+\\)" line))
  1112. (match-string 1 line)
  1113. line))
  1114. (split-string
  1115. (buffer-substring
  1116. (point) (org-babel-result-end)) "[\r\n]+")
  1117. "\n")))
  1118. (or (org-babel-number-p result-string) result-string))
  1119. ((looking-at org-babel-result-regexp)
  1120. (save-excursion (forward-line 1) (org-babel-read-result))))))
  1121. (defun org-babel-read-table ()
  1122. "Read the table at `point' into emacs-lisp."
  1123. (mapcar (lambda (row)
  1124. (if (and (symbolp row) (equal row 'hline)) row
  1125. (mapcar #'org-babel-read row)))
  1126. (org-table-to-lisp)))
  1127. (defvar org-link-types-re)
  1128. (defun org-babel-read-link ()
  1129. "Read the link at `point' into emacs-lisp.
  1130. If the path of the link is a file path it is expanded using
  1131. `expand-file-name'."
  1132. (let* ((case-fold-search t)
  1133. (raw (and (looking-at org-bracket-link-regexp)
  1134. (org-babel-clean-text-properties (match-string 1))))
  1135. (type (and (string-match org-link-types-re raw)
  1136. (match-string 1 raw))))
  1137. (cond
  1138. ((not type) (expand-file-name raw))
  1139. ((string= type "file")
  1140. (and (string-match "file\\(.*\\):\\(.+\\)" raw)
  1141. (expand-file-name (match-string 2 raw))))
  1142. (t raw))))
  1143. (defun org-babel-insert-result
  1144. (result &optional result-params info hash indent lang)
  1145. "Insert RESULT into the current buffer.
  1146. By default RESULT is inserted after the end of the
  1147. current source block. With optional argument RESULT-PARAMS
  1148. controls insertion of results in the org-mode file.
  1149. RESULT-PARAMS can take the following values...
  1150. replace - (default option) insert results after the source block
  1151. replacing any previously inserted results
  1152. silent -- no results are inserted
  1153. file ---- the results are interpreted as a file path, and are
  1154. inserted into the buffer using the Org-mode file syntax
  1155. raw ----- results are added directly to the org-mode file. This
  1156. is a good option if you code block will output org-mode
  1157. formatted text.
  1158. org ----- similar in effect to raw, only the results are wrapped
  1159. in an org code block. Similar to the raw option, on
  1160. export the results will be interpreted as org-formatted
  1161. text, however by wrapping the results in an org code
  1162. block they can be replaced upon re-execution of the
  1163. code block.
  1164. html ---- results are added inside of a #+BEGIN_HTML block. This
  1165. is a good option if you code block will output html
  1166. formatted text.
  1167. latex --- results are added inside of a #+BEGIN_LATEX block.
  1168. This is a good option if you code block will output
  1169. latex formatted text.
  1170. code ---- the results are extracted in the syntax of the source
  1171. code of the language being evaluated and are added
  1172. inside of a #+BEGIN_SRC block with the source-code
  1173. language set appropriately. Note this relies on the
  1174. optional LANG argument."
  1175. (if (stringp result)
  1176. (progn
  1177. (setq result (org-babel-clean-text-properties result))
  1178. (when (member "file" result-params)
  1179. (setq result (org-babel-result-to-file result))))
  1180. (unless (listp result) (setq result (format "%S" result))))
  1181. (if (and result-params (member "silent" result-params))
  1182. (progn
  1183. (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
  1184. result)
  1185. (when (and (stringp result) ;; ensure results end in a newline
  1186. (not (or (string-equal (substring result -1) "\n")
  1187. (string-equal (substring result -1) "\r"))))
  1188. (setq result (concat result "\n")))
  1189. (save-excursion
  1190. (let ((existing-result (org-babel-where-is-src-block-result
  1191. t info hash indent))
  1192. (results-switches
  1193. (cdr (assoc :results_switches (nth 2 info))))
  1194. beg end)
  1195. (if (not existing-result)
  1196. (setq beg (point))
  1197. (goto-char existing-result)
  1198. (save-excursion
  1199. (re-search-forward "#" nil t)
  1200. (setq indent (- (current-column) 1)))
  1201. (forward-line 1)
  1202. (setq beg (point))
  1203. (cond
  1204. ((member "replace" result-params)
  1205. (delete-region (point) (org-babel-result-end)))
  1206. ((member "append" result-params)
  1207. (goto-char (org-babel-result-end)) (setq beg (point)))
  1208. ((member "prepend" result-params) ;; already there
  1209. )))
  1210. (setq results-switches
  1211. (if results-switches (concat " " results-switches) ""))
  1212. (cond
  1213. ;; assume the result is a table if it's not a string
  1214. ((not (stringp result))
  1215. (insert (concat (orgtbl-to-orgtbl
  1216. (if (or (eq 'hline (car result))
  1217. (and (listp (car result))
  1218. (listp (cdr (car result)))))
  1219. result (list result))
  1220. '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
  1221. (goto-char beg) (when (org-at-table-p) (org-table-align)))
  1222. ((member "file" result-params)
  1223. (insert result))
  1224. ((member "html" result-params)
  1225. (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
  1226. results-switches result)))
  1227. ((member "latex" result-params)
  1228. (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
  1229. results-switches result)))
  1230. ((member "code" result-params)
  1231. (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
  1232. (or lang "none") results-switches result)))
  1233. ((member "org" result-params)
  1234. (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
  1235. ((member "raw" result-params)
  1236. (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
  1237. (t
  1238. (org-babel-examplize-region
  1239. (point) (progn (insert result) (point)) results-switches)))
  1240. ;; possibly indent the results to match the #+results line
  1241. (setq end (if (listp result) (org-table-end) (point)))
  1242. (when (and indent (> indent 0)
  1243. ;; in this case `table-align' does the work for us
  1244. (not (and (listp result)
  1245. (member "append" result-params))))
  1246. (indent-rigidly beg end indent))))
  1247. (if (= (length result) 0)
  1248. (if (member "value" result-params)
  1249. (message "No result returned by source block")
  1250. (message "Source block produced no output"))
  1251. (message "finished"))))
  1252. (defun org-babel-remove-result (&optional info)
  1253. "Remove the result of the current source block."
  1254. (interactive)
  1255. (let ((location (org-babel-where-is-src-block-result nil info)) start)
  1256. (when location
  1257. (save-excursion
  1258. (goto-char location) (setq start (point)) (forward-line 1)
  1259. (delete-region start (org-babel-result-end))))))
  1260. (defun org-babel-result-end ()
  1261. "Return the point at the end of the current set of results"
  1262. (save-excursion
  1263. (if (org-at-table-p)
  1264. (progn (goto-char (org-table-end)) (point))
  1265. (let ((case-fold-search t))
  1266. (cond
  1267. ((looking-at "[ \t]*#\\+begin_latex")
  1268. (re-search-forward "[ \t]*#\\+end_latex" nil t)
  1269. (forward-line 1))
  1270. ((looking-at "[ \t]*#\\+begin_html")
  1271. (re-search-forward "[ \t]*#\\+end_html" nil t)
  1272. (forward-line 1))
  1273. ((looking-at "[ \t]*#\\+begin_example")
  1274. (re-search-forward "[ \t]*#\\+end_example" nil t)
  1275. (forward-line 1))
  1276. ((looking-at "[ \t]*#\\+begin_src")
  1277. (re-search-forward "[ \t]*#\\+end_src" nil t)
  1278. (forward-line 1))
  1279. (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
  1280. (forward-line 1))))))
  1281. (point))))
  1282. (defun org-babel-result-to-file (result)
  1283. "Convert RESULT into an `org-mode' link.
  1284. If the `default-directory' is different from the containing
  1285. file's directory then expand relative links."
  1286. (format
  1287. "[[file:%s]]"
  1288. (if (and default-directory
  1289. buffer-file-name
  1290. (not (string= (expand-file-name default-directory)
  1291. (expand-file-name
  1292. (file-name-directory buffer-file-name)))))
  1293. (expand-file-name result default-directory)
  1294. result)))
  1295. (defun org-babel-examplize-region (beg end &optional results-switches)
  1296. "Comment out region using the ': ' org example quote."
  1297. (interactive "*r")
  1298. (let ((size (count-lines beg end)))
  1299. (save-excursion
  1300. (cond ((= size 0)
  1301. (error (concat "This should be impossible:"
  1302. "a newline was appended to result if missing")))
  1303. ((< size org-babel-min-lines-for-block-output)
  1304. (goto-char beg)
  1305. (dotimes (n size)
  1306. (beginning-of-line 1) (insert ": ") (forward-line 1)))
  1307. (t
  1308. (goto-char beg)
  1309. (insert (if results-switches
  1310. (format "#+begin_example%s\n" results-switches)
  1311. "#+begin_example\n"))
  1312. (forward-char (- end beg))
  1313. (insert "#+end_example\n"))))))
  1314. (defun org-babel-merge-params (&rest plists)
  1315. "Combine all parameter association lists in PLISTS.
  1316. Later elements of PLISTS override the values of previous element.
  1317. This takes into account some special considerations for certain
  1318. parameters when merging lists."
  1319. (let ((results-exclusive-groups
  1320. '(("file" "vector" "table" "scalar" "raw" "org"
  1321. "html" "latex" "code" "pp")
  1322. ("replace" "silent" "append" "prepend")
  1323. ("output" "value")))
  1324. (exports-exclusive-groups
  1325. '(("code" "results" "both" "none")))
  1326. params results exports tangle noweb cache vars var ref shebang comments)
  1327. (flet ((e-merge (exclusive-groups &rest result-params)
  1328. ;; maintain exclusivity of mutually exclusive parameters
  1329. (let (output)
  1330. (mapc (lambda (new-params)
  1331. (mapc (lambda (new-param)
  1332. (mapc (lambda (exclusive-group)
  1333. (when (member new-param exclusive-group)
  1334. (mapcar (lambda (excluded-param)
  1335. (setq output
  1336. (delete
  1337. excluded-param
  1338. output)))
  1339. exclusive-group)))
  1340. exclusive-groups)
  1341. (setq output (org-uniquify
  1342. (cons new-param output))))
  1343. new-params))
  1344. result-params)
  1345. output)))
  1346. (mapc (lambda (plist)
  1347. (mapc (lambda (pair)
  1348. (case (car pair)
  1349. (:var
  1350. ;; we want only one specification per variable
  1351. (when (string-match
  1352. (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
  1353. "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
  1354. ;; TODO: When is this not true?
  1355. (setq var (intern (match-string 1 (cdr pair)))
  1356. ref (match-string 2 (cdr pair))
  1357. vars (cons (cons var ref)
  1358. (assq-delete-all var vars)))))
  1359. (:results
  1360. (setq results
  1361. (e-merge results-exclusive-groups
  1362. results (split-string (cdr pair)))))
  1363. (:file
  1364. (when (cdr pair)
  1365. (setq results (e-merge results-exclusive-groups
  1366. results '("file")))
  1367. (unless (or (member "both" exports)
  1368. (member "none" exports)
  1369. (member "code" exports))
  1370. (setq exports (e-merge exports-exclusive-groups
  1371. exports '("results"))))
  1372. (setq params
  1373. (cons pair
  1374. (assq-delete-all (car pair) params)))))
  1375. (:exports
  1376. (setq exports
  1377. (e-merge exports-exclusive-groups
  1378. exports (split-string (cdr pair)))))
  1379. (:tangle ;; take the latest -- always overwrite
  1380. (setq tangle (or (list (cdr pair)) tangle)))
  1381. (:noweb
  1382. (setq noweb
  1383. (e-merge '(("yes" "no")) noweb
  1384. (split-string (or (cdr pair) "")))))
  1385. (:cache
  1386. (setq cache
  1387. (e-merge '(("yes" "no")) cache
  1388. (split-string (or (cdr pair) "")))))
  1389. (:shebang ;; take the latest -- always overwrite
  1390. (setq shebang (or (list (cdr pair)) shebang)))
  1391. (:comments
  1392. (setq comments
  1393. (e-merge '(("yes" "no")) comments
  1394. (split-string (or (cdr pair) "")))))
  1395. (t ;; replace: this covers e.g. :session
  1396. (setq params
  1397. (cons pair
  1398. (assq-delete-all (car pair) params))))))
  1399. plist))
  1400. plists))
  1401. (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
  1402. (while vars (setq params (cons (cons :var (pop vars)) params)))
  1403. (cons (cons :comments (mapconcat 'identity comments " "))
  1404. (cons (cons :shebang (mapconcat 'identity shebang " "))
  1405. (cons (cons :cache (mapconcat 'identity cache " "))
  1406. (cons (cons :noweb (mapconcat 'identity noweb " "))
  1407. (cons (cons :tangle (mapconcat 'identity tangle " "))
  1408. (cons (cons :exports
  1409. (mapconcat 'identity exports " "))
  1410. (cons
  1411. (cons :results
  1412. (mapconcat 'identity results " "))
  1413. params)))))))))
  1414. (defun org-babel-expand-noweb-references (&optional info parent-buffer)
  1415. "Expand Noweb references in the body of the current source code block.
  1416. For example the following reference would be replaced with the
  1417. body of the source-code block named 'example-block'.
  1418. <<example-block>>
  1419. Note that any text preceding the <<foo>> construct on a line will
  1420. be interposed between the lines of the replacement text. So for
  1421. example if <<foo>> is placed behind a comment, then the entire
  1422. replacement text will also be commented.
  1423. This function must be called from inside of the buffer containing
  1424. the source-code block which holds BODY.
  1425. In addition the following syntax can be used to insert the
  1426. results of evaluating the source-code block named 'example-block'.
  1427. <<example-block()>>
  1428. Any optional arguments can be passed to example-block by placing
  1429. the arguments inside the parenthesis following the convention
  1430. defined by `org-babel-lob'. For example
  1431. <<example-block(a=9)>>
  1432. would set the value of argument \"a\" equal to \"9\". Note that
  1433. these arguments are not evaluated in the current source-code
  1434. block but are passed literally to the \"example-block\"."
  1435. (let* ((parent-buffer (or parent-buffer (current-buffer)))
  1436. (info (or info (org-babel-get-src-block-info)))
  1437. (lang (nth 0 info))
  1438. (body (nth 1 info))
  1439. (new-body "") index source-name evaluate prefix)
  1440. (flet ((nb-add (text)
  1441. (setq new-body (concat new-body text))))
  1442. (with-temp-buffer
  1443. (insert body) (goto-char (point-min))
  1444. (setq index (point))
  1445. (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
  1446. (save-match-data (setf source-name (match-string 1)))
  1447. (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
  1448. (save-match-data
  1449. (setq prefix
  1450. (buffer-substring (match-beginning 0)
  1451. (save-excursion
  1452. (beginning-of-line 1) (point)))))
  1453. ;; add interval to new-body (removing noweb reference)
  1454. (goto-char (match-beginning 0))
  1455. (nb-add (buffer-substring index (point)))
  1456. (goto-char (match-end 0))
  1457. (setq index (point))
  1458. (nb-add (with-current-buffer parent-buffer
  1459. (mapconcat ;; interpose PREFIX between every line
  1460. #'identity
  1461. (split-string
  1462. (if evaluate
  1463. (let ((raw (org-babel-ref-resolve-reference
  1464. source-name nil)))
  1465. (if (stringp raw) raw (format "%S" raw)))
  1466. (save-restriction
  1467. (widen)
  1468. (let ((point (org-babel-find-named-block
  1469. source-name)))
  1470. (if point
  1471. (save-excursion
  1472. (goto-char point)
  1473. (org-babel-trim
  1474. (org-babel-expand-noweb-references
  1475. (org-babel-get-src-block-info))))
  1476. ;; optionally raise an error if named
  1477. ;; source-block doesn't exist
  1478. (if (member lang org-babel-noweb-error-langs)
  1479. (error "%s"
  1480. (concat
  1481. "<<" source-name ">> "
  1482. "could not be resolved (see "
  1483. "`org-babel-noweb-error-langs')"))
  1484. "")))))
  1485. "[\n\r]") (concat "\n" prefix)))))
  1486. (nb-add (buffer-substring index (point-max)))))
  1487. new-body))
  1488. (defun org-babel-clean-text-properties (text)
  1489. "Strip all properties from text return."
  1490. (when text
  1491. (set-text-properties 0 (length text) nil text) text))
  1492. (defun org-babel-strip-protective-commas (body)
  1493. "Strip protective commas from bodies of source blocks."
  1494. (replace-regexp-in-string "^,#" "#" body))
  1495. (defun org-babel-read (cell)
  1496. "Convert the string value of CELL to a number if appropriate.
  1497. Otherwise if cell looks like lisp (meaning it starts with a
  1498. \"(\" or a \"'\") then read it as lisp, otherwise return it
  1499. unmodified as a string.
  1500. This is taken almost directly from `org-read-prop'."
  1501. (if (and (stringp cell) (not (equal cell "")))
  1502. (or (org-babel-number-p cell)
  1503. (if (or (equal "(" (substring cell 0 1))
  1504. (equal "'" (substring cell 0 1))
  1505. (equal "`" (substring cell 0 1)))
  1506. (eval (read cell))
  1507. (progn (set-text-properties 0 (length cell) nil cell) cell)))
  1508. cell))
  1509. (defun org-babel-number-p (string)
  1510. "Return t if STRING represents a number."
  1511. (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
  1512. (= (length (substring string (match-beginning 0)
  1513. (match-end 0)))
  1514. (length string)))
  1515. (string-to-number string)))
  1516. (defun org-babel-import-elisp-from-file (file-name &optional separator)
  1517. "Read the results located at FILE-NAME into an elisp table.
  1518. If the table is trivial, then return it as a scalar."
  1519. (let (result)
  1520. (save-window-excursion
  1521. (with-temp-buffer
  1522. (condition-case nil
  1523. (progn
  1524. (org-table-import file-name separator)
  1525. (delete-file file-name)
  1526. (setq result (mapcar (lambda (row)
  1527. (mapcar #'org-babel-string-read row))
  1528. (org-table-to-lisp))))
  1529. (error nil)))
  1530. (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
  1531. (if (consp (car result))
  1532. (if (null (cdr (car result)))
  1533. (caar result)
  1534. result)
  1535. (car result))
  1536. result))))
  1537. (defun org-babel-string-read (cell)
  1538. "Strip nested \"s from around strings."
  1539. (org-babel-read (or (and (stringp cell)
  1540. (string-match "\\\"\\(.+\\)\\\"" cell)
  1541. (match-string 1 cell))
  1542. cell)))
  1543. (defun org-babel-reverse-string (string)
  1544. "Return the reverse of STRING."
  1545. (apply 'string (reverse (string-to-list string))))
  1546. (defun org-babel-chomp (string &optional regexp)
  1547. "Strip trailing spaces and carriage returns from STRING.
  1548. Default regexp used is \"[ \f\t\n\r\v]\" but can be
  1549. overwritten by specifying a regexp as a second argument."
  1550. (let ((regexp (or regexp "[ \f\t\n\r\v]")))
  1551. (while (and (> (length string) 0)
  1552. (string-match regexp (substring string -1)))
  1553. (setq string (substring string 0 -1)))
  1554. string))
  1555. (defun org-babel-trim (string &optional regexp)
  1556. "Strip leading and trailing spaces and carriage returns from STRING.
  1557. Like `org-babel-chomp' only it runs on both the front and back
  1558. of the string."
  1559. (org-babel-chomp (org-babel-reverse-string
  1560. (org-babel-chomp (org-babel-reverse-string string) regexp))
  1561. regexp))
  1562. (defvar org-babel-org-babel-call-process-region-original nil)
  1563. (defun org-babel-tramp-handle-call-process-region
  1564. (start end program &optional delete buffer display &rest args)
  1565. "Use tramp to handle call-process-region.
  1566. Fixes a bug in `tramp-handle-call-process-region'."
  1567. (if (and (featurep 'tramp) (file-remote-p default-directory))
  1568. (let ((tmpfile (tramp-compat-make-temp-file "")))
  1569. (write-region start end tmpfile)
  1570. (when delete (delete-region start end))
  1571. (unwind-protect
  1572. ;; (apply 'call-process program tmpfile buffer display args)
  1573. ;; bug in tramp
  1574. (apply 'process-file program tmpfile buffer display args)
  1575. (delete-file tmpfile)))
  1576. ;; org-babel-call-process-region-original is the original emacs definition. It
  1577. ;; is in scope from the let binding in org-babel-execute-src-block
  1578. (apply org-babel-call-process-region-original
  1579. start end program delete buffer display args)))
  1580. (defun org-babel-maybe-remote-file (file)
  1581. "Conditionally parse information on a remote connnection.
  1582. If FILE specifies a remove file, then parse the information on
  1583. the remote connection."
  1584. (if (file-remote-p default-directory)
  1585. (let* ((vec (tramp-dissect-file-name default-directory))
  1586. (user (tramp-file-name-user vec))
  1587. (host (tramp-file-name-host vec)))
  1588. (concat "/" user (when user "@") host ":" file))
  1589. file))
  1590. (defun org-babel-tramp-localname (file)
  1591. "Return the local name component of FILE."
  1592. (if (file-remote-p file)
  1593. (let (localname)
  1594. (with-parsed-tramp-file-name file nil
  1595. localname))
  1596. file))
  1597. (defvar org-babel-temporary-directory
  1598. (or (and (boundp 'org-babel-temporary-directory)
  1599. org-babel-temporary-directory)
  1600. (make-temp-file "babel-" t))
  1601. "Directory to hold temporary files created to execute code blocks.
  1602. Used by `org-babel-temp-file'. This directory will be removed on
  1603. Emacs shutdown.")
  1604. (defun org-babel-temp-file (prefix &optional suffix)
  1605. "Create a temporary file in the `org-babel-temporary-directory'.
  1606. Passes PREFIX and SUFFIX directly to `make-temp-file' with the
  1607. value of `temporary-file-directory' temporarily set to the value
  1608. of `org-babel-temporary-directory'."
  1609. (if (file-remote-p default-directory)
  1610. (make-temp-file
  1611. (concat (file-remote-p default-directory)
  1612. (expand-file-name
  1613. prefix temporary-file-directory)
  1614. nil suffix))
  1615. (let ((temporary-file-directory (expand-file-name
  1616. org-babel-temporary-directory
  1617. temporary-file-directory)))
  1618. (make-temp-file prefix nil suffix))))
  1619. (defun org-babel-remove-temporary-directory ()
  1620. "Remove `org-babel-temporary-directory' on Emacs shutdown."
  1621. (when (boundp 'org-babel-temporary-directory)
  1622. ;; taken from `delete-directory' in files.el
  1623. (mapc (lambda (file)
  1624. ;; This test is equivalent to
  1625. ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1626. ;; but more efficient
  1627. (if (eq t (car (file-attributes file)))
  1628. (delete-directory file)
  1629. (delete-file file)))
  1630. ;; We do not want to delete "." and "..".
  1631. (directory-files org-babel-temporary-directory 'full
  1632. "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
  1633. (delete-directory org-babel-temporary-directory)))
  1634. (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
  1635. (provide 'ob)
  1636. ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
  1637. ;;; ob.el ends here