XEmacs 21.2.33 "Melpomene".
[chise/xemacs-chise.git.1] / lisp / process.el
1 ;;; process.el --- commands for subprocesses; split out of simple.el
2
3 ;; Copyright (C) 1985-7, 1993,4, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995, 2000 Ben Wing.
5
6 ;; Author: Ben Wing
7 ;; Maintainer: XEmacs Development Team
8 ;; Keywords: internal, processes, dumped
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the 
24 ;; Free Software Foundation, 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Synched up with: FSF 19.30.
28
29 ;;; Authorship:
30
31 ;; Created 1995 by Ben Wing during Mule work -- some commands split out
32 ;; of simple.el and wrappers of *-internal functions created so they could
33 ;; be redefined in a Mule world.
34 ;; Lisp definition of call-process-internal added Mar. 2000 by Ben Wing.
35
36 ;;; Commentary:
37
38 ;; This file is dumped with XEmacs.
39
40 ;;; Code:
41
42 \f
43 (defgroup processes nil
44   "Process, subshell, compilation, and job control support."
45   :group 'external
46   :group 'development)
47
48 (defgroup processes-basics nil
49   "Basic stuff dealing with processes."
50   :group 'processes)
51
52 (defgroup execute nil
53   "Executing external commands."
54   :group 'processes)
55
56
57 (defvar shell-command-switch "-c"
58   "Switch used to have the shell execute its command line argument.")
59
60 (defun start-process-shell-command (name buffer &rest args)
61   "Start a program in a subprocess.  Return the process object for it.
62 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
63 NAME is name for process.  It is modified if necessary to make it unique.
64 BUFFER is the buffer or (buffer-name) to associate with the process.
65  Process output goes at end of that buffer, unless you specify
66  an output stream or filter function to handle the output.
67  BUFFER may be also nil, meaning that this process is not associated
68  with any buffer
69 Third arg is command name, the name of a shell command.
70 Remaining arguments are the arguments for the command.
71 Wildcards and redirection are handled as usual in the shell."
72   ;; We used to use `exec' to replace the shell with the command,
73   ;; but that failed to handle (...) and semicolon, etc.
74   (start-process name buffer shell-file-name shell-command-switch
75                  (mapconcat #'identity args " ")))
76
77 (defun call-process-internal (program &optional infile buffer display &rest args)
78   "Call PROGRAM synchronously in separate process, with coding-system specified.
79 Arguments are
80  (PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS).
81 The program's input comes from file INFILE (nil means `/dev/null').
82 Insert output in BUFFER before point; t means current buffer;
83  nil for BUFFER means discard it; 0 means discard and don't wait.
84 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
85 REAL-BUFFER says what to do with standard output, as above,
86 while STDERR-FILE says what to do with standard error in the child.
87 STDERR-FILE may be nil (discard standard error output),
88 t (mix it with ordinary output), or a file name string.
89
90 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
91 Remaining arguments are strings passed as command arguments to PROGRAM.
92
93 If BUFFER is 0, `call-process' returns immediately with value nil.
94 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
95  or a signal description string.
96 If you quit, the process is killed with SIGINT, or SIGKILL if you
97  quit again."
98   ;; #### remove windows-nt check when this is ready for prime time.
99   (if (or (noninteractive) (not (eq 'windows-nt system-type)))
100       (apply 'old-call-process-internal program infile buffer display args)
101     (let (proc inbuf errbuf discard)
102       (unwind-protect
103           (progn
104             (when infile
105               (setq infile (expand-file-name infile))
106               (setq inbuf (generate-new-buffer "*call-process*"))
107               (with-current-buffer inbuf
108                 (insert-file-contents-internal infile nil nil nil nil
109                                                coding-system-for-read)))
110             (let ((stderr (if (consp buffer) (second buffer) t)))
111               (if (consp buffer) (setq buffer (car buffer)))
112               (setq buffer
113                     (cond ((null buffer) nil)
114                           ((eq buffer t) (current-buffer))
115                           ;; use integerp for compatibility with existing
116                           ;; call-process rmsism.
117                           ((integerp buffer) (setq discard t) nil)
118                           (t (get-buffer-create buffer))))
119               (when (and stderr (not (eq t stderr)))
120                 (setq stderr (expand-file-name stderr))
121                 (setq errbuf (generate-new-buffer "*call-process*")))
122               (setq proc
123                     (apply 'start-process-internal "*call-process*"
124                            buffer
125                            ;#### not implemented until my new process
126                            ;changes go in.
127                            ;(if (eq t stderr) buffer (list buffer errbuf))
128                            program args))
129               (if buffer
130                   (set-marker (process-mark proc) (point buffer) buffer))
131               (unwind-protect
132                   (progn
133                     (catch 'call-process-done
134                       (when (not discard)
135                         (set-process-sentinel
136                          proc
137                          #'(lambda (proc status)
138                              (cond ((eq 'exit (process-status proc))
139                                     (set-process-sentinel proc nil)
140                                     (throw 'call-process-done
141                                            (process-exit-status proc)))
142                                    ((eq 'signal (process-status proc))
143                                     (set-process-sentinel proc nil)
144                                     (throw 'call-process-done status))))))
145                       (when inbuf
146                         (process-send-region proc 1
147                                              (1+ (buffer-size inbuf)) inbuf))
148                       (process-send-eof proc)
149                       (when discard
150                         ;; we're trying really really hard to emulate
151                         ;; the old call-process.
152                         (if errbuf
153                             (set-process-sentinel
154                              proc
155                              `(lambda (proc status)
156                                 (write-region-internal
157                                  1 (1+ (buffer-size))
158                                  ,stderr
159                                  nil 'major-rms-kludge-city nil
160                                  coding-system-for-write))))
161                         (setq errbuf nil)
162                         (setq proc nil)
163                         (throw 'call-process-done nil))
164                       (while t
165                         (accept-process-output proc)
166                         (if display (sit-for 0))))
167                     (when errbuf
168                       (with-current-buffer errbuf
169                         (write-region-internal 1 (1+ (buffer-size)) stderr
170                                                nil 'major-rms-kludge-city nil
171                                                coding-system-for-write))))
172                 (if proc (set-process-sentinel proc nil)))))
173         (if inbuf (kill-buffer inbuf))
174         (if errbuf (kill-buffer errbuf))
175         (condition-case nil
176             (if (and proc (process-live-p proc)) (kill-process proc))
177           (error nil))))))
178
179 (defun call-process (program &optional infile buffer displayp &rest args)
180   "Call PROGRAM synchronously in separate process.
181 The program's input comes from file INFILE (nil means `/dev/null').
182 Insert output in BUFFER before point; t means current buffer;
183  nil for BUFFER means discard it; 0 means discard and don't wait.
184 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
185 REAL-BUFFER says what to do with standard output, as above,
186 while STDERR-FILE says what to do with standard error in the child.
187 STDERR-FILE may be nil (discard standard error output),
188 t (mix it with ordinary output), or a file name string.
189
190 Fourth arg DISPLAYP non-nil means redisplay buffer as output is inserted.
191 Remaining arguments are strings passed as command arguments to PROGRAM.
192
193 If BUFFER is 0, `call-process' returns immediately with value nil.
194 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
195  or a signal description string.
196 If you quit, the process is killed with SIGINT, or SIGKILL if you
197  quit again."
198   (apply 'call-process-internal program infile buffer displayp args))
199
200 (defun call-process-region (start end program
201                             &optional deletep buffer displayp
202                             &rest args)
203   "Send text from START to END to a synchronous process running PROGRAM.
204 Delete the text if fourth arg DELETEP is non-nil.
205
206 Insert output in BUFFER before point; t means current buffer;
207  nil for BUFFER means discard it; 0 means discard and don't wait.
208 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
209 REAL-BUFFER says what to do with standard output, as above,
210 while STDERR-FILE says what to do with standard error in the child.
211 STDERR-FILE may be nil (discard standard error output),
212 t (mix it with ordinary output), or a file name string.
213
214 Sixth arg DISPLAYP non-nil means redisplay buffer as output is inserted.
215 Remaining args are passed to PROGRAM at startup as command args.
216
217 If BUFFER is 0, returns immediately with value nil.
218 Otherwise waits for PROGRAM to terminate
219 and returns a numeric exit status or a signal description string.
220 If you quit, the process is first killed with SIGINT, then with SIGKILL if
221 you quit again before the process exits."
222   (let ((temp
223          (make-temp-name
224           (concat (file-name-as-directory (temp-directory)) "emacs"))))
225     (unwind-protect
226         (progn
227           (write-region start end temp nil 'silent)
228           (if deletep (delete-region start end))
229           (apply #'call-process program temp buffer displayp args))
230       (ignore-file-errors (delete-file temp)))))
231
232 \f
233 (defun shell-command (command &optional output-buffer)
234   "Execute string COMMAND in inferior shell; display output, if any.
235
236 If COMMAND ends in ampersand, execute it asynchronously.
237 The output appears in the buffer `*Async Shell Command*'.
238 That buffer is in shell mode.
239
240 Otherwise, COMMAND is executed synchronously.  The output appears in the
241 buffer `*Shell Command Output*'.
242 If the output is one line, it is displayed in the echo area *as well*,
243 but it is nonetheless available in buffer `*Shell Command Output*',
244 even though that buffer is not automatically displayed.
245 If there is no output, or if output is inserted in the current buffer,
246 then `*Shell Command Output*' is deleted.
247
248 The optional second argument OUTPUT-BUFFER, if non-nil,
249 says to put the output in some other buffer.
250 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
251 If OUTPUT-BUFFER is not a buffer and not nil,
252 insert output in current buffer.  (This cannot be done asynchronously.)
253 In either case, the output is inserted after point (leaving mark after it)."
254   (interactive (list (read-shell-command "Shell command: ")
255                      current-prefix-arg))
256   (if (and output-buffer
257            (not (or (bufferp output-buffer)  (stringp output-buffer))))
258       (progn (barf-if-buffer-read-only)
259              (push-mark)
260              ;; We do not use -f for csh; we will not support broken use of
261              ;; .cshrcs.  Even the BSD csh manual says to use
262              ;; "if ($?prompt) exit" before things which are not useful
263              ;; non-interactively.  Besides, if someone wants their other
264              ;; aliases for shell commands then they can still have them.
265              (call-process shell-file-name nil t nil
266                            shell-command-switch command)
267              (exchange-point-and-mark t))
268     ;; Preserve the match data in case called from a program.
269     (save-match-data
270       (if (string-match "[ \t]*&[ \t]*$" command)
271           ;; Command ending with ampersand means asynchronous.
272           (progn
273             (background (substring command 0 (match-beginning 0))))
274         (shell-command-on-region (point) (point) command output-buffer)))))
275
276 ;; We have a sentinel to prevent insertion of a termination message
277 ;; in the buffer itself.
278 (defun shell-command-sentinel (process signal)
279   (if (memq (process-status process) '(exit signal))
280       (message "%s: %s."
281                (car (cdr (cdr (process-command process))))
282                (substring signal 0 -1))))
283
284 (defun shell-command-on-region (start end command
285                                       &optional output-buffer replace)
286   "Execute string COMMAND in inferior shell with region as input.
287 Normally display output (if any) in temp buffer `*Shell Command Output*';
288 Prefix arg means replace the region with it.
289
290 The noninteractive arguments are START, END, COMMAND, OUTPUT-BUFFER, REPLACE.
291 If REPLACE is non-nil, that means insert the output
292 in place of text from START to END, putting point and mark around it.
293
294 If the output is one line, it is displayed in the echo area,
295 but it is nonetheless available in buffer `*Shell Command Output*'
296 even though that buffer is not automatically displayed.
297 If there is no output, or if output is inserted in the current buffer,
298 then `*Shell Command Output*' is deleted.
299
300 If the optional fourth argument OUTPUT-BUFFER is non-nil,
301 that says to put the output in some other buffer.
302 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
303 If OUTPUT-BUFFER is not a buffer and not nil,
304 insert output in the current buffer.
305 In either case, the output is inserted after point (leaving mark after it)."
306   (interactive (let ((string
307                       ;; Do this before calling region-beginning
308                       ;; and region-end, in case subprocess output
309                       ;; relocates them while we are in the minibuffer.
310                       (read-shell-command "Shell command on region: ")))
311                  ;; call-interactively recognizes region-beginning and
312                  ;; region-end specially, leaving them in the history.
313                  (list (region-beginning) (region-end)
314                        string
315                        current-prefix-arg
316                        current-prefix-arg)))
317   (if (or replace
318           (and output-buffer
319                (not (or (bufferp output-buffer) (stringp output-buffer)))))
320       ;; Replace specified region with output from command.
321       (let ((swap (and replace (< start end))))
322         ;; Don't muck with mark unless REPLACE says we should.
323         (goto-char start)
324         (and replace (push-mark))
325         (call-process-region start end shell-file-name t t nil
326                              shell-command-switch command)
327         (let ((shell-buffer (get-buffer "*Shell Command Output*")))
328           (and shell-buffer (not (eq shell-buffer (current-buffer)))
329                (kill-buffer shell-buffer)))
330         ;; Don't muck with mark unless REPLACE says we should.
331         (and replace swap (exchange-point-and-mark t)))
332       ;; No prefix argument: put the output in a temp buffer,
333       ;; replacing its entire contents.
334     (let ((buffer (get-buffer-create
335                    (or output-buffer "*Shell Command Output*")))
336           (success nil)
337           (exit-status nil)
338           (directory default-directory))
339       (unwind-protect
340           (if (eq buffer (current-buffer))
341               ;; If the input is the same buffer as the output,
342               ;; delete everything but the specified region,
343               ;; then replace that region with the output.
344               (progn (setq buffer-read-only nil)
345                      (delete-region (max start end) (point-max))
346                      (delete-region (point-min) (max start end))
347                      (setq exit-status
348                            (call-process-region (point-min) (point-max)
349                                                 shell-file-name t t nil
350                                                 shell-command-switch command))
351                      (setq success t))
352             ;; Clear the output buffer,
353             ;; then run the command with output there.
354             (save-excursion
355               (set-buffer buffer)
356               (setq buffer-read-only nil)
357               ;; XEmacs change
358               (setq default-directory directory)
359               (erase-buffer))
360             (setq exit-status
361                   (call-process-region start end shell-file-name
362                                        nil buffer nil
363                                        shell-command-switch command))
364             (setq success t))
365         ;; Report the amount of output.
366         (let ((lines (save-excursion
367                        (set-buffer buffer)
368                        (if (= (buffer-size) 0)
369                            0
370                          (count-lines (point-min) (point-max))))))
371           (cond ((= lines 0)
372                  (if success
373                      (display-message
374                       'command
375                       (if (eql exit-status 0)
376                           "(Shell command succeeded with no output)"
377                         "(Shell command failed with no output)")))
378                  (kill-buffer buffer))
379                 ((and success (= lines 1))
380                  (message "%s"
381                           (save-excursion
382                             (set-buffer buffer)
383                             (goto-char (point-min))
384                             (buffer-substring (point)
385                                               (progn (end-of-line)
386                                                      (point))))))
387                 (t
388                  (set-window-start (display-buffer buffer) 1))))))))
389
390 \f
391 (defun start-process (name buffer program &rest program-args)
392   "Start a program in a subprocess.  Return the process object for it.
393 Args are NAME BUFFER PROGRAM &rest PROGRAM-ARGS
394 NAME is name for process.  It is modified if necessary to make it unique.
395 BUFFER is the buffer or (buffer-name) to associate with the process.
396  Process output goes at end of that buffer, unless you specify
397  an output stream or filter function to handle the output.
398  BUFFER may be also nil, meaning that this process is not associated
399  with any buffer
400 Third arg is program file name.  It is searched for as in the shell.
401 Remaining arguments are strings to give program as arguments."
402   (apply 'start-process-internal name buffer program program-args))
403
404 (defun open-network-stream (name buffer host service &optional protocol)
405   "Open a TCP connection for a service to a host.
406 Returns a subprocess-object to represent the connection.
407 Input and output work as for subprocesses; `delete-process' closes it.
408 Args are NAME BUFFER HOST SERVICE.
409 NAME is name for process.  It is modified if necessary to make it unique.
410 BUFFER is the buffer (or buffer-name) to associate with the process.
411  Process output goes at end of that buffer, unless you specify
412  an output stream or filter function to handle the output.
413  BUFFER may be also nil, meaning that this process is not associated
414  with any buffer
415 Third arg is name of the host to connect to, or its IP address.
416 Fourth arg SERVICE is name of the service desired, or an integer
417  specifying a port number to connect to.
418 Fifth argument PROTOCOL is a network protocol.  Currently 'tcp
419  (Transmission Control Protocol) and 'udp (User Datagram Protocol) are
420  supported.  When omitted, 'tcp is assumed.
421
422 Ouput via `process-send-string' and input via buffer or filter (see
423 `set-process-filter') are stream-oriented.  That means UDP datagrams are
424 not guaranteed to be sent and received in discrete packets. (But small
425 datagrams around 500 bytes that are not truncated by `process-send-string'
426 are usually fine.)  Note further that UDP protocol does not guard against
427 lost packets."
428   (open-network-stream-internal name buffer host service protocol))
429
430 (defun shell-quote-argument (argument)
431   "Quote an argument for passing as argument to an inferior shell."
432   (if (eq system-type 'windows-nt)
433       (nt-quote-process-args (list shell-file-name argument))
434     ;; Quote everything except POSIX filename characters.
435     ;; This should be safe enough even for really weird shells.
436     (let ((result "") (start 0) end)
437       (while (string-match "[^-0-9a-zA-Z_./]" argument start)
438         (setq end (match-beginning 0)
439               result (concat result (substring argument start end)
440                              "\\" (substring argument end (1+ end)))
441               start (1+ end)))
442       (concat result (substring argument start)))))
443
444 (defun shell-command-to-string (command)
445   "Execute shell command COMMAND and return its output as a string."
446   (with-output-to-string
447     (call-process shell-file-name nil t nil shell-command-switch command)))
448
449 (defalias 'exec-to-string 'shell-command-to-string)
450
451 ;;; process.el ends here