org-babel.el 64 KB

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