ob.el 64 KB

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