Release 7.3
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / ob.el
blob44557c6624ad476e22688e822c3b266e22933aa2
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.3
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; See the online documentation for more information
29 ;; http://orgmode.org/worg/org-contrib/babel/
31 ;;; Code:
32 (eval-when-compile
33 (require 'cl))
34 (require 'org-macs)
36 (defvar org-babel-call-process-region-original)
37 (declare-function show-all "outline" ())
38 (declare-function tramp-compat-make-temp-file "tramp-compat"
39 (filename &optional dir-flag))
40 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
41 (declare-function tramp-file-name-user "tramp" (vec))
42 (declare-function tramp-file-name-host "tramp" (vec))
43 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
44 (declare-function org-icompleting-read "org" (&rest args))
45 (declare-function org-edit-src-code "org-src"
46 (&optional context code edit-buffer-name quietp))
47 (declare-function org-edit-src-exit "org-src" (&optional context))
48 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
49 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
50 (declare-function org-outline-overlay-data "org" (&optional use-markers))
51 (declare-function org-set-outline-overlay-data "org" (data))
52 (declare-function org-narrow-to-subtree "org" ())
53 (declare-function org-entry-get "org"
54 (pom property &optional inherit literal-nil))
55 (declare-function org-make-options-regexp "org" (kwds &optional extra))
56 (declare-function org-do-remove-indentation "org" (&optional n))
57 (declare-function org-show-context "org" (&optional key))
58 (declare-function org-at-table-p "org" (&optional table-type))
59 (declare-function org-cycle "org" (&optional arg))
60 (declare-function org-uniquify "org" (list))
61 (declare-function org-current-level "org" ())
62 (declare-function org-table-import "org-table" (file arg))
63 (declare-function org-add-hook "org-compat"
64 (hook function &optional append local))
65 (declare-function org-table-align "org-table" ())
66 (declare-function org-table-end "org-table" (&optional table-type))
67 (declare-function orgtbl-to-generic "org-table" (table params))
68 (declare-function orgtbl-to-orgtbl "org-table" (table params))
69 (declare-function org-babel-lob-get-info "ob-lob" nil)
70 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
71 (declare-function org-babel-ref-parse "ob-ref" (assignment))
72 (declare-function org-babel-ref-resolve "ob-ref" (ref))
73 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
74 (declare-function org-number-sequence "org-compat" (from &optional to inc))
76 (defgroup org-babel nil
77 "Code block evaluation and management in `org-mode' documents."
78 :tag "Babel"
79 :group 'org)
81 (defcustom org-confirm-babel-evaluate t
82 "Confirm before evaluation.
83 Require confirmation before interactively evaluating code
84 blocks in Org-mode buffers. The default value of this variable
85 is t, meaning confirmation is required for any code block
86 evaluation. This variable can be set to nil to inhibit any
87 future confirmation requests. This variable can also be set to a
88 function which takes two arguments the language of the code block
89 and the body of the code block. Such a function should then
90 return a non-nil value if the user should be prompted for
91 execution or nil if no prompt is required.
93 Warning: Disabling confirmation may result in accidental
94 evaluation of potentially harmful code. It may be advisable
95 remove code block execution from C-c C-c as further protection
96 against accidental code block evaluation. The
97 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
98 remove code block execution from the C-c C-c keybinding."
99 :group 'org-babel
100 :type '(choice boolean function))
101 ;; don't allow this variable to be changed through file settings
102 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
104 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
105 "Remove code block evaluation from the C-c C-c key binding."
106 :group 'org-babel
107 :type 'boolean)
109 (defvar org-babel-src-name-regexp
110 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
111 "Regular expression used to match a source name line.")
113 (defvar org-babel-multi-line-header-regexp
114 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
115 "Regular expression used to match multi-line header arguments.")
117 (defvar org-babel-src-name-w-name-regexp
118 (concat org-babel-src-name-regexp
119 "\\("
120 org-babel-multi-line-header-regexp
121 "\\)*"
122 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
123 "Regular expression matching source name lines with a name.")
125 (defvar org-babel-src-block-regexp
126 (concat
127 ;; (1) indentation (2) lang
128 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
129 ;; (3) switches
130 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
131 ;; (4) header arguments
132 "\\([^\n]*\\)\n"
133 ;; (5) body
134 "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
135 "Regexp used to identify code blocks.")
137 (defvar org-babel-inline-src-block-regexp
138 (concat
139 ;; (1) replacement target (2) lang
140 "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
141 ;; (3,4) (unused, headers)
142 "\\(\\|\\[\\(.*?\\)\\]\\)"
143 ;; (5) body
144 "{\\([^\f\n\r\v]+?\\)}\\)")
145 "Regexp used to identify inline src-blocks.")
147 (defun org-babel-get-header (params key &optional others)
148 "Select only header argument of type KEY from a list.
149 Optional argument OTHERS indicates that only the header that do
150 not match KEY should be returned."
151 (delq nil
152 (mapcar
153 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
154 params)))
156 (defun org-babel-get-src-block-info (&optional light)
157 "Get information on the current source block.
159 Optional argument LIGHT does not resolve remote variable
160 references; a process which could likely result in the execution
161 of other code blocks.
163 Returns a list
164 (language body header-arguments-alist switches name indent)."
165 (let ((case-fold-search t) head info name indent)
166 ;; full code block
167 (if (setq head (org-babel-where-is-src-block-head))
168 (save-excursion
169 (goto-char head)
170 (setq info (org-babel-parse-src-block-match))
171 (setq indent (car (last info)))
172 (setq info (butlast info))
173 (while (and (forward-line -1)
174 (looking-at org-babel-multi-line-header-regexp))
175 (setf (nth 2 info)
176 (org-babel-merge-params
177 (org-babel-parse-header-arguments (match-string 1))
178 (nth 2 info))))
179 (when (looking-at org-babel-src-name-w-name-regexp)
180 (setq name (org-babel-clean-text-properties (match-string 4)))
181 (when (match-string 6)
182 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
183 (org-babel-merge-params
184 (mapcar (lambda (ref) (cons :var ref))
185 (org-babel-ref-split-args (match-string 6)))
186 (nth 2 info))))))
187 ;; inline source block
188 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
189 (looking-at org-babel-inline-src-block-regexp))
190 (setq info (org-babel-parse-inline-src-block-match))))
191 ;; resolve variable references and add summary parameters
192 (when (and info (not light))
193 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
194 (when info (append info (list name indent)))))
196 (defun org-babel-confirm-evaluate (info)
197 "Confirm evaluation of the code block INFO.
198 This behavior can be suppressed by setting the value of
199 `org-confirm-babel-evaluate' to nil, in which case all future
200 interactive code block evaluations will proceed without any
201 confirmation from the user.
203 Note disabling confirmation may result in accidental evaluation
204 of potentially harmful code."
205 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
206 (when (assoc :noeval (nth 2 info)) "no")))
207 (query (or (equal eval "query")
208 (if (functionp org-confirm-babel-evaluate)
209 (funcall org-confirm-babel-evaluate
210 (nth 0 info) (nth 1 info))
211 org-confirm-babel-evaluate))))
212 (if (or (equal eval "never") (equal eval "no")
213 (and query
214 (not (yes-or-no-p
215 (format "Evaluate this%scode on your system? "
216 (if info (format " %s " (nth 0 info)) " "))))))
217 (prog1 nil (message "evaluation aborted"))
218 t)))
220 ;;;###autoload
221 (defun org-babel-execute-safely-maybe ()
222 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
223 (org-babel-execute-maybe)))
225 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
227 ;;;###autoload
228 (defun org-babel-execute-maybe ()
229 (interactive)
230 (or (org-babel-execute-src-block-maybe)
231 (org-babel-lob-execute-maybe)))
233 (defun org-babel-execute-src-block-maybe ()
234 "Conditionally execute a source block.
235 Detect if this is context for a Babel src-block and if so
236 then run `org-babel-execute-src-block'."
237 (interactive)
238 (let ((info (org-babel-get-src-block-info)))
239 (if info
240 (progn (org-babel-execute-src-block current-prefix-arg info) t) nil)))
242 ;;;###autoload
243 (defun org-babel-expand-src-block-maybe ()
244 "Conditionally expand a source block.
245 Detect if this is context for a org-babel src-block and if so
246 then run `org-babel-expand-src-block'."
247 (interactive)
248 (let ((info (org-babel-get-src-block-info)))
249 (if info
250 (progn (org-babel-expand-src-block current-prefix-arg info) t)
251 nil)))
253 ;;;###autoload
254 (defun org-babel-load-in-session-maybe ()
255 "Conditionally load a source block in a session.
256 Detect if this is context for a org-babel src-block and if so
257 then run `org-babel-load-in-session'."
258 (interactive)
259 (let ((info (org-babel-get-src-block-info)))
260 (if info
261 (progn (org-babel-load-in-session current-prefix-arg info) t)
262 nil)))
264 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
266 ;;;###autoload
267 (defun org-babel-pop-to-session-maybe ()
268 "Conditionally pop to a session.
269 Detect if this is context for a org-babel src-block and if so
270 then run `org-babel-pop-to-session'."
271 (interactive)
272 (let ((info (org-babel-get-src-block-info)))
273 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
275 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
277 (defconst org-babel-header-arg-names
278 '(cache cmdline colnames dir exports file noweb results
279 session tangle var eval noeval comments)
280 "Common header arguments used by org-babel.
281 Note that individual languages may define their own language
282 specific header arguments as well.")
284 (defvar org-babel-default-header-args
285 '((:session . "none") (:results . "replace") (:exports . "code")
286 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
287 "Default arguments to use when evaluating a source block.")
289 (defvar org-babel-default-inline-header-args
290 '((:session . "none") (:results . "silent") (:exports . "results"))
291 "Default arguments to use when evaluating an inline source block.")
293 (defvar org-babel-current-buffer-properties nil
294 "Local cache for buffer properties.")
295 (make-variable-buffer-local 'org-babel-current-buffer-properties)
297 (defvar org-babel-result-regexp
298 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
299 "Regular expression used to match result lines.
300 If the results are associated with a hash key then the hash will
301 be saved in the second match data.")
303 (defvar org-babel-result-w-name-regexp
304 (concat org-babel-result-regexp
305 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
307 (defvar org-babel-min-lines-for-block-output 10
308 "The minimum number of lines for block output.
309 If number of lines of output is equal to or exceeds this
310 value, the output is placed in a #+begin_example...#+end_example
311 block. Otherwise the output is marked as literal by inserting
312 colons at the starts of the lines. This variable only takes
313 effect if the :results output option is in effect.")
315 (defvar org-babel-noweb-error-langs nil
316 "Languages for which Babel will raise literate programming errors.
317 List of languages for which errors should be raised when the
318 source code block satisfying a noweb reference in this language
319 can not be resolved.")
321 (defvar org-babel-hash-show 4
322 "Number of initial characters to show of a hidden results hash.")
324 (defvar org-babel-after-execute-hook nil
325 "Hook for functions to be called after `org-babel-execute-src-block'")
326 (defun org-babel-named-src-block-regexp-for-name (name)
327 "This generates a regexp used to match a src block named NAME."
328 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
329 (substring org-babel-src-block-regexp 1)))
331 ;;; functions
332 (defvar call-process-region)
333 ;;;###autoload
335 (defun org-babel-execute-src-block (&optional arg info params)
336 "Execute the current source code block.
337 Insert the results of execution into the buffer. Source code
338 execution and the collection and formatting of results can be
339 controlled through a variety of header arguments.
341 With prefix argument ARG, force re-execution even if a an
342 existing result cached in the buffer would otherwise have been
343 returned.
345 Optionally supply a value for INFO in the form returned by
346 `org-babel-get-src-block-info'.
348 Optionally supply a value for PARAMS which will be merged with
349 the header arguments specified at the front of the source code
350 block."
351 (interactive)
352 (let ((info (or info (org-babel-get-src-block-info))))
353 (when (org-babel-confirm-evaluate info)
354 (let* ((lang (nth 0 info))
355 (params (if params
356 (org-babel-process-params
357 (org-babel-merge-params (nth 2 info) params))
358 (nth 2 info)))
359 (cache? (and (not arg) (cdr (assoc :cache params))
360 (string= "yes" (cdr (assoc :cache params)))))
361 (result-params (cdr (assoc :result-params params)))
362 (new-hash (when cache? (org-babel-sha1-hash info)))
363 (old-hash (when cache? (org-babel-result-hash info)))
364 (body (setf (nth 1 info)
365 (if (and (cdr (assoc :noweb params))
366 (string= "yes" (cdr (assoc :noweb params))))
367 (org-babel-expand-noweb-references info)
368 (nth 1 info))))
369 (cmd (intern (concat "org-babel-execute:" lang)))
370 (dir (cdr (assoc :dir params)))
371 (default-directory
372 (or (and dir (file-name-as-directory dir)) default-directory))
373 (org-babel-call-process-region-original
374 (if (boundp 'org-babel-call-process-region-original)
375 org-babel-call-process-region-original
376 (symbol-function 'call-process-region)))
377 (indent (car (last info)))
378 result)
379 (unwind-protect
380 (flet ((call-process-region (&rest args)
381 (apply 'org-babel-tramp-handle-call-process-region args)))
382 (unless (fboundp cmd)
383 (error "No org-babel-execute function for %s!" lang))
384 (if (and (not arg) new-hash (equal new-hash old-hash))
385 (save-excursion ;; return cached result
386 (goto-char (org-babel-where-is-src-block-result nil info))
387 (end-of-line 1) (forward-char 1)
388 (setq result (org-babel-read-result))
389 (message (replace-regexp-in-string
390 "%" "%%" (format "%S" result))) result)
391 (message "executing %s code block%s..."
392 (capitalize lang)
393 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
394 (setq result
395 ((lambda (result)
396 (cond
397 ((member "file" result-params)
398 (cdr (assoc :file params)))
399 ((and (eq (cdr (assoc :result-type params)) 'value)
400 (or (member "vector" result-params)
401 (member "table" result-params))
402 (not (listp result)))
403 (list (list result)))
404 (t result)))
405 (funcall cmd body params)))
406 (org-babel-insert-result
407 result result-params info new-hash indent lang)
408 (run-hooks 'org-babel-after-execute-hook)
409 result))
410 (setq call-process-region 'org-babel-call-process-region-original))))))
412 (defun org-babel-expand-body:generic (body params &optional var-lines)
413 "Expand BODY with PARAMS.
414 Expand a block of code with org-babel according to it's header
415 arguments. This generic implementation of body expansion is
416 called for languages which have not defined their own specific
417 org-babel-expand-body:lang function."
418 (mapconcat #'identity (append var-lines (list body)) "\n"))
420 ;;;###autoload
421 (defun org-babel-expand-src-block (&optional arg info params)
422 "Expand the current source code block.
423 Expand according to the source code block's header
424 arguments and pop open the results in a preview buffer."
425 (interactive)
426 (let* ((info (or info (org-babel-get-src-block-info)))
427 (lang (nth 0 info))
428 (params (setf (nth 2 info)
429 (sort (org-babel-merge-params (nth 2 info) params)
430 (lambda (el1 el2) (string< (symbol-name (car el1))
431 (symbol-name (car el2)))))))
432 (body (setf (nth 1 info)
433 (if (and (cdr (assoc :noweb params))
434 (string= "yes" (cdr (assoc :noweb params))))
435 (org-babel-expand-noweb-references info) (nth 1 info))))
436 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
437 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
438 (expanded
439 (if (fboundp expand-cmd) (funcall expand-cmd body params)
440 (org-babel-expand-body:generic
441 body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
442 (org-edit-src-code
443 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
445 ;;;###autoload
446 (defun org-babel-load-in-session (&optional arg info)
447 "Load the body of the current source-code block.
448 Evaluate the header arguments for the source block before
449 entering the session. After loading the body this pops open the
450 session."
451 (interactive)
452 (let* ((info (or info (org-babel-get-src-block-info)))
453 (lang (nth 0 info))
454 (params (nth 2 info))
455 (body (setf (nth 1 info)
456 (if (and (cdr (assoc :noweb params))
457 (string= "yes" (cdr (assoc :noweb params))))
458 (org-babel-expand-noweb-references info)
459 (nth 1 info))))
460 (session (cdr (assoc :session params)))
461 (dir (cdr (assoc :dir params)))
462 (default-directory
463 (or (and dir (file-name-as-directory dir)) default-directory))
464 (cmd (intern (concat "org-babel-load-session:" lang))))
465 (unless (fboundp cmd)
466 (error "No org-babel-load-session function for %s!" lang))
467 (pop-to-buffer (funcall cmd session body params))
468 (end-of-line 1)))
470 ;;;###autoload
471 (defun org-babel-initiate-session (&optional arg info)
472 "Initiate session for current code block.
473 If called with a prefix argument then resolve any variable
474 references in the header arguments and assign these variables in
475 the session. Copy the body of the code block to the kill ring."
476 (interactive "P")
477 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
478 (lang (nth 0 info))
479 (body (nth 1 info))
480 (params (nth 2 info))
481 (session (cdr (assoc :session params)))
482 (dir (cdr (assoc :dir params)))
483 (default-directory
484 (or (and dir (file-name-as-directory dir)) default-directory))
485 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
486 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
487 (if (and (stringp session) (string= session "none"))
488 (error "This block is not using a session!"))
489 (unless (fboundp init-cmd)
490 (error "No org-babel-initiate-session function for %s!" lang))
491 (with-temp-buffer (insert (org-babel-trim body))
492 (copy-region-as-kill (point-min) (point-max)))
493 (when arg
494 (unless (fboundp prep-cmd)
495 (error "No org-babel-prep-session function for %s!" lang))
496 (funcall prep-cmd session params))
497 (funcall init-cmd session params)))
499 ;;;###autoload
500 (defun org-babel-switch-to-session (&optional arg info)
501 "Switch to the session of the current code block.
502 Uses `org-babel-initiate-session' to start the session. If called
503 with a prefix argument then this is passed on to
504 `org-babel-initiate-session'."
505 (interactive "P")
506 (pop-to-buffer (org-babel-initiate-session arg info))
507 (end-of-line 1))
509 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
511 ;;;###autoload
512 (defun org-babel-switch-to-session-with-code (&optional arg info)
513 "Switch to code buffer and display session."
514 (interactive "P")
515 (flet ((swap-windows
517 (let ((other-window-buffer (window-buffer (next-window))))
518 (set-window-buffer (next-window) (current-buffer))
519 (set-window-buffer (selected-window) other-window-buffer))
520 (other-window 1)))
521 (let ((info (org-babel-get-src-block-info))
522 (org-src-window-setup 'reorganize-frame))
523 (save-excursion
524 (org-babel-switch-to-session arg info))
525 (org-edit-src-code))
526 (swap-windows)))
528 (defmacro org-babel-do-in-edit-buffer (&rest body)
529 "Evaluate BODY in edit buffer if there is a code block at point.
530 Return t if a code block was found at point, nil otherwise."
531 `(let ((org-src-window-setup 'switch-invisibly))
532 (when (and (org-babel-where-is-src-block-head)
533 (org-edit-src-code nil nil nil 'quietly))
534 (unwind-protect (progn ,@body)
535 (if (org-bound-and-true-p org-edit-src-from-org-mode)
536 (org-edit-src-exit)))
537 t)))
539 (defun org-babel-do-key-sequence-in-edit-buffer (key)
540 "Read key sequence and execute the command in edit buffer.
541 Enter a key sequence to be executed in the language major-mode
542 edit buffer. For example, TAB will alter the contents of the
543 Org-mode code block according to the effect of TAB in the
544 language major-mode buffer. For languages that support
545 interactive sessions, this can be used to send code from the Org
546 buffer to the session for evaluation using the native major-mode
547 evaluation mechanisms."
548 (interactive "kEnter key-sequence to execute in edit buffer: ")
549 (org-babel-do-in-edit-buffer
550 (call-interactively
551 (key-binding (or key (read-key-sequence nil))))))
553 (defvar org-bracket-link-regexp)
554 ;;;###autoload
555 (defun org-babel-open-src-block-result (&optional re-run)
556 "If `point' is on a src block then open the results of the
557 source code block, otherwise return nil. With optional prefix
558 argument RE-RUN the source-code block is evaluated even if
559 results already exist."
560 (interactive "P")
561 (when (org-babel-get-src-block-info)
562 (save-excursion
563 ;; go to the results, if there aren't any then run the block
564 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
565 (progn (org-babel-execute-src-block)
566 (org-babel-where-is-src-block-result))))
567 (end-of-line 1)
568 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
569 ;; open the results
570 (if (looking-at org-bracket-link-regexp)
571 ;; file results
572 (org-open-at-point)
573 (let ((results (org-babel-read-result)))
574 (flet ((echo-res (result)
575 (if (stringp result) result (format "%S" result))))
576 (pop-to-buffer (get-buffer-create "org-babel-results"))
577 (delete-region (point-min) (point-max))
578 (if (listp results)
579 ;; table result
580 (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
581 ;; scalar result
582 (insert (echo-res results))))))
583 t)))
585 ;;;###autoload
586 (defun org-babel-execute-buffer (&optional arg)
587 "Execute source code blocks in a buffer.
588 Call `org-babel-execute-src-block' on every source block in
589 the current buffer."
590 (interactive "P")
591 (org-save-outline-visibility t
592 (org-babel-map-src-blocks nil
593 (org-babel-execute-src-block arg))))
595 ;;;###autoload
596 (defun org-babel-execute-subtree (&optional arg)
597 "Execute source code blocks in a subtree.
598 Call `org-babel-execute-src-block' on every source block in
599 the current subtree."
600 (interactive "P")
601 (save-restriction
602 (save-excursion
603 (org-narrow-to-subtree)
604 (org-babel-execute-buffer arg)
605 (widen))))
607 ;;;###autoload
608 (defun org-babel-sha1-hash (&optional info)
609 "Generate an sha1 hash based on the value of info."
610 (interactive)
611 (let ((print-level nil)
612 (info (or info (org-babel-get-src-block-info))))
613 (setf (nth 2 info)
614 (sort (copy-sequence (nth 2 info))
615 (lambda (a b) (string< (car a) (car b)))))
616 (let ((hash (sha1
617 (format "%s-%s"
618 (mapconcat
619 #'identity
620 (delq nil
621 (mapcar
622 (lambda (arg)
623 (let ((v (cdr arg)))
624 (when (and v (not (and (sequencep v)
625 (not (consp v))
626 (= (length v) 0))))
627 (format "%S" v))))
628 (nth 2 info))) ":")
629 (nth 1 info)))))
630 (when (interactive-p) (message hash))
631 hash)))
633 (defun org-babel-result-hash (&optional info)
634 "Return the in-buffer hash associated with INFO."
635 (org-babel-where-is-src-block-result nil info)
636 (org-babel-clean-text-properties (match-string 3)))
638 (defun org-babel-hide-hash ()
639 "Hide the hash in the current results line.
640 Only the initial `org-babel-hash-show' characters of the hash
641 will remain visible."
642 (add-to-invisibility-spec '(org-babel-hide-hash . t))
643 (save-excursion
644 (when (and (re-search-forward org-babel-result-regexp nil t)
645 (match-string 3))
646 (let* ((start (match-beginning 3))
647 (hide-start (+ org-babel-hash-show start))
648 (end (match-end 3))
649 (hash (match-string 3))
650 ov1 ov2)
651 (setq ov1 (make-overlay start hide-start))
652 (setq ov2 (make-overlay hide-start end))
653 (overlay-put ov2 'invisible 'org-babel-hide-hash)
654 (overlay-put ov1 'babel-hash hash)))))
656 (defun org-babel-hide-all-hashes ()
657 "Hide the hash in the current buffer.
658 Only the initial `org-babel-hash-show' characters of each hash
659 will remain visible. This function should be called as part of
660 the `org-mode-hook'."
661 (save-excursion
662 (while (re-search-forward org-babel-result-regexp nil t)
663 (goto-char (match-beginning 0))
664 (org-babel-hide-hash)
665 (goto-char (match-end 0)))))
666 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
668 (defun org-babel-hash-at-point (&optional point)
669 "Return the value of the hash at POINT.
670 The hash is also added as the last element of the kill ring.
671 This can be called with C-c C-c."
672 (interactive)
673 (let ((hash (car (delq nil (mapcar
674 (lambda (ol) (overlay-get ol 'babel-hash))
675 (overlays-at (or point (point))))))))
676 (when hash (kill-new hash) (message hash))))
677 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
679 (defun org-babel-result-hide-spec ()
680 "Hide portions of results lines.
681 Add `org-babel-hide-result' as an invisibility spec for hiding
682 portions of results lines."
683 (add-to-invisibility-spec '(org-babel-hide-result . t)))
684 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
686 (defvar org-babel-hide-result-overlays nil
687 "Overlays hiding results.")
689 (defun org-babel-result-hide-all ()
690 "Fold all results in the current buffer."
691 (interactive)
692 (org-babel-show-result-all)
693 (save-excursion
694 (while (re-search-forward org-babel-result-regexp nil t)
695 (save-excursion (goto-char (match-beginning 0))
696 (org-babel-hide-result-toggle-maybe)))))
698 (defun org-babel-show-result-all ()
699 "Unfold all results in the current buffer."
700 (mapc 'delete-overlay org-babel-hide-result-overlays)
701 (setq org-babel-hide-result-overlays nil))
703 ;;;###autoload
704 (defun org-babel-hide-result-toggle-maybe ()
705 "Toggle visibility of result at point."
706 (interactive)
707 (let ((case-fold-search t))
708 (if (save-excursion
709 (beginning-of-line 1)
710 (looking-at org-babel-result-regexp))
711 (progn (org-babel-hide-result-toggle)
712 t) ;; to signal that we took action
713 nil))) ;; to signal that we did not
715 (defun org-babel-hide-result-toggle (&optional force)
716 "Toggle the visibility of the current result."
717 (interactive)
718 (save-excursion
719 (beginning-of-line)
720 (if (re-search-forward org-babel-result-regexp nil t)
721 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
722 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
724 (if (memq t (mapcar (lambda (overlay)
725 (eq (overlay-get overlay 'invisible)
726 'org-babel-hide-result))
727 (overlays-at start)))
728 (if (or (not force) (eq force 'off))
729 (mapc (lambda (ov)
730 (when (member ov org-babel-hide-result-overlays)
731 (setq org-babel-hide-result-overlays
732 (delq ov org-babel-hide-result-overlays)))
733 (when (eq (overlay-get ov 'invisible)
734 'org-babel-hide-result)
735 (delete-overlay ov)))
736 (overlays-at start)))
737 (setq ov (make-overlay start end))
738 (overlay-put ov 'invisible 'org-babel-hide-result)
739 ;; make the block accessible to isearch
740 (overlay-put
741 ov 'isearch-open-invisible
742 (lambda (ov)
743 (when (member ov org-babel-hide-result-overlays)
744 (setq org-babel-hide-result-overlays
745 (delq ov org-babel-hide-result-overlays)))
746 (when (eq (overlay-get ov 'invisible)
747 'org-babel-hide-result)
748 (delete-overlay ov))))
749 (push ov org-babel-hide-result-overlays)))
750 (error "Not looking at a result line"))))
752 ;; org-tab-after-check-for-cycling-hook
753 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
754 ;; Remove overlays when changing major mode
755 (add-hook 'org-mode-hook
756 (lambda () (org-add-hook 'change-major-mode-hook
757 'org-babel-show-result-all 'append 'local)))
759 (defmacro org-babel-map-src-blocks (file &rest body)
760 "Evaluate BODY forms on each source-block in FILE.
761 If FILE is nil evaluate BODY forms on source blocks in current
762 buffer. During evaluation of BODY the following local variables
763 are set relative to the currently matched code block.
765 full-block ------- string holding the entirety of the code block
766 beg-block -------- point at the beginning of the code block
767 end-block -------- point at the end of the matched code block
768 lang ------------- string holding the language of the code block
769 beg-lang --------- point at the beginning of the lang
770 end-lang --------- point at the end of the lang
771 switches --------- string holding the switches
772 beg-switches ----- point at the beginning of the switches
773 end-switches ----- point at the end of the switches
774 header-args ------ string holding the header-args
775 beg-header-args -- point at the beginning of the header-args
776 end-header-args -- point at the end of the header-args
777 body ------------- string holding the body of the code block
778 beg-body --------- point at the beginning of the body
779 end-body --------- point at the end of the body"
780 (declare (indent 1))
781 `(let ((visited-p (or (null ,file)
782 (get-file-buffer (expand-file-name ,file))))
783 (point (point)) to-be-removed)
784 (save-window-excursion
785 (when ,file (find-file ,file))
786 (setq to-be-removed (current-buffer))
787 (goto-char (point-min))
788 (while (re-search-forward org-babel-src-block-regexp nil t)
789 (goto-char (match-beginning 0))
790 (let ((full-block (match-string 0))
791 (beg-block (match-beginning 0))
792 (end-block (match-end 0))
793 (lang (match-string 2))
794 (beg-lang (match-beginning 2))
795 (end-lang (match-end 2))
796 (switches (match-string 3))
797 (beg-switches (match-beginning 3))
798 (end-switches (match-end 3))
799 (header-args (match-string 4))
800 (beg-header-args (match-beginning 4))
801 (end-header-args (match-end 4))
802 (body (match-string 5))
803 (beg-body (match-beginning 5))
804 (end-body (match-end 5)))
805 ,@body
806 (goto-char end-block))))
807 (unless visited-p (kill-buffer to-be-removed))
808 (goto-char point)))
810 (defvar org-file-properties)
811 (defun org-babel-params-from-properties (&optional lang)
812 "Retrieve parameters specified as properties.
813 Return an association list of any source block params which
814 may be specified in the properties of the current outline entry."
815 (save-match-data
816 (let (val sym)
817 (delq nil
818 (mapcar
819 (lambda (header-arg)
820 (and (setq val
821 (or (condition-case nil
822 (org-entry-get (point) header-arg t)
823 (error nil))
824 (cdr (assoc header-arg org-file-properties))))
825 (cons (intern (concat ":" header-arg))
826 (org-babel-read val))))
827 (mapcar
828 'symbol-name
829 (append
830 org-babel-header-arg-names
831 (progn
832 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
833 (and (boundp sym) (eval sym))))))))))
835 (defun org-babel-params-from-buffer ()
836 "Retrieve per-buffer parameters.
837 Return an association list of any source block params which
838 may be specified at the top of the current buffer."
839 (or org-babel-current-buffer-properties
840 (setq org-babel-current-buffer-properties
841 (save-match-data
842 (save-excursion
843 (save-restriction
844 (widen)
845 (goto-char (point-min))
846 (when (re-search-forward
847 (org-make-options-regexp (list "BABEL")) nil t)
848 (org-babel-parse-header-arguments
849 (org-match-string-no-properties 2)))))))))
851 (defvar org-src-preserve-indentation)
852 (defun org-babel-parse-src-block-match ()
853 "Parse the results from a match of the `org-babel-src-block-regexp'."
854 (let* ((block-indentation (length (match-string 1)))
855 (lang (org-babel-clean-text-properties (match-string 2)))
856 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
857 (switches (match-string 3))
858 (body (org-babel-clean-text-properties (match-string 5)))
859 (preserve-indentation (or org-src-preserve-indentation
860 (string-match "-i\\>" switches))))
861 (list lang
862 ;; get block body less properties, protective commas, and indentation
863 (with-temp-buffer
864 (save-match-data
865 (insert (org-babel-strip-protective-commas body))
866 (unless preserve-indentation (org-do-remove-indentation))
867 (buffer-string)))
868 (org-babel-merge-params
869 org-babel-default-header-args
870 (org-babel-params-from-buffer)
871 (org-babel-params-from-properties lang)
872 (if (boundp lang-headers) (eval lang-headers) nil)
873 (org-babel-parse-header-arguments
874 (org-babel-clean-text-properties (or (match-string 4) ""))))
875 switches
876 block-indentation)))
878 (defun org-babel-parse-inline-src-block-match ()
879 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
880 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
881 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
882 (list lang
883 (org-babel-strip-protective-commas
884 (org-babel-clean-text-properties (match-string 5)))
885 (org-babel-merge-params
886 org-babel-default-inline-header-args
887 (org-babel-params-from-buffer)
888 (org-babel-params-from-properties lang)
889 (if (boundp lang-headers) (eval lang-headers) nil)
890 (org-babel-parse-header-arguments
891 (org-babel-clean-text-properties (or (match-string 4) "")))))))
893 (defun org-babel-parse-header-arguments (arg-string)
894 "Parse a string of header arguments returning an alist."
895 (if (> (length arg-string) 0)
896 (delq nil
897 (mapcar
898 (lambda (arg)
899 (if (string-match
900 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
901 arg)
902 (cons (intern (concat ":" (match-string 1 arg)))
903 (org-babel-read (org-babel-chomp (match-string 2 arg))))
904 (cons (intern (concat ":" arg)) nil)))
905 (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
907 (defun org-babel-process-params (params)
908 "Expand variables in PARAMS and add summary parameters."
909 (let* ((vars-and-names (org-babel-disassemble-tables
910 (mapcar (lambda (el)
911 (if (consp (cdr el))
912 (cdr el) (org-babel-ref-parse (cdr el))))
913 (org-babel-get-header params :var))
914 (cdr (assoc :hlines params))
915 (cdr (assoc :colnames params))
916 (cdr (assoc :rownames params))))
917 (result-params (append
918 (split-string (or (cdr (assoc :results params)) ""))
919 (cdr (assoc :result-params params)))))
920 (append
921 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
922 (list
923 (cons :colname-names (cadr vars-and-names))
924 (cons :rowname-names (caddr vars-and-names))
925 (cons :result-params result-params)
926 (cons :result-type (cond ((member "output" result-params) 'output)
927 ((member "value" result-params) 'value)
928 (t 'value))))
929 (org-babel-get-header params :var 'other))))
931 ;; row and column names
932 (defun org-babel-del-hlines (table)
933 "Remove all 'hlines from TABLE."
934 (remove 'hline table))
936 (defun org-babel-get-colnames (table)
937 "Return the column names of TABLE.
938 Return a cons cell, the `car' of which contains the TABLE less
939 colnames, and the `cdr' of which contains a list of the column
940 names."
941 (if (equal 'hline (nth 1 table))
942 (cons (cddr table) (car table))
943 (cons (cdr table) (car table))))
945 (defun org-babel-get-rownames (table)
946 "Return the row names of TABLE.
947 Return a cons cell, the `car' of which contains the TABLE less
948 colnames, and the `cdr' of which contains a list of the column
949 names. Note: this function removes any hlines in TABLE."
950 (flet ((trans (table) (apply #'mapcar* #'list table)))
951 (let* ((width (apply 'max
952 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
953 (table (trans (mapcar (lambda (row)
954 (if (not (equal row 'hline))
956 (setq row '())
957 (dotimes (n width)
958 (setq row (cons 'hline row)))
959 row))
960 table))))
961 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
962 (trans (cdr table)))
963 (remove 'hline (car table))))))
965 (defun org-babel-put-colnames (table colnames)
966 "Add COLNAMES to TABLE if they exist."
967 (if colnames (apply 'list colnames 'hline table) table))
969 (defun org-babel-put-rownames (table rownames)
970 "Add ROWNAMES to TABLE if they exist."
971 (if rownames
972 (mapcar (lambda (row)
973 (if (listp row)
974 (cons (or (pop rownames) "") row)
975 row)) table)
976 table))
978 (defun org-babel-pick-name (names selector)
979 "Select one out of an alist of row or column names.
980 SELECTOR can be either a list of names in which case those names
981 will be returned directly, or an index into the list NAMES in
982 which case the indexed names will be return."
983 (if (listp selector)
984 selector
985 (when names
986 (if (and selector (symbolp selector) (not (equal t selector)))
987 (cdr (assoc selector names))
988 (if (integerp selector)
989 (nth (- selector 1) names)
990 (cdr (car (last names))))))))
992 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
993 "Parse tables for further processing.
994 Process the variables in VARS according to the HLINES,
995 ROWNAMES and COLNAMES header arguments. Return a list consisting
996 of the vars, cnames and rnames."
997 (let (cnames rnames)
998 (list
999 (mapcar
1000 (lambda (var)
1001 (when (listp (cdr var))
1002 (when (and (not (equal colnames "no"))
1003 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1004 (not (member 'hline (cddr (cdr var)))))))
1005 (let ((both (org-babel-get-colnames (cdr var))))
1006 (setq cnames (cons (cons (car var) (cdr both))
1007 cnames))
1008 (setq var (cons (car var) (car both)))))
1009 (when (and rownames (not (equal rownames "no")))
1010 (let ((both (org-babel-get-rownames (cdr var))))
1011 (setq rnames (cons (cons (car var) (cdr both))
1012 rnames))
1013 (setq var (cons (car var) (car both)))))
1014 (when (and hlines (not (equal hlines "yes")))
1015 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1016 var)
1017 vars)
1018 cnames rnames)))
1020 (defun org-babel-reassemble-table (table colnames rownames)
1021 "Add column and row names to a table.
1022 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1023 to the table for reinsertion to org-mode."
1024 (if (listp table)
1025 ((lambda (table)
1026 (if (and colnames (listp (car table)) (= (length (car table))
1027 (length colnames)))
1028 (org-babel-put-colnames table colnames) table))
1029 (if (and rownames (= (length table) (length rownames)))
1030 (org-babel-put-rownames table rownames) table))
1031 table))
1033 (defun org-babel-where-is-src-block-head ()
1034 "Find where the current source block begins.
1035 Return the point at the beginning of the current source
1036 block. Specifically at the beginning of the #+BEGIN_SRC line.
1037 If the point is not on a source block then return nil."
1038 (let ((initial (point)) top bottom)
1040 (save-excursion ;; on a source name line
1041 (beginning-of-line 1)
1042 (and (looking-at org-babel-src-name-regexp) (forward-line 1)
1043 (looking-at org-babel-src-block-regexp)
1044 (point)))
1045 (save-excursion ;; on a #+begin_src line
1046 (beginning-of-line 1)
1047 (and (looking-at org-babel-src-block-regexp)
1048 (point)))
1049 (save-excursion ;; inside a src block
1050 (and
1051 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1052 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1053 (< top initial) (< initial bottom)
1054 (progn (goto-char top) (beginning-of-line 1)
1055 (looking-at org-babel-src-block-regexp))
1056 (point))))))
1058 ;;;###autoload
1059 (defun org-babel-goto-src-block-head ()
1060 "Go to the beginning of the current code block."
1061 (interactive)
1062 ((lambda (head)
1063 (if head (goto-char head) (error "not currently in a code block")))
1064 (org-babel-where-is-src-block-head)))
1066 ;;;###autoload
1067 (defun org-babel-goto-named-src-block (name)
1068 "Go to a named source-code block."
1069 (interactive
1070 (let ((completion-ignore-case t))
1071 (list (org-icompleting-read "source-block name: "
1072 (org-babel-src-block-names) nil t))))
1073 (let ((point (org-babel-find-named-block name)))
1074 (if point
1075 ;; taken from `org-open-at-point'
1076 (progn (goto-char point) (org-show-context))
1077 (message "source-code block '%s' not found in this buffer" name))))
1079 (defun org-babel-find-named-block (name)
1080 "Find a named source-code block.
1081 Return the location of the source block identified by source
1082 NAME, or nil if no such block exists. Set match data according to
1083 org-babel-named-src-block-regexp."
1084 (save-excursion
1085 (let ((case-fold-search t)
1086 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1087 (goto-char (point-min))
1088 (when (or (re-search-forward regexp nil t)
1089 (re-search-backward regexp nil t))
1090 (match-beginning 0)))))
1092 (defun org-babel-src-block-names (&optional file)
1093 "Returns the names of source blocks in FILE or the current buffer."
1094 (save-excursion
1095 (when file (find-file file)) (goto-char (point-min))
1096 (let (names)
1097 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1098 (setq names (cons (org-babel-clean-text-properties (match-string 3))
1099 names)))
1100 names)))
1102 ;;;###autoload
1103 (defun org-babel-goto-named-result (name)
1104 "Go to a named result."
1105 (interactive
1106 (let ((completion-ignore-case t))
1107 (list (org-icompleting-read "source-block name: "
1108 (org-babel-result-names) nil t))))
1109 (let ((point (org-babel-find-named-result name)))
1110 (if point
1111 ;; taken from `org-open-at-point'
1112 (progn (goto-char point) (org-show-context))
1113 (message "result '%s' not found in this buffer" name))))
1115 (defun org-babel-find-named-result (name)
1116 "Find a named result.
1117 Return the location of the result named NAME in the current
1118 buffer or nil if no such result exists."
1119 (save-excursion
1120 (goto-char (point-min))
1121 (when (re-search-forward
1122 (concat org-babel-result-regexp
1123 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1124 (beginning-of-line 0) (point))))
1126 (defun org-babel-result-names (&optional file)
1127 "Returns the names of results in FILE or the current buffer."
1128 (save-excursion
1129 (when file (find-file file)) (goto-char (point-min))
1130 (let (names)
1131 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1132 (setq names (cons (org-babel-clean-text-properties (match-string 4))
1133 names)))
1134 names)))
1136 ;;;###autoload
1137 (defun org-babel-next-src-block (&optional arg)
1138 "Jump to the next source block.
1139 With optional prefix argument ARG, jump forward ARG many source blocks."
1140 (interactive "P")
1141 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1142 (condition-case nil
1143 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1144 (error (error "No further code blocks")))
1145 (goto-char (match-beginning 0)) (org-show-context))
1147 ;;;###autoload
1148 (defun org-babel-previous-src-block (&optional arg)
1149 "Jump to the previous source block.
1150 With optional prefix argument ARG, jump backward ARG many source blocks."
1151 (interactive "P")
1152 (condition-case nil
1153 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1154 (error (error "No previous code blocks")))
1155 (goto-char (match-beginning 0)) (org-show-context))
1157 (defvar org-babel-load-languages)
1159 ;;;###autoload
1160 (defun org-babel-mark-block ()
1161 "Mark current src block"
1162 (interactive)
1163 ((lambda (head)
1164 (when head
1165 (save-excursion
1166 (goto-char head)
1167 (looking-at org-babel-src-block-regexp))
1168 (push-mark (match-end 5) nil t)
1169 (goto-char (match-beginning 5))))
1170 (org-babel-where-is-src-block-head)))
1172 (defun org-babel-demarcate-block (&optional arg)
1173 "Wrap or split the code in the region or on the point.
1174 When called from inside of a code block the current block is
1175 split. When called from outside of a code block a new code block
1176 is created. In both cases if the region is demarcated and if the
1177 region is not active then the point is demarcated."
1178 (interactive "P")
1179 (let ((info (org-babel-get-src-block-info 'light))
1180 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1181 (if info
1182 (mapc
1183 (lambda (place)
1184 (save-excursion
1185 (goto-char place)
1186 (let ((lang (nth 0 info))
1187 (indent (make-string (nth 5 info) ? )))
1188 (when (string-match "^[[:space:]]*$"
1189 (buffer-substring (point-at-bol)
1190 (point-at-eol)))
1191 (delete-region (point-at-bol) (point-at-eol)))
1192 (insert (concat (if (looking-at "^") "" "\n")
1193 indent "#+end_src\n"
1194 (if arg stars indent) "\n"
1195 indent "#+begin_src " lang
1196 (if (looking-at "[\n\r]") "" "\n")))))
1197 (move-end-of-line 2))
1198 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1199 (let ((start (point))
1200 (lang (org-icompleting-read "Lang: "
1201 (mapcar (lambda (el) (symbol-name (car el)))
1202 org-babel-load-languages)))
1203 (body (delete-and-extract-region
1204 (if (region-active-p) (mark) (point)) (point))))
1205 (insert (concat (if (looking-at "^") "" "\n")
1206 (if arg (concat stars "\n") "")
1207 "#+begin_src " lang "\n"
1208 body
1209 (if (or (= (length body) 0)
1210 (string-match "[\r\n]$" body)) "" "\n")
1211 "#+end_src\n"))
1212 (goto-char start) (move-end-of-line 1)))))
1214 (defvar org-babel-lob-one-liner-regexp)
1215 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1216 "Find where the current source block results begin.
1217 Return the point at the beginning of the result of the current
1218 source block. Specifically at the beginning of the results line.
1219 If no result exists for this block then create a results line
1220 following the source block."
1221 (save-excursion
1222 (let* ((on-lob-line (progn (beginning-of-line 1)
1223 (looking-at org-babel-lob-one-liner-regexp)))
1224 (name (if on-lob-line
1225 (nth 0 (org-babel-lob-get-info))
1226 (nth 4 (or info (org-babel-get-src-block-info)))))
1227 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1228 found beg end)
1229 (when head (goto-char head))
1230 (setq
1231 found ;; was there a result (before we potentially insert one)
1233 (and
1234 ;; named results:
1235 ;; - return t if it is found, else return nil
1236 ;; - if it does not need to be rebuilt, then don't set end
1237 ;; - if it does need to be rebuilt then do set end
1238 name (setq beg (org-babel-find-named-result name))
1239 (prog1 beg
1240 (when (and hash (not (string= hash (match-string 3))))
1241 (goto-char beg) (setq end beg) ;; beginning of result
1242 (forward-line 1)
1243 (delete-region end (org-babel-result-end)) nil)))
1244 (and
1245 ;; unnamed results:
1246 ;; - return t if it is found, else return nil
1247 ;; - if it is found, and the hash doesn't match, delete and set end
1248 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1249 (progn (end-of-line 1)
1250 (if (eobp) (insert "\n") (forward-char 1))
1251 (setq end (point))
1252 (or (and (not name)
1253 (progn ;; unnamed results line already exists
1254 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1255 (beginning-of-line 1)
1256 (looking-at
1257 (concat org-babel-result-regexp "\n")))
1258 (prog1 (point)
1259 ;; must remove and rebuild if hash!=old-hash
1260 (if (and hash (not (string= hash (match-string 3))))
1261 (prog1 nil
1262 (forward-line 1)
1263 (delete-region
1264 end (org-babel-result-end)))
1265 (setq end nil)))))))))
1266 (if (and insert end)
1267 (progn
1268 (goto-char end)
1269 (unless beg
1270 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1271 (insert (concat
1272 (if indent
1273 (mapconcat
1274 (lambda (el) " ")
1275 (org-number-sequence 1 indent) "")
1277 "#+results"
1278 (when hash (concat "["hash"]"))
1280 (when name (concat " " name)) "\n"))
1281 (unless beg (insert "\n") (backward-char))
1282 (beginning-of-line 0)
1283 (if hash (org-babel-hide-hash))
1284 (point))
1285 found))))
1287 (defvar org-block-regexp)
1288 (defun org-babel-read-result ()
1289 "Read the result at `point' into emacs-lisp."
1290 (let ((case-fold-search t) result-string)
1291 (cond
1292 ((org-at-table-p) (org-babel-read-table))
1293 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1294 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1295 ((looking-at "^[ \t]*: ")
1296 (setq result-string
1297 (org-babel-trim
1298 (mapconcat (lambda (line)
1299 (if (and (> (length line) 1)
1300 (string-match "^[ \t]*: \\(.+\\)" line))
1301 (match-string 1 line)
1302 line))
1303 (split-string
1304 (buffer-substring
1305 (point) (org-babel-result-end)) "[\r\n]+")
1306 "\n")))
1307 (or (org-babel-number-p result-string) result-string))
1308 ((looking-at org-babel-result-regexp)
1309 (save-excursion (forward-line 1) (org-babel-read-result))))))
1311 (defun org-babel-read-table ()
1312 "Read the table at `point' into emacs-lisp."
1313 (mapcar (lambda (row)
1314 (if (and (symbolp row) (equal row 'hline)) row
1315 (mapcar #'org-babel-read row)))
1316 (org-table-to-lisp)))
1318 (defvar org-link-types-re)
1319 (defun org-babel-read-link ()
1320 "Read the link at `point' into emacs-lisp.
1321 If the path of the link is a file path it is expanded using
1322 `expand-file-name'."
1323 (let* ((case-fold-search t)
1324 (raw (and (looking-at org-bracket-link-regexp)
1325 (org-babel-clean-text-properties (match-string 1))))
1326 (type (and (string-match org-link-types-re raw)
1327 (match-string 1 raw))))
1328 (cond
1329 ((not type) (expand-file-name raw))
1330 ((string= type "file")
1331 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1332 (expand-file-name (match-string 2 raw))))
1333 (t raw))))
1335 (defun org-babel-insert-result
1336 (result &optional result-params info hash indent lang)
1337 "Insert RESULT into the current buffer.
1338 By default RESULT is inserted after the end of the
1339 current source block. With optional argument RESULT-PARAMS
1340 controls insertion of results in the org-mode file.
1341 RESULT-PARAMS can take the following values...
1343 replace - (default option) insert results after the source block
1344 replacing any previously inserted results
1346 silent -- no results are inserted
1348 file ---- the results are interpreted as a file path, and are
1349 inserted into the buffer using the Org-mode file syntax
1351 raw ----- results are added directly to the org-mode file. This
1352 is a good option if you code block will output org-mode
1353 formatted text.
1355 org ----- similar in effect to raw, only the results are wrapped
1356 in an org code block. Similar to the raw option, on
1357 export the results will be interpreted as org-formatted
1358 text, however by wrapping the results in an org code
1359 block they can be replaced upon re-execution of the
1360 code block.
1362 html ---- results are added inside of a #+BEGIN_HTML block. This
1363 is a good option if you code block will output html
1364 formatted text.
1366 latex --- results are added inside of a #+BEGIN_LATEX block.
1367 This is a good option if you code block will output
1368 latex formatted text.
1370 code ---- the results are extracted in the syntax of the source
1371 code of the language being evaluated and are added
1372 inside of a #+BEGIN_SRC block with the source-code
1373 language set appropriately. Note this relies on the
1374 optional LANG argument."
1375 (if (stringp result)
1376 (progn
1377 (setq result (org-babel-clean-text-properties result))
1378 (when (member "file" result-params)
1379 (setq result (org-babel-result-to-file result))))
1380 (unless (listp result) (setq result (format "%S" result))))
1381 (if (and result-params (member "silent" result-params))
1382 (progn
1383 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1384 result)
1385 (when (and (stringp result) ;; ensure results end in a newline
1386 (> (length result) 0)
1387 (not (or (string-equal (substring result -1) "\n")
1388 (string-equal (substring result -1) "\r"))))
1389 (setq result (concat result "\n")))
1390 (save-excursion
1391 (let ((existing-result (org-babel-where-is-src-block-result
1392 t info hash indent))
1393 (results-switches
1394 (cdr (assoc :results_switches (nth 2 info))))
1395 beg end)
1396 (if (not existing-result)
1397 (setq beg (point))
1398 (goto-char existing-result)
1399 (save-excursion
1400 (re-search-forward "#" nil t)
1401 (setq indent (- (current-column) 1)))
1402 (forward-line 1)
1403 (setq beg (point))
1404 (cond
1405 ((member "replace" result-params)
1406 (delete-region (point) (org-babel-result-end)))
1407 ((member "append" result-params)
1408 (goto-char (org-babel-result-end)) (setq beg (point)))
1409 ((member "prepend" result-params) ;; already there
1411 (setq results-switches
1412 (if results-switches (concat " " results-switches) ""))
1413 (cond
1414 ;; do nothing for an empty result
1415 ((= (length result) 0))
1416 ;; assume the result is a table if it's not a string
1417 ((not (stringp result))
1418 (insert (concat (orgtbl-to-orgtbl
1419 (if (or (eq 'hline (car result))
1420 (and (listp (car result))
1421 (listp (cdr (car result)))))
1422 result (list result))
1423 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1424 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1425 ((member "file" result-params)
1426 (insert result))
1427 ((member "html" result-params)
1428 (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
1429 results-switches result)))
1430 ((member "latex" result-params)
1431 (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
1432 results-switches result)))
1433 ((member "code" result-params)
1434 (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
1435 (or lang "none") results-switches result)))
1436 ((member "org" result-params)
1437 (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result)))
1438 ((member "raw" result-params)
1439 (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
1441 (org-babel-examplize-region
1442 (point) (progn (insert result) (point)) results-switches)))
1443 ;; possibly indent the results to match the #+results line
1444 (setq end (if (listp result) (org-table-end) (point)))
1445 (when (and indent (> indent 0)
1446 ;; in this case `table-align' does the work for us
1447 (not (and (listp result)
1448 (member "append" result-params))))
1449 (indent-rigidly beg end indent))))
1450 (if (= (length result) 0)
1451 (if (member "value" result-params)
1452 (message "No result returned by source block")
1453 (message "Source block produced no output"))
1454 (message "finished"))))
1456 (defun org-babel-remove-result (&optional info)
1457 "Remove the result of the current source block."
1458 (interactive)
1459 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1460 (when location
1461 (save-excursion
1462 (goto-char location) (setq start (point)) (forward-line 1)
1463 (delete-region start (org-babel-result-end))))))
1465 (defun org-babel-result-end ()
1466 "Return the point at the end of the current set of results"
1467 (save-excursion
1468 (if (org-at-table-p)
1469 (progn (goto-char (org-table-end)) (point))
1470 (let ((case-fold-search t))
1471 (cond
1472 ((looking-at "[ \t]*#\\+begin_latex")
1473 (re-search-forward "[ \t]*#\\+end_latex" nil t)
1474 (forward-line 1))
1475 ((looking-at "[ \t]*#\\+begin_html")
1476 (re-search-forward "[ \t]*#\\+end_html" nil t)
1477 (forward-line 1))
1478 ((looking-at "[ \t]*#\\+begin_example")
1479 (re-search-forward "[ \t]*#\\+end_example" nil t)
1480 (forward-line 1))
1481 ((looking-at "[ \t]*#\\+begin_src")
1482 (re-search-forward "[ \t]*#\\+end_src" nil t)
1483 (forward-line 1))
1484 (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1485 (forward-line 1))))))
1486 (point))))
1488 (defun org-babel-result-to-file (result)
1489 "Convert RESULT into an `org-mode' link.
1490 If the `default-directory' is different from the containing
1491 file's directory then expand relative links."
1492 (format
1493 "[[file:%s]]"
1494 (if (and default-directory
1495 buffer-file-name
1496 (not (string= (expand-file-name default-directory)
1497 (expand-file-name
1498 (file-name-directory buffer-file-name)))))
1499 (expand-file-name result default-directory)
1500 result)))
1502 (defun org-babel-examplize-region (beg end &optional results-switches)
1503 "Comment out region using the ': ' org example quote."
1504 (interactive "*r")
1505 (let ((size (count-lines beg end)))
1506 (save-excursion
1507 (cond ((= size 0)
1508 (error (concat "This should not be impossible:"
1509 "a newline was appended to result if missing")))
1510 ((< size org-babel-min-lines-for-block-output)
1511 (goto-char beg)
1512 (dotimes (n size)
1513 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1515 (goto-char beg)
1516 (insert (if results-switches
1517 (format "#+begin_example%s\n" results-switches)
1518 "#+begin_example\n"))
1519 (forward-char (- end beg))
1520 (insert "#+end_example\n"))))))
1522 (defun org-babel-update-block-body (new-body)
1523 "Update the body of the current code block to NEW-BODY."
1524 (if (not (org-babel-where-is-src-block-head))
1525 (error "not in source block")
1526 (save-match-data
1527 (replace-match (concat (org-babel-trim new-body) "\n") nil nil nil 5))
1528 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1530 (defun org-babel-merge-params (&rest plists)
1531 "Combine all parameter association lists in PLISTS.
1532 Later elements of PLISTS override the values of previous element.
1533 This takes into account some special considerations for certain
1534 parameters when merging lists."
1535 (let ((results-exclusive-groups
1536 '(("file" "vector" "table" "scalar" "raw" "org"
1537 "html" "latex" "code" "pp")
1538 ("replace" "silent" "append" "prepend")
1539 ("output" "value")))
1540 (exports-exclusive-groups
1541 '(("code" "results" "both" "none")))
1542 params results exports tangle noweb cache vars shebang comments)
1543 (flet ((e-merge (exclusive-groups &rest result-params)
1544 ;; maintain exclusivity of mutually exclusive parameters
1545 (let (output)
1546 (mapc (lambda (new-params)
1547 (mapc (lambda (new-param)
1548 (mapc (lambda (exclusive-group)
1549 (when (member new-param exclusive-group)
1550 (mapcar (lambda (excluded-param)
1551 (setq output
1552 (delete
1553 excluded-param
1554 output)))
1555 exclusive-group)))
1556 exclusive-groups)
1557 (setq output (org-uniquify
1558 (cons new-param output))))
1559 new-params))
1560 result-params)
1561 output)))
1562 (mapc
1563 (lambda (plist)
1564 (mapc
1565 (lambda (pair)
1566 (case (car pair)
1567 (:var
1568 (let ((name (if (listp (cdr pair))
1569 (cadr pair)
1570 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1571 (cdr pair))
1572 (intern (match-string 1 (cdr pair)))))))
1573 (when name
1574 (setq vars
1575 (cons (cons name pair)
1576 (if (member name (mapcar #'car vars))
1577 (delq nil
1578 (mapcar
1579 (lambda (p) (unless (equal (car p) name) p))
1580 vars))
1581 vars))))))
1582 (:results
1583 (setq results (e-merge results-exclusive-groups
1584 results (split-string (cdr pair)))))
1585 (:file
1586 (when (cdr pair)
1587 (setq results (e-merge results-exclusive-groups
1588 results '("file")))
1589 (unless (or (member "both" exports)
1590 (member "none" exports)
1591 (member "code" exports))
1592 (setq exports (e-merge exports-exclusive-groups
1593 exports '("results"))))
1594 (setq params (cons pair (assq-delete-all (car pair) params)))))
1595 (:exports
1596 (setq exports (e-merge exports-exclusive-groups
1597 exports (split-string (cdr pair)))))
1598 (:tangle ;; take the latest -- always overwrite
1599 (setq tangle (or (list (cdr pair)) tangle)))
1600 (:noweb
1601 (setq noweb (e-merge '(("yes" "no")) noweb
1602 (split-string (or (cdr pair) "")))))
1603 (:cache
1604 (setq cache (e-merge '(("yes" "no")) cache
1605 (split-string (or (cdr pair) "")))))
1606 (:shebang ;; take the latest -- always overwrite
1607 (setq shebang (or (list (cdr pair)) shebang)))
1608 (:comments
1609 (setq comments (e-merge '(("yes" "no")) comments
1610 (split-string (or (cdr pair) "")))))
1611 (t ;; replace: this covers e.g. :session
1612 (setq params (cons pair (assq-delete-all (car pair) params))))))
1613 plist))
1614 plists))
1615 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1616 (cons (cons :comments (mapconcat 'identity comments " "))
1617 (cons (cons :shebang (mapconcat 'identity shebang " "))
1618 (cons (cons :cache (mapconcat 'identity cache " "))
1619 (cons (cons :noweb (mapconcat 'identity noweb " "))
1620 (cons (cons :tangle (mapconcat 'identity tangle " "))
1621 (cons (cons :exports
1622 (mapconcat 'identity exports " "))
1623 (cons
1624 (cons :results
1625 (mapconcat 'identity results " "))
1626 params)))))))))
1628 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1629 "Expand Noweb references in the body of the current source code block.
1631 For example the following reference would be replaced with the
1632 body of the source-code block named 'example-block'.
1634 <<example-block>>
1636 Note that any text preceding the <<foo>> construct on a line will
1637 be interposed between the lines of the replacement text. So for
1638 example if <<foo>> is placed behind a comment, then the entire
1639 replacement text will also be commented.
1641 This function must be called from inside of the buffer containing
1642 the source-code block which holds BODY.
1644 In addition the following syntax can be used to insert the
1645 results of evaluating the source-code block named 'example-block'.
1647 <<example-block()>>
1649 Any optional arguments can be passed to example-block by placing
1650 the arguments inside the parenthesis following the convention
1651 defined by `org-babel-lob'. For example
1653 <<example-block(a=9)>>
1655 would set the value of argument \"a\" equal to \"9\". Note that
1656 these arguments are not evaluated in the current source-code
1657 block but are passed literally to the \"example-block\"."
1658 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1659 (info (or info (org-babel-get-src-block-info)))
1660 (lang (nth 0 info))
1661 (body (nth 1 info))
1662 (new-body "") index source-name evaluate prefix)
1663 (flet ((nb-add (text)
1664 (setq new-body (concat new-body text))))
1665 (with-temp-buffer
1666 (insert body) (goto-char (point-min))
1667 (setq index (point))
1668 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1669 (save-match-data (setf source-name (match-string 1)))
1670 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1671 (save-match-data
1672 (setq prefix
1673 (buffer-substring (match-beginning 0)
1674 (save-excursion
1675 (beginning-of-line 1) (point)))))
1676 ;; add interval to new-body (removing noweb reference)
1677 (goto-char (match-beginning 0))
1678 (nb-add (buffer-substring index (point)))
1679 (goto-char (match-end 0))
1680 (setq index (point))
1681 (nb-add (with-current-buffer parent-buffer
1682 (mapconcat ;; interpose PREFIX between every line
1683 #'identity
1684 (split-string
1685 (if evaluate
1686 (let ((raw (org-babel-ref-resolve source-name)))
1687 (if (stringp raw) raw (format "%S" raw)))
1688 (save-restriction
1689 (widen)
1690 (let ((point (org-babel-find-named-block
1691 source-name)))
1692 (if point
1693 (save-excursion
1694 (goto-char point)
1695 (org-babel-trim
1696 (org-babel-expand-noweb-references
1697 (org-babel-get-src-block-info))))
1698 ;; optionally raise an error if named
1699 ;; source-block doesn't exist
1700 (if (member lang org-babel-noweb-error-langs)
1701 (error "%s"
1702 (concat
1703 "<<" source-name ">> "
1704 "could not be resolved (see "
1705 "`org-babel-noweb-error-langs')"))
1706 "")))))
1707 "[\n\r]") (concat "\n" prefix)))))
1708 (nb-add (buffer-substring index (point-max)))))
1709 new-body))
1711 (defun org-babel-clean-text-properties (text)
1712 "Strip all properties from text return."
1713 (when text
1714 (set-text-properties 0 (length text) nil text) text))
1716 (defun org-babel-strip-protective-commas (body)
1717 "Strip protective commas from bodies of source blocks."
1718 (replace-regexp-in-string "^,#" "#" body))
1720 (defun org-babel-read (cell)
1721 "Convert the string value of CELL to a number if appropriate.
1722 Otherwise if cell looks like lisp (meaning it starts with a
1723 \"(\" or a \"'\") then read it as lisp, otherwise return it
1724 unmodified as a string.
1726 This is taken almost directly from `org-read-prop'."
1727 (if (and (stringp cell) (not (equal cell "")))
1728 (or (org-babel-number-p cell)
1729 (if (or (equal "(" (substring cell 0 1))
1730 (equal "'" (substring cell 0 1))
1731 (equal "`" (substring cell 0 1)))
1732 (eval (read cell))
1733 (progn (set-text-properties 0 (length cell) nil cell) cell)))
1734 cell))
1736 (defun org-babel-number-p (string)
1737 "If STRING represents a number return it's value."
1738 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1739 (= (length (substring string (match-beginning 0)
1740 (match-end 0)))
1741 (length string)))
1742 (string-to-number string)))
1744 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1745 "Read the results located at FILE-NAME into an elisp table.
1746 If the table is trivial, then return it as a scalar."
1747 (let (result)
1748 (save-window-excursion
1749 (with-temp-buffer
1750 (condition-case nil
1751 (progn
1752 (org-table-import file-name separator)
1753 (delete-file file-name)
1754 (setq result (mapcar (lambda (row)
1755 (mapcar #'org-babel-string-read row))
1756 (org-table-to-lisp))))
1757 (error nil)))
1758 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1759 (if (consp (car result))
1760 (if (null (cdr (car result)))
1761 (caar result)
1762 result)
1763 (car result))
1764 result))))
1766 (defun org-babel-string-read (cell)
1767 "Strip nested \"s from around strings."
1768 (org-babel-read (or (and (stringp cell)
1769 (string-match "\\\"\\(.+\\)\\\"" cell)
1770 (match-string 1 cell))
1771 cell)))
1773 (defun org-babel-reverse-string (string)
1774 "Return the reverse of STRING."
1775 (apply 'string (reverse (string-to-list string))))
1777 (defun org-babel-chomp (string &optional regexp)
1778 "Strip trailing spaces and carriage returns from STRING.
1779 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1780 overwritten by specifying a regexp as a second argument."
1781 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1782 (while (and (> (length string) 0)
1783 (string-match regexp (substring string -1)))
1784 (setq string (substring string 0 -1)))
1785 string))
1787 (defun org-babel-trim (string &optional regexp)
1788 "Strip leading and trailing spaces and carriage returns from STRING.
1789 Like `org-babel-chomp' only it runs on both the front and back
1790 of the string."
1791 (org-babel-chomp (org-babel-reverse-string
1792 (org-babel-chomp (org-babel-reverse-string string) regexp))
1793 regexp))
1795 (defvar org-babel-org-babel-call-process-region-original nil)
1796 (defun org-babel-tramp-handle-call-process-region
1797 (start end program &optional delete buffer display &rest args)
1798 "Use tramp to handle call-process-region.
1799 Fixes a bug in `tramp-handle-call-process-region'."
1800 (if (and (featurep 'tramp) (file-remote-p default-directory))
1801 (let ((tmpfile (tramp-compat-make-temp-file "")))
1802 (write-region start end tmpfile)
1803 (when delete (delete-region start end))
1804 (unwind-protect
1805 ;; (apply 'call-process program tmpfile buffer display args)
1806 ;; bug in tramp
1807 (apply 'process-file program tmpfile buffer display args)
1808 (delete-file tmpfile)))
1809 ;; org-babel-call-process-region-original is the original emacs
1810 ;; definition. It is in scope from the let binding in
1811 ;; org-babel-execute-src-block
1812 (apply org-babel-call-process-region-original
1813 start end program delete buffer display args)))
1815 (defun org-babel-local-file-name (file)
1816 "Return the local name component of FILE."
1817 (if (file-remote-p file)
1818 (let (localname)
1819 (with-parsed-tramp-file-name file nil
1820 localname))
1821 file))
1823 (defun org-babel-process-file-name (name &optional no-quote-p)
1824 "Prepare NAME to be used in an external process.
1825 If NAME specifies a remote location, the remote portion of the
1826 name is removed, since in that case the process will be executing
1827 remotely. The file name is then processed by
1828 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
1829 the file name is additionally processed by
1830 `shell-quote-argument'"
1831 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
1832 (expand-file-name (org-babel-local-file-name name))))
1834 (defvar org-babel-temporary-directory)
1835 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
1836 (defvar org-babel-temporary-directory
1837 (or (and (boundp 'org-babel-temporary-directory)
1838 (file-exists-p org-babel-temporary-directory)
1839 org-babel-temporary-directory)
1840 (make-temp-file "babel-" t))
1841 "Directory to hold temporary files created to execute code blocks.
1842 Used by `org-babel-temp-file'. This directory will be removed on
1843 Emacs shutdown."))
1845 (defun org-babel-temp-file (prefix &optional suffix)
1846 "Create a temporary file in the `org-babel-temporary-directory'.
1847 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
1848 value of `temporary-file-directory' temporarily set to the value
1849 of `org-babel-temporary-directory'."
1850 (if (file-remote-p default-directory)
1851 (make-temp-file
1852 (concat (file-remote-p default-directory)
1853 (expand-file-name
1854 prefix temporary-file-directory)
1855 nil suffix))
1856 (let ((temporary-file-directory
1857 (or (and (file-exists-p org-babel-temporary-directory)
1858 org-babel-temporary-directory)
1859 temporary-file-directory)))
1860 (make-temp-file prefix nil suffix))))
1862 (defun org-babel-remove-temporary-directory ()
1863 "Remove `org-babel-temporary-directory' on Emacs shutdown."
1864 (when (and (boundp 'org-babel-temporary-directory)
1865 (file-exists-p org-babel-temporary-directory))
1866 ;; taken from `delete-directory' in files.el
1867 (mapc (lambda (file)
1868 ;; This test is equivalent to
1869 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
1870 ;; but more efficient
1871 (if (eq t (car (file-attributes file)))
1872 (delete-directory file)
1873 (delete-file file)))
1874 ;; We do not want to delete "." and "..".
1875 (directory-files org-babel-temporary-directory 'full
1876 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
1877 (delete-directory org-babel-temporary-directory)))
1879 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
1881 (provide 'ob)
1883 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
1885 ;;; ob.el ends here