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