ob.el 65 KB

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