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