org-babel.el 64 KB

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