org-babel.el 64 KB

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