ob.el 66 KB

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