Minor backslash fixes in manuals and scripts
[emacs.git] / lisp / eshell / esh-proc.el
blob867d3b9145d4be3a19b571eacd0ded0404e15461
1 ;;; esh-proc.el --- process 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 ;;; 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 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)
124 (run-hook-with-args 'eshell-kill-hook proc status))
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)
133 ; (define-key eshell-command-map [(control ?q)] 'eshell-continue-process)
134 (define-key eshell-command-map [(control ?s)] 'list-processes)
135 ; (define-key eshell-command-map [(control ?z)] 'eshell-stop-process)
136 (define-key eshell-command-map [(control ?\\)] 'eshell-quit-process))
138 (defun eshell-reset-after-proc (status)
139 "Reset the command input location after a process terminates.
140 The signals which will cause this to happen are matched by
141 `eshell-reset-signals'."
142 (if (and (stringp status)
143 (string-match eshell-reset-signals status))
144 (eshell-reset)))
146 (defun eshell-wait-for-process (&rest procs)
147 "Wait until PROC has successfully completed."
148 (while procs
149 (let ((proc (car procs)))
150 (when (eshell-processp proc)
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))))
159 (defalias 'eshell/wait 'eshell-wait-for-process)
161 (defun eshell/jobs (&rest args)
162 "List processes, if there are any."
163 (and (fboundp 'process-list)
164 (process-list)
165 (list-processes)))
167 (defun eshell/kill (&rest args)
168 "Kill processes.
169 Usage: kill [-<signal>] <pid>|<process> ...
170 Accepts PIDs and process objects."
171 ;; If the first argument starts with a dash, treat it as the signal
172 ;; specifier.
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))
197 (signal-process arg signum)))))
198 (setq args (cdr args))))
199 nil)
201 (defun eshell-read-process-name (prompt)
202 "Read the name of a process from the minibuffer, using completion.
203 The 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))
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) ">"))
218 (defsubst eshell-record-process-object (object)
219 "Record OBJECT as now running."
220 (if (and (eshell-processp object)
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)))
229 (defun eshell-remove-process-entry (entry)
230 "Record the process ENTRY as fully completed."
231 (if (and (eshell-processp (car entry))
232 (nth 2 entry)
233 eshell-done-messages-in-minibuffer)
234 (message "[%s]+ Done %s" (process-name (car entry))
235 (process-command (car entry))))
236 (setq eshell-process-list
237 (delq entry eshell-process-list)))
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.
243 Used only on systems which do not support async subprocesses.")
245 (defvar eshell-needs-pipe '("bc")
246 "List of commands which need `process-connection-type' to be nil.
247 Currently only affects commands in pipelines, and not those at
248 the front. If an element contains a directory part it must match
249 the full name of a command, otherwise just the nondirectory part must match.")
251 (defun eshell-needs-pipe-p (command)
252 "Return non-nil if COMMAND needs `process-connection-type' to be nil.
253 See `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))))))
265 (defun eshell-gather-process-output (command args)
266 "Gather the output from COMMAND + ARGS."
267 (unless (and (file-executable-p command)
268 (file-regular-p (file-truename command)))
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))
275 proc decoding encoding changed)
276 (cond
277 ((fboundp 'start-file-process)
278 (setq proc
279 (let ((process-connection-type
280 (unless (eshell-needs-pipe-p command)
281 process-connection-type))
282 (command (or (file-remote-p command 'localname) command)))
283 (apply 'start-file-process
284 (file-name-nondirectory command) nil
285 ;; `start-process' can't deal with relative filenames.
286 (append (list (expand-file-name command)) args))))
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))))
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))
354 (eshell-kill-process-function command exit-status)
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))))
360 proc))
362 (defun eshell-insertion-filter (proc string)
363 "Insert a string into the eshell buffer, or a process/file/buffer.
364 PROC is the process for which we're inserting output. STRING is the
365 output."
366 (when (buffer-live-p (process-buffer proc))
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)))))))))
380 (defun eshell-sentinel (proc string)
381 "Generic sentinel for command processes. Reports only signals.
382 PROC is the process that's exiting. STRING is the exit message."
383 (when (buffer-live-p (process-buffer proc))
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))))
399 (eshell-kill-process-function proc string)))))
401 (defun eshell-process-interact (func &optional all query)
402 "Interact with a process, using PROMPT if more than one, via FUNC.
403 If ALL is non-nil, background processes will be interacted with as well.
404 If QUERY is non-nil, query the user with QUERY before calling FUNC."
405 (let (defunct result)
406 (dolist (entry eshell-process-list)
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-message query
413 (process-name (car entry))))))
414 (setq result (funcall func (car entry))))
415 (unless (memq (process-status (car entry))
416 '(run stop open closed))
417 (setq defunct (cons entry defunct))))
418 ;; clean up the process list; this can get dirty if an error
419 ;; occurred that brought the user into the debugger, and then they
420 ;; quit, so that the sentinel was never called.
421 (dolist (d defunct)
422 (eshell-remove-process-entry d))
423 result))
425 (defcustom eshell-kill-process-wait-time 5
426 "Seconds to wait between sending termination signals to a subprocess."
427 :type 'integer
428 :group 'eshell-proc)
430 (defcustom eshell-kill-process-signals '(SIGINT SIGQUIT SIGKILL)
431 "Signals used to kill processes when an Eshell buffer exits.
432 Eshell calls each of these signals in order when an Eshell buffer is
433 killed; if the process is still alive afterwards, Eshell waits a
434 number of seconds defined by `eshell-kill-process-wait-time', and
435 tries the next signal in the list."
436 :type '(repeat symbol)
437 :group 'eshell-proc)
439 (defcustom eshell-kill-processes-on-exit nil
440 "If non-nil, kill active processes when exiting an Eshell buffer.
441 Emacs will only kill processes owned by that Eshell buffer.
443 If nil, ownership of background and foreground processes reverts to
444 Emacs itself, and will die only if the user exits Emacs, calls
445 `kill-process', or terminates the processes externally.
447 If `ask', Emacs prompts the user before killing any processes.
449 If `every', it prompts once for every process.
451 If t, it kills all buffer-owned processes without asking.
453 Processes are first sent SIGHUP, then SIGINT, then SIGQUIT, then
454 SIGKILL. The variable `eshell-kill-process-wait-time' specifies how
455 long to delay between signals."
456 :type '(choice (const :tag "Kill all, don't ask" t)
457 (const :tag "Ask before killing" ask)
458 (const :tag "Ask for each process" every)
459 (const :tag "Don't kill subprocesses" nil))
460 :group 'eshell-proc)
462 (defun eshell-round-robin-kill (&optional query)
463 "Kill current process by trying various signals in sequence.
464 See the variable `eshell-kill-processes-on-exit'."
465 (let ((sigs eshell-kill-process-signals))
466 (while sigs
467 (eshell-process-interact
468 (function
469 (lambda (proc)
470 (signal-process (process-id proc) (car sigs)))) t query)
471 (setq query nil)
472 (if (not eshell-process-list)
473 (setq sigs nil)
474 (sleep-for eshell-kill-process-wait-time)
475 (setq sigs (cdr sigs))))))
477 (defun eshell-query-kill-processes ()
478 "Kill processes belonging to the current Eshell buffer, possibly w/ query."
479 (when (and eshell-kill-processes-on-exit
480 eshell-process-list)
481 (save-window-excursion
482 (list-processes)
483 (if (or (not (eq eshell-kill-processes-on-exit 'ask))
484 (y-or-n-p (format-message "Kill processes owned by `%s'? "
485 (buffer-name))))
486 (eshell-round-robin-kill
487 (if (eq eshell-kill-processes-on-exit 'every)
488 (format-message "Kill Eshell child process `%s'? "))))
489 (let ((buf (get-buffer "*Process List*")))
490 (if (and buf (buffer-live-p buf))
491 (kill-buffer buf)))
492 (message nil))))
494 (defun eshell-interrupt-process ()
495 "Interrupt a process."
496 (interactive)
497 (unless (eshell-process-interact 'interrupt-process)
498 (eshell-kill-process-function nil "interrupt")))
500 (defun eshell-kill-process ()
501 "Kill a process."
502 (interactive)
503 (unless (eshell-process-interact 'kill-process)
504 (eshell-kill-process-function nil "killed")))
506 (defun eshell-quit-process ()
507 "Send quit signal to process."
508 (interactive)
509 (unless (eshell-process-interact 'quit-process)
510 (eshell-kill-process-function nil "quit")))
512 ;(defun eshell-stop-process ()
513 ; "Send STOP signal to process."
514 ; (interactive)
515 ; (unless (eshell-process-interact 'stop-process)
516 ; (eshell-kill-process-function nil "stopped")))
518 ;(defun eshell-continue-process ()
519 ; "Send CONTINUE signal to process."
520 ; (interactive)
521 ; (unless (eshell-process-interact 'continue-process)
522 ; ;; jww (1999-09-17): this signal is not dealt with yet. For
523 ; ;; example, `eshell-reset' will be called, and so will
524 ; ;; `eshell-resume-eval'.
525 ; (eshell-kill-process-function nil "continue")))
527 (defun eshell-send-eof-to-process ()
528 "Send EOF to process."
529 (interactive)
530 (eshell-send-input nil nil t)
531 (eshell-process-interact 'process-send-eof))
533 ;;; esh-proc.el ends here