ob.el 60 KB

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