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