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