ob.el 60 KB

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