*** empty log message ***
[bpt/emacs.git] / lisp / eshell / esh-io.el
CommitLineData
60370d40 1;;; esh-io.el --- I/O management
affbf647 2
5b423d48 3;; Copyright (C) 1999, 2000, 2005 Free Software Foundation
affbf647 4
7de5b421
GM
5;; Author: John Wiegley <johnw@gnu.org>
6
affbf647
GM
7;; This file is part of GNU Emacs.
8
9;; GNU Emacs is free software; you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
11;; the Free Software Foundation; either version 2, or (at your option)
12;; any later version.
13
14;; GNU Emacs is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
18
19;; You should have received a copy of the GNU General Public License
20;; along with GNU Emacs; see the file COPYING. If not, write to the
21;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22;; Boston, MA 02111-1307, USA.
23
24(provide 'esh-io)
25
26(eval-when-compile (require 'esh-maint))
27
28(defgroup eshell-io nil
29 "Eshell's I/O management code provides a scheme for treating many
30different kinds of objects -- symbols, files, buffers, etc. -- as
31though they were files."
32 :tag "I/O management"
33 :group 'eshell)
34
35;;; Commentary:
36
37;; At the moment, only output redirection is supported in Eshell. To
38;; use input redirection, the following syntax will work, assuming
39;; that the command after the pipe is always an external command:
40;;
41;; cat <file> | <command>
42;;
43;; Otherwise, output redirection and piping are provided in a manner
44;; consistent with most shells. Therefore, only unique features are
45;; mentioned here.
46;;
47;;;_* Insertion
48;;
49;; To insert at the location of point in a buffer, use '>>>':
50;;
51;; echo alpha >>> #<buffer *scratch*>;
52;;
53;;;_* Pseudo-devices
54;;
55;; A few pseudo-devices are provided, since Emacs cannot write
56;; directly to a UNIX device file:
57;;
58;; echo alpha > /dev/null ; the bit bucket
59;; echo alpha > /dev/kill ; set the kill ring
60;; echo alpha >> /dev/clip ; append to the clipboard
61;;
62;;;_* Multiple output targets
63;;
64;; Eshell can write to multiple output targets, including pipes.
65;; Example:
66;;
67;; (+ 1 2) > a > b > c ; prints number to all three files
68;; (+ 1 2) > a | wc ; prints to 'a', and pipes to 'wc'
69
70;;; User Variables:
71
72(defcustom eshell-io-load-hook '(eshell-io-initialize)
73 "*A hook that gets run when `eshell-io' is loaded."
74 :type 'hook
75 :group 'eshell-io)
76
77(defcustom eshell-number-of-handles 3
78 "*The number of file handles that eshell supports.
79Currently this is standard input, output and error. But even all of
80these Emacs does not currently support with asynchronous processes
81\(which is what eshell uses so that you can continue doing work in
82other buffers) ."
83 :type 'integer
84 :group 'eshell-io)
85
86(defcustom eshell-output-handle 1
87 "*The index of the standard output handle."
88 :type 'integer
89 :group 'eshell-io)
90
91(defcustom eshell-error-handle 2
92 "*The index of the standard error handle."
93 :type 'integer
94 :group 'eshell-io)
95
96(defcustom eshell-buffer-shorthand nil
97 "*If non-nil, a symbol name can be used for a buffer in redirection.
98If nil, redirecting to a buffer requires buffer name syntax. If this
99variable is set, redirection directly to Lisp symbols will be
100impossible.
101
102Example:
103
104 echo hello > '*scratch* ; works if `eshell-buffer-shorthand' is t
105 echo hello > #<buffer *scratch*> ; always works"
106 :type 'boolean
107 :group 'eshell-io)
108
109(defcustom eshell-print-queue-size 5
110 "*The size of the print queue, for doing buffered printing.
111This is basically a speed enhancement, to avoid blocking the Lisp code
112from executing while Emacs is redisplaying."
113 :type 'integer
114 :group 'eshell-io)
115
116(defcustom eshell-virtual-targets
117 '(("/dev/eshell" eshell-interactive-print nil)
118 ("/dev/kill" (lambda (mode)
119 (if (eq mode 'overwrite)
120 (kill-new ""))
121 'eshell-kill-append) t)
122 ("/dev/clip" (lambda (mode)
123 (if (eq mode 'overwrite)
124 (let ((x-select-enable-clipboard t))
125 (kill-new "")))
126 'eshell-clipboard-append) t))
127 "*Map virtual devices name to Emacs Lisp functions.
128If the user specifies any of the filenames above as a redirection
129target, the function in the second element will be called.
130
131If the third element is non-nil, the redirection mode is passed as an
132argument (which is the symbol `overwrite', `append' or `insert'), and
133the function is expected to return another function -- which is the
134output function. Otherwise, the second element itself is the output
135function.
136
ca7aae91
JW
137The output function is then called repeatedly with single strings,
138which represents successive pieces of the output of the command, until nil
affbf647
GM
139is passed, meaning EOF.
140
141NOTE: /dev/null is handled specially as a virtual target, and should
142not be added to this variable."
143 :type '(repeat
144 (list (string :tag "Target")
145 function
146 (choice (const :tag "Func returns output-func" t)
147 (const :tag "Func is output-func" nil))))
148 :group 'eshell-io)
149
150(put 'eshell-virtual-targets 'risky-local-variable t)
151
152;;; Internal Variables:
153
154(defvar eshell-current-handles nil)
155
156(defvar eshell-last-command-status 0
157 "The exit code from the last command. 0 if successful.")
158
159(defvar eshell-last-command-result nil
160 "The result of the last command. Not related to success.")
161
162(defvar eshell-output-file-buffer nil
163 "If non-nil, the current buffer is a file output buffer.")
164
165(defvar eshell-print-count)
166(defvar eshell-current-redirections)
167
168;;; Functions:
169
170(defun eshell-io-initialize ()
171 "Initialize the I/O subsystem code."
affbf647
GM
172 (add-hook 'eshell-parse-argument-hook
173 'eshell-parse-redirection nil t)
174 (make-local-variable 'eshell-current-redirections)
affbf647
GM
175 (add-hook 'eshell-pre-rewrite-command-hook
176 'eshell-strip-redirections nil t)
affbf647
GM
177 (add-hook 'eshell-post-rewrite-command-hook
178 'eshell-apply-redirections nil t))
179
180(defun eshell-parse-redirection ()
181 "Parse an output redirection, such as '2>'."
182 (if (and (not eshell-current-quoted)
183 (looking-at "\\([0-9]\\)?\\(<\\|>+\\)&?\\([0-9]\\)?\\s-*"))
184 (if eshell-current-argument
185 (eshell-finish-arg)
186 (let ((sh (match-string 1))
187 (oper (match-string 2))
188; (th (match-string 3))
189 )
190 (if (string= oper "<")
191 (error "Eshell does not support input redirection"))
192 (eshell-finish-arg
193 (prog1
194 (list 'eshell-set-output-handle
195 (or (and sh (string-to-int sh)) 1)
196 (list 'quote
197 (aref [overwrite append insert]
198 (1- (length oper)))))
199 (goto-char (match-end 0))))))))
200
201(defun eshell-strip-redirections (terms)
202 "Rewrite any output redirections in TERMS."
203 (setq eshell-current-redirections (list t))
204 (let ((tl terms)
205 (tt (cdr terms)))
206 (while tt
207 (if (not (and (consp (car tt))
208 (eq (caar tt) 'eshell-set-output-handle)))
209 (setq tt (cdr tt)
210 tl (cdr tl))
211 (unless (cdr tt)
212 (error "Missing redirection target"))
213 (nconc eshell-current-redirections
214 (list (list 'ignore
215 (append (car tt) (list (cadr tt))))))
216 (setcdr tl (cddr tt))
217 (setq tt (cddr tt))))
218 (setq eshell-current-redirections
219 (cdr eshell-current-redirections))))
220
221(defun eshell-apply-redirections (cmdsym)
222 "Apply any redirection which were specified for COMMAND."
223 (if eshell-current-redirections
224 (set cmdsym
225 (append (list 'progn)
226 eshell-current-redirections
227 (list (symbol-value cmdsym))))))
228
229(defun eshell-create-handles
230 (standard-output output-mode &optional standard-error error-mode)
231 "Create a new set of file handles for a command.
232The default location for standard output and standard error will go to
ca7aae91
JW
233STANDARD-OUTPUT and STANDARD-ERROR, respectively.
234OUTPUT-MODE and ERROR-MODE are either `overwrite', `append' or `insert';
235a nil value of mode defaults to `insert'."
affbf647
GM
236 (let ((handles (make-vector eshell-number-of-handles nil))
237 (output-target (eshell-get-target standard-output output-mode))
238 (error-target (eshell-get-target standard-error error-mode)))
239 (aset handles eshell-output-handle (cons output-target 1))
240 (if standard-error
241 (aset handles eshell-error-handle (cons error-target 1))
242 (aset handles eshell-error-handle (cons output-target 1)))
243 handles))
244
245(defun eshell-protect-handles (handles)
246 "Protect the handles in HANDLES from a being closed."
247 (let ((idx 0))
248 (while (< idx eshell-number-of-handles)
249 (if (aref handles idx)
250 (setcdr (aref handles idx)
251 (1+ (cdr (aref handles idx)))))
252 (setq idx (1+ idx))))
253 handles)
254
255(defun eshell-close-target (target status)
256 "Close an output TARGET, passing STATUS as the result.
257STATUS should be non-nil on successful termination of the output."
258 (cond
259 ((symbolp target) nil)
260
261 ;; If we were redirecting to a file, save the file and close the
262 ;; buffer.
263 ((markerp target)
264 (let ((buf (marker-buffer target)))
265 (when buf ; somebody's already killed it!
266 (save-current-buffer
267 (set-buffer buf)
268 (when eshell-output-file-buffer
269 (save-buffer)
270 (when (eq eshell-output-file-buffer t)
271 (or status (set-buffer-modified-p nil))
272 (kill-buffer buf)))))))
273
274 ;; If we're redirecting to a process (via a pipe, or process
275 ;; redirection), send it EOF so that it knows we're finished.
ca7aae91 276 ((eshell-processp target)
affbf647
GM
277 (if (eq (process-status target) 'run)
278 (process-send-eof target)))
279
280 ;; A plain function redirection needs no additional arguments
281 ;; passed.
282 ((functionp target)
283 (funcall target status))
284
285 ;; But a more complicated function redirection (which can only
286 ;; happen with aliases at the moment) has arguments that need to be
287 ;; passed along with it.
288 ((consp target)
289 (apply (car target) status (cdr target)))))
290
291(defun eshell-close-handles (exit-code &optional result handles)
292 "Close all of the current handles, taking refcounts into account.
293EXIT-CODE is the process exit code; mainly, it is zero, if the command
294completed successfully. RESULT is the quoted value of the last
295command. If nil, then the meta variables for keeping track of the
296last execution result should not be changed."
297 (let ((idx 0))
298 (assert (or (not result) (eq (car result) 'quote)))
299 (setq eshell-last-command-status exit-code
300 eshell-last-command-result (cadr result))
301 (while (< idx eshell-number-of-handles)
302 (let ((handles (or handles eshell-current-handles)))
303 (when (aref handles idx)
304 (setcdr (aref handles idx)
305 (1- (cdr (aref handles idx))))
306 (when (= (cdr (aref handles idx)) 0)
307 (let ((target (car (aref handles idx))))
308 (if (not (listp target))
309 (eshell-close-target target (= exit-code 0))
310 (while target
311 (eshell-close-target (car target) (= exit-code 0))
312 (setq target (cdr target)))))
313 (setcar (aref handles idx) nil))))
314 (setq idx (1+ idx)))
315 nil))
316
317(defun eshell-kill-append (string)
318 "Call `kill-append' with STRING, if it is indeed a string."
319 (if (stringp string)
320 (kill-append string nil)))
321
322(defun eshell-clipboard-append (string)
323 "Call `kill-append' with STRING, if it is indeed a string."
324 (if (stringp string)
325 (let ((x-select-enable-clipboard t))
326 (kill-append string nil))))
327
328(defun eshell-get-target (target &optional mode)
329 "Convert TARGET, which is a raw argument, into a valid output target.
ca7aae91
JW
330MODE is either `overwrite', `append' or `insert'; if it is omitted or nil,
331it defaults to `insert'."
affbf647
GM
332 (setq mode (or mode 'insert))
333 (cond
334 ((stringp target)
335 (let ((redir (assoc target eshell-virtual-targets)))
e1703ba9
JW
336 (if redir
337 (if (nth 2 redir)
338 (funcall (nth 1 redir) mode)
339 (nth 1 redir))
340 (let* ((exists (get-file-buffer target))
341 (buf (find-file-noselect target t)))
342 (with-current-buffer buf
343 (if buffer-read-only
344 (error "Cannot write to read-only file `%s'" target))
345 (set (make-local-variable 'eshell-output-file-buffer)
346 (if (eq exists buf) 0 t))
347 (cond ((eq mode 'overwrite)
348 (erase-buffer))
349 ((eq mode 'append)
350 (goto-char (point-max))))
351 (point-marker))))))
352
affbf647
GM
353 ((or (bufferp target)
354 (and (boundp 'eshell-buffer-shorthand)
355 (symbol-value 'eshell-buffer-shorthand)
9c041409
JW
356 (symbolp target)
357 (not (memq target '(t nil)))))
affbf647
GM
358 (let ((buf (if (bufferp target)
359 target
360 (get-buffer-create
361 (symbol-name target)))))
362 (with-current-buffer buf
363 (cond ((eq mode 'overwrite)
364 (erase-buffer))
365 ((eq mode 'append)
366 (goto-char (point-max))))
367 (point-marker))))
e1703ba9
JW
368
369 ((functionp target) nil)
370
affbf647
GM
371 ((symbolp target)
372 (if (eq mode 'overwrite)
373 (set target nil))
374 target)
e1703ba9 375
ca7aae91 376 ((or (eshell-processp target)
affbf647
GM
377 (markerp target))
378 target)
e1703ba9 379
affbf647 380 (t
5b423d48 381 (error "Invalid redirection target: %s"
affbf647
GM
382 (eshell-stringify target)))))
383
384(eval-when-compile
385 (defvar grep-null-device))
386
387(defun eshell-set-output-handle (index mode &optional target)
388 "Set handle INDEX, using MODE, to point to TARGET."
389 (when target
390 (if (and (stringp target)
391 (or (cond
392 ((boundp 'null-device)
393 (string= target null-device))
394 ((boundp 'grep-null-device)
395 (string= target grep-null-device))
396 (t nil))
397 (string= target "/dev/null")))
398 (aset eshell-current-handles index nil)
399 (let ((where (eshell-get-target target mode))
400 (current (car (aref eshell-current-handles index))))
401 (if (and (listp current)
402 (not (member where current)))
403 (setq current (append current (list where)))
2c762cee 404 (setq current (list where)))
affbf647
GM
405 (if (not (aref eshell-current-handles index))
406 (aset eshell-current-handles index (cons nil 1)))
407 (setcar (aref eshell-current-handles index) current)))))
408
409(defun eshell-interactive-output-p ()
410 "Return non-nil if current handles are bound for interactive display."
411 (and (eq (car (aref eshell-current-handles
412 eshell-output-handle)) t)
413 (eq (car (aref eshell-current-handles
414 eshell-error-handle)) t)))
415
416(defvar eshell-print-queue nil)
417(defvar eshell-print-queue-count -1)
418
419(defun eshell-flush (&optional reset-p)
420 "Flush out any lines that have been queued for printing.
421Must be called before printing begins with -1 as its argument, and
422after all printing is over with no argument."
423 (ignore
424 (if reset-p
425 (setq eshell-print-queue nil
426 eshell-print-queue-count reset-p)
427 (if eshell-print-queue
428 (eshell-print eshell-print-queue))
429 (eshell-flush 0))))
430
431(defun eshell-init-print-buffer ()
432 "Initialize the buffered printing queue."
433 (eshell-flush -1))
434
435(defun eshell-buffered-print (&rest strings)
436 "A buffered print -- *for strings only*."
437 (if (< eshell-print-queue-count 0)
438 (progn
439 (eshell-print (apply 'concat strings))
440 (setq eshell-print-queue-count 0))
441 (if (= eshell-print-queue-count eshell-print-queue-size)
442 (eshell-flush))
443 (setq eshell-print-queue
444 (concat eshell-print-queue (apply 'concat strings))
445 eshell-print-queue-count (1+ eshell-print-queue-count))))
446
447(defsubst eshell-print (object)
ca7aae91 448 "Output OBJECT to the standard output handle."
affbf647
GM
449 (eshell-output-object object eshell-output-handle))
450
451(defsubst eshell-error (object)
ca7aae91 452 "Output OBJECT to the standard error handle."
affbf647
GM
453 (eshell-output-object object eshell-error-handle))
454
455(defsubst eshell-errorn (object)
ca7aae91 456 "Output OBJECT followed by a newline to the standard error handle."
affbf647
GM
457 (eshell-error object)
458 (eshell-error "\n"))
459
460(defsubst eshell-printn (object)
ca7aae91 461 "Output OBJECT followed by a newline to the standard output handle."
affbf647
GM
462 (eshell-print object)
463 (eshell-print "\n"))
464
465(defun eshell-output-object-to-target (object target)
466 "Insert OBJECT into TARGET.
467Returns what was actually sent, or nil if nothing was sent."
468 (cond
469 ((functionp target)
470 (funcall target object))
471
472 ((symbolp target)
473 (if (eq target t) ; means "print to display"
474 (eshell-output-filter nil (eshell-stringify object))
475 (if (not (symbol-value target))
476 (set target object)
477 (setq object (eshell-stringify object))
478 (if (not (stringp (symbol-value target)))
479 (set target (eshell-stringify
480 (symbol-value target))))
481 (set target (concat (symbol-value target) object)))))
482
483 ((markerp target)
484 (if (buffer-live-p (marker-buffer target))
485 (with-current-buffer (marker-buffer target)
486 (let ((moving (= (point) target)))
487 (save-excursion
488 (goto-char target)
e1703ba9
JW
489 (unless (stringp object)
490 (setq object (eshell-stringify object)))
affbf647
GM
491 (insert-and-inherit object)
492 (set-marker target (point-marker)))
493 (if moving
494 (goto-char target))))))
495
ca7aae91 496 ((eshell-processp target)
affbf647 497 (when (eq (process-status target) 'run)
e1703ba9
JW
498 (unless (stringp object)
499 (setq object (eshell-stringify object)))
affbf647
GM
500 (process-send-string target object)))
501
502 ((consp target)
503 (apply (car target) object (cdr target))))
504 object)
505
506(defun eshell-output-object (object &optional handle-index handles)
507 "Insert OBJECT, using HANDLE-INDEX specifically)."
508 (let ((target (car (aref (or handles eshell-current-handles)
509 (or handle-index eshell-output-handle)))))
510 (if (and target (not (listp target)))
511 (eshell-output-object-to-target object target)
512 (while target
513 (eshell-output-object-to-target object (car target))
514 (setq target (cdr target))))))
515
516;;; Code:
517
ab5796a9 518;;; arch-tag: 9ca2080f-d5e0-4b26-aa0b-d59194a905a2
affbf647 519;;; esh-io.el ends here