ob.el 65 KB

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