org-babel.el 62 KB

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