org-babel.el 62 KB

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