Merge from emacs-24; up to 2013-01-03T02:31:36Z!rgm@gnu.org
[emacs.git] / lisp / eshell / esh-proc.el
blobe77287c2f7823428471cabfb8fb989d505730b54
1 ;;; esh-proc.el --- process management -*- lexical-binding:t -*-
3 ;; Copyright (C) 1999-2013 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 ;;; Code:
26 (provide 'esh-proc)
28 (require 'esh-cmd)
30 (defgroup eshell-proc nil
31 "When Eshell invokes external commands, it always does so
32 asynchronously, so that Emacs isn't tied up waiting for the process to
33 finish."
34 :tag "Process management"
35 :group 'eshell)
37 ;;; User Variables:
39 (defcustom eshell-proc-load-hook nil
40 "A hook that gets run when `eshell-proc' is loaded."
41 :version "24.1" ; removed eshell-proc-initialize
42 :type 'hook
43 :group 'eshell-proc)
45 (defcustom eshell-process-wait-seconds 0
46 "The number of seconds to delay waiting for a synchronous process."
47 :type 'integer
48 :group 'eshell-proc)
50 (defcustom eshell-process-wait-milliseconds 50
51 "The number of milliseconds to delay waiting for a synchronous process."
52 :type 'integer
53 :group 'eshell-proc)
55 (defcustom eshell-done-messages-in-minibuffer t
56 "If non-nil, subjob \"Done\" messages will display in minibuffer."
57 :type 'boolean
58 :group 'eshell-proc)
60 (defcustom eshell-delete-exited-processes t
61 "If nil, process entries will stick around until `jobs' is run.
62 This variable sets the buffer-local value of `delete-exited-processes'
63 in Eshell buffers.
65 This variable causes Eshell to mimic the behavior of bash when set to
66 nil. It allows the user to view the exit status of a completed subjob
67 \(process) at their leisure, because the process entry remains in
68 memory until the user examines it using \\[list-processes].
70 Otherwise, if `eshell-done-messages-in-minibuffer' is nil, and this
71 variable is set to t, the only indication the user will have that a
72 subjob is done is that it will no longer appear in the
73 \\[list-processes\\] display.
75 Note that Eshell will have to be restarted for a change in this
76 variable's value to take effect."
77 :type 'boolean
78 :group 'eshell-proc)
80 (defcustom eshell-reset-signals
81 "^\\(interrupt\\|killed\\|quit\\|stopped\\)"
82 "If a termination signal matches this regexp, the terminal will be reset."
83 :type 'regexp
84 :group 'eshell-proc)
86 (defcustom eshell-exec-hook nil
87 "Called each time a process is exec'd by `eshell-gather-process-output'.
88 It is passed one argument, which is the process that was just started.
89 It is useful for things that must be done each time a process is
90 executed in a eshell mode buffer (e.g., `process-kill-without-query').
91 In contrast, `eshell-mode-hook' is only executed once when the buffer
92 is created."
93 :type 'hook
94 :group 'eshell-proc)
96 (defcustom eshell-kill-hook nil
97 "Called when a process run by `eshell-gather-process-output' has ended.
98 It is passed two arguments: the process that was just ended, and the
99 termination status (as a string). Note that the first argument may be
100 nil, in which case the user attempted to send a signal, but there was
101 no relevant process. This can be used for displaying help
102 information, for example."
103 :version "24.1" ; removed eshell-reset-after-proc
104 :type 'hook
105 :group 'eshell-proc)
107 ;;; Internal Variables:
109 (defvar eshell-current-subjob-p nil)
111 (defvar eshell-process-list nil
112 "A list of the current status of subprocesses.")
114 ;;; Functions:
116 (defun eshell-kill-process-function (proc status)
117 "Function run when killing a process.
118 Runs `eshell-reset-after-proc' and `eshell-kill-hook', passing arguments
119 PROC and STATUS to both."
120 (or (memq 'eshell-reset-after-proc eshell-kill-hook)
121 (eshell-reset-after-proc proc status))
122 (run-hook-with-args 'eshell-kill-hook proc status))
124 (defun eshell-proc-initialize ()
125 "Initialize the process handling code."
126 (make-local-variable 'eshell-process-list)
127 (define-key eshell-command-map [(meta ?i)] 'eshell-insert-process)
128 (define-key eshell-command-map [(control ?c)] 'eshell-interrupt-process)
129 (define-key eshell-command-map [(control ?k)] 'eshell-kill-process)
130 (define-key eshell-command-map [(control ?d)] 'eshell-send-eof-to-process)
131 ; (define-key eshell-command-map [(control ?q)] 'eshell-continue-process)
132 (define-key eshell-command-map [(control ?s)] 'list-processes)
133 ; (define-key eshell-command-map [(control ?z)] 'eshell-stop-process)
134 (define-key eshell-command-map [(control ?\\)] 'eshell-quit-process))
136 (defun eshell-reset-after-proc (proc status)
137 "Reset the command input location after a process terminates.
138 The signals which will cause this to happen are matched by
139 `eshell-reset-signals'."
140 (if (and (stringp status)
141 (string-match eshell-reset-signals status))
142 (eshell-reset)))
144 (defun eshell-wait-for-process (&rest procs)
145 "Wait until PROC has successfully completed."
146 (while procs
147 (let ((proc (car procs)))
148 (when (eshell-processp proc)
149 ;; NYI: If the process gets stopped here, that's bad.
150 (while (assq proc eshell-process-list)
151 (if (input-pending-p)
152 (discard-input))
153 (sit-for eshell-process-wait-seconds
154 eshell-process-wait-milliseconds))))
155 (setq procs (cdr procs))))
157 (defalias 'eshell/wait 'eshell-wait-for-process)
159 (defun eshell/jobs (&rest args)
160 "List processes, if there are any."
161 (and (fboundp 'process-list)
162 (process-list)
163 (list-processes)))
165 (defun eshell/kill (&rest args)
166 "Kill processes.
167 Usage: kill [-<signal>] <pid>|<process> ...
168 Accepts PIDs and process objects."
169 ;; If the first argument starts with a dash, treat it as the signal
170 ;; specifier.
171 (let ((signum 'SIGINT))
172 (let ((arg (car args))
173 (case-fold-search nil))
174 (when (stringp arg)
175 (cond
176 ((string-match "\\`-[[:digit:]]+\\'" arg)
177 (setq signum (abs (string-to-number arg))))
178 ((string-match "\\`-\\([[:upper:]]+\\|[[:lower:]]+\\)\\'" arg)
179 (setq signum (abs (string-to-number arg)))))
180 (setq args (cdr args))))
181 (while args
182 (let ((arg (if (eshell-processp (car args))
183 (process-id (car args))
184 (car args))))
185 (when arg
186 (cond
187 ((null arg)
188 (error "kill: null pid. Process may actually be a network connection."))
189 ((not (numberp arg))
190 (error "kill: invalid argument type: %s" (type-of arg)))
191 ((and (numberp arg)
192 (<= arg 0))
193 (error "kill: bad pid: %d" arg))
195 (signal-process arg signum)))))
196 (setq args (cdr args))))
197 nil)
199 (defun eshell-read-process-name (prompt)
200 "Read the name of a process from the minibuffer, using completion.
201 The prompt will be set to PROMPT."
202 (completing-read prompt
203 (mapcar
204 (function
205 (lambda (proc)
206 (cons (process-name proc) t)))
207 (process-list)) nil t))
209 (defun eshell-insert-process (process)
210 "Insert the name of PROCESS into the current buffer at point."
211 (interactive
212 (list (get-process
213 (eshell-read-process-name "Name of process: "))))
214 (insert-and-inherit "#<process " (process-name process) ">"))
216 (defsubst eshell-record-process-object (object)
217 "Record OBJECT as now running."
218 (if (and (eshell-processp object)
219 eshell-current-subjob-p)
220 (eshell-interactive-print
221 (format "[%s] %d\n" (process-name object) (process-id object))))
222 (setq eshell-process-list
223 (cons (list object eshell-current-handles
224 eshell-current-subjob-p nil nil)
225 eshell-process-list)))
227 (defun eshell-remove-process-entry (entry)
228 "Record the process ENTRY as fully completed."
229 (if (and (eshell-processp (car entry))
230 (nth 2 entry)
231 eshell-done-messages-in-minibuffer)
232 (message "[%s]+ Done %s" (process-name (car entry))
233 (process-command (car entry))))
234 (setq eshell-process-list
235 (delq entry eshell-process-list)))
237 (defvar eshell-scratch-buffer " *eshell-scratch*"
238 "Scratch buffer for holding Eshell's input/output.")
239 (defvar eshell-last-sync-output-start nil
240 "A marker that tracks the beginning of output of the last subprocess.
241 Used only on systems which do not support async subprocesses.")
243 (defvar eshell-needs-pipe '("bc")
244 "List of commands which need `process-connection-type' to be nil.
245 Currently only affects commands in pipelines, and not those at
246 the front. If an element contains a directory part it must match
247 the full name of a command, otherwise just the nondirectory part must match.")
249 (defun eshell-needs-pipe-p (command)
250 "Return non-nil if COMMAND needs `process-connection-type' to be nil.
251 See `eshell-needs-pipe'."
252 (and eshell-in-pipeline-p
253 (not (eq eshell-in-pipeline-p 'first))
254 ;; FIXME should this return non-nil for anything that is
255 ;; neither 'first nor 'last? See bug#1388 discussion.
256 (catch 'found
257 (dolist (exe eshell-needs-pipe)
258 (if (string-equal exe (if (string-match "/" exe)
259 command
260 (file-name-nondirectory command)))
261 (throw 'found t))))))
263 (defun eshell-gather-process-output (command args)
264 "Gather the output from COMMAND + ARGS."
265 (unless (and (file-executable-p command)
266 (file-regular-p (file-truename command)))
267 (error "%s: not an executable file" command))
268 (let* ((delete-exited-processes
269 (if eshell-current-subjob-p
270 eshell-delete-exited-processes
271 delete-exited-processes))
272 (process-environment (eshell-environment-variables))
273 proc decoding encoding changed)
274 (cond
275 ((fboundp 'start-file-process)
276 (setq proc
277 (let ((process-connection-type
278 (unless (eshell-needs-pipe-p command)
279 process-connection-type))
280 (command (or (file-remote-p command 'localname) command)))
281 (apply 'start-file-process
282 (file-name-nondirectory command) nil
283 ;; `start-process' can't deal with relative filenames.
284 (append (list (expand-file-name command)) args))))
285 (eshell-record-process-object proc)
286 (set-process-buffer proc (current-buffer))
287 (if (eshell-interactive-output-p)
288 (set-process-filter proc 'eshell-output-filter)
289 (set-process-filter proc 'eshell-insertion-filter))
290 (set-process-sentinel proc 'eshell-sentinel)
291 (run-hook-with-args 'eshell-exec-hook proc)
292 (when (fboundp 'process-coding-system)
293 (let ((coding-systems (process-coding-system proc)))
294 (setq decoding (car coding-systems)
295 encoding (cdr coding-systems)))
296 ;; If start-process decided to use some coding system for
297 ;; decoding data sent from the process and the coding system
298 ;; doesn't specify EOL conversion, we had better convert CRLF
299 ;; to LF.
300 (if (vectorp (coding-system-eol-type decoding))
301 (setq decoding (coding-system-change-eol-conversion decoding 'dos)
302 changed t))
303 ;; Even if start-process left the coding system for encoding
304 ;; data sent from the process undecided, we had better use the
305 ;; same one as what we use for decoding. But, we should
306 ;; suppress EOL conversion.
307 (if (and decoding (not encoding))
308 (setq encoding (coding-system-change-eol-conversion decoding 'unix)
309 changed t))
310 (if changed
311 (set-process-coding-system proc decoding encoding))))
313 ;; No async subprocesses...
314 (let ((oldbuf (current-buffer))
315 (interact-p (eshell-interactive-output-p))
316 lbeg lend line proc-buf exit-status)
317 (and (not (markerp eshell-last-sync-output-start))
318 (setq eshell-last-sync-output-start (point-marker)))
319 (setq proc-buf
320 (set-buffer (get-buffer-create eshell-scratch-buffer)))
321 (erase-buffer)
322 (set-buffer oldbuf)
323 (run-hook-with-args 'eshell-exec-hook command)
324 (setq exit-status
325 (apply 'call-process-region
326 (append (list eshell-last-sync-output-start (point)
327 command t
328 eshell-scratch-buffer nil)
329 args)))
330 ;; When in a pipeline, record the place where the output of
331 ;; this process will begin.
332 (and eshell-in-pipeline-p
333 (set-marker eshell-last-sync-output-start (point)))
334 ;; Simulate the effect of the process filter.
335 (when (numberp exit-status)
336 (set-buffer proc-buf)
337 (goto-char (point-min))
338 (setq lbeg (point))
339 (while (eq 0 (forward-line 1))
340 (setq lend (point)
341 line (buffer-substring-no-properties lbeg lend))
342 (set-buffer oldbuf)
343 (if interact-p
344 (eshell-output-filter nil line)
345 (eshell-output-object line))
346 (setq lbeg lend)
347 (set-buffer proc-buf))
348 (set-buffer oldbuf))
349 (eshell-update-markers eshell-last-output-end)
350 ;; Simulate the effect of eshell-sentinel.
351 (eshell-close-handles (if (numberp exit-status) exit-status -1))
352 (eshell-kill-process-function command exit-status)
353 (or eshell-in-pipeline-p
354 (setq eshell-last-sync-output-start nil))
355 (if (not (numberp exit-status))
356 (error "%s: external command failed: %s" command exit-status))
357 (setq proc t))))
358 proc))
360 (defun eshell-insertion-filter (proc string)
361 "Insert a string into the eshell buffer, or a process/file/buffer.
362 PROC is the process for which we're inserting output. STRING is the
363 output."
364 (when (buffer-live-p (process-buffer proc))
365 (with-current-buffer (process-buffer proc)
366 (let ((entry (assq proc eshell-process-list)))
367 (when entry
368 (setcar (nthcdr 3 entry)
369 (concat (nth 3 entry) string))
370 (unless (nth 4 entry) ; already being handled?
371 (while (nth 3 entry)
372 (let ((data (nth 3 entry)))
373 (setcar (nthcdr 3 entry) nil)
374 (setcar (nthcdr 4 entry) t)
375 (eshell-output-object data nil (cadr entry))
376 (setcar (nthcdr 4 entry) nil)))))))))
378 (defun eshell-sentinel (proc string)
379 "Generic sentinel for command processes. Reports only signals.
380 PROC is the process that's exiting. STRING is the exit message."
381 (when (buffer-live-p (process-buffer proc))
382 (with-current-buffer (process-buffer proc)
383 (unwind-protect
384 (let* ((entry (assq proc eshell-process-list)))
385 ; (if (not entry)
386 ; (error "Sentinel called for unowned process `%s'"
387 ; (process-name proc))
388 (when entry
389 (unwind-protect
390 (progn
391 (unless (string= string "run")
392 (unless (string-match "^\\(finished\\|exited\\)" string)
393 (eshell-insertion-filter proc string))
394 (eshell-close-handles (process-exit-status proc) 'nil
395 (cadr entry))))
396 (eshell-remove-process-entry entry))))
397 (eshell-kill-process-function proc string)))))
399 (defun eshell-process-interact (func &optional all query)
400 "Interact with a process, using PROMPT if more than one, via FUNC.
401 If ALL is non-nil, background processes will be interacted with as well.
402 If QUERY is non-nil, query the user with QUERY before calling FUNC."
403 (let (defunct result)
404 (dolist (entry eshell-process-list)
405 (if (and (memq (process-status (car entry))
406 '(run stop open closed))
407 (or all
408 (not (nth 2 entry)))
409 (or (not query)
410 (y-or-n-p (format query (process-name (car entry))))))
411 (setq result (funcall func (car entry))))
412 (unless (memq (process-status (car entry))
413 '(run stop open closed))
414 (setq defunct (cons entry defunct))))
415 ;; clean up the process list; this can get dirty if an error
416 ;; occurred that brought the user into the debugger, and then they
417 ;; quit, so that the sentinel was never called.
418 (dolist (d defunct)
419 (eshell-remove-process-entry d))
420 result))
422 (defcustom eshell-kill-process-wait-time 5
423 "Seconds to wait between sending termination signals to a subprocess."
424 :type 'integer
425 :group 'eshell-proc)
427 (defcustom eshell-kill-process-signals '(SIGINT SIGQUIT SIGKILL)
428 "Signals used to kill processes when an Eshell buffer exits.
429 Eshell calls each of these signals in order when an Eshell buffer is
430 killed; if the process is still alive afterwards, Eshell waits a
431 number of seconds defined by `eshell-kill-process-wait-time', and
432 tries the next signal in the list."
433 :type '(repeat symbol)
434 :group 'eshell-proc)
436 (defcustom eshell-kill-processes-on-exit nil
437 "If non-nil, kill active processes when exiting an Eshell buffer.
438 Emacs will only kill processes owned by that Eshell buffer.
440 If nil, ownership of background and foreground processes reverts to
441 Emacs itself, and will die only if the user exits Emacs, calls
442 `kill-process', or terminates the processes externally.
444 If `ask', Emacs prompts the user before killing any processes.
446 If `every', it prompts once for every process.
448 If t, it kills all buffer-owned processes without asking.
450 Processes are first sent SIGHUP, then SIGINT, then SIGQUIT, then
451 SIGKILL. The variable `eshell-kill-process-wait-time' specifies how
452 long to delay between signals."
453 :type '(choice (const :tag "Kill all, don't ask" t)
454 (const :tag "Ask before killing" ask)
455 (const :tag "Ask for each process" every)
456 (const :tag "Don't kill subprocesses" nil))
457 :group 'eshell-proc)
459 (defun eshell-round-robin-kill (&optional query)
460 "Kill current process by trying various signals in sequence.
461 See the variable `eshell-kill-processes-on-exit'."
462 (let ((sigs eshell-kill-process-signals))
463 (while sigs
464 (eshell-process-interact
465 (function
466 (lambda (proc)
467 (signal-process (process-id proc) (car sigs)))) t query)
468 (setq query nil)
469 (if (not eshell-process-list)
470 (setq sigs nil)
471 (sleep-for eshell-kill-process-wait-time)
472 (setq sigs (cdr sigs))))))
474 (defun eshell-query-kill-processes ()
475 "Kill processes belonging to the current Eshell buffer, possibly w/ query."
476 (when (and eshell-kill-processes-on-exit
477 eshell-process-list)
478 (save-window-excursion
479 (list-processes)
480 (if (or (not (eq eshell-kill-processes-on-exit 'ask))
481 (y-or-n-p (format "Kill processes owned by `%s'? "
482 (buffer-name))))
483 (eshell-round-robin-kill
484 (if (eq eshell-kill-processes-on-exit 'every)
485 "Kill Eshell child process `%s'? ")))
486 (let ((buf (get-buffer "*Process List*")))
487 (if (and buf (buffer-live-p buf))
488 (kill-buffer buf)))
489 (message nil))))
491 (defun eshell-interrupt-process ()
492 "Interrupt a process."
493 (interactive)
494 (unless (eshell-process-interact 'interrupt-process)
495 (eshell-kill-process-function nil "interrupt")))
497 (defun eshell-kill-process ()
498 "Kill a process."
499 (interactive)
500 (unless (eshell-process-interact 'kill-process)
501 (eshell-kill-process-function nil "killed")))
503 (defun eshell-quit-process ()
504 "Send quit signal to process."
505 (interactive)
506 (unless (eshell-process-interact 'quit-process)
507 (eshell-kill-process-function nil "quit")))
509 ;(defun eshell-stop-process ()
510 ; "Send STOP signal to process."
511 ; (interactive)
512 ; (unless (eshell-process-interact 'stop-process)
513 ; (eshell-kill-process-function nil "stopped")))
515 ;(defun eshell-continue-process ()
516 ; "Send CONTINUE signal to process."
517 ; (interactive)
518 ; (unless (eshell-process-interact 'continue-process)
519 ; ;; jww (1999-09-17): this signal is not dealt with yet. For
520 ; ;; example, `eshell-reset' will be called, and so will
521 ; ;; `eshell-resume-eval'.
522 ; (eshell-kill-process-function nil "continue")))
524 (defun eshell-send-eof-to-process ()
525 "Send EOF to process."
526 (interactive)
527 (eshell-send-input nil nil t)
528 (eshell-process-interact 'process-send-eof))
530 ;;; esh-proc.el ends here