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