ob.el 63 KB

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