org-babel.el 64 KB

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