XEmacs 21.2.28 "Hermes".
[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 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 ;;; Commentary:
30
31 ;; This file is dumped with XEmacs.
32
33 ;;; Code:
34
35 \f
36 (defgroup processes nil
37   "Process, subshell, compilation, and job control support."
38   :group 'external
39   :group 'development)
40
41 (defgroup processes-basics nil
42   "Basic stuff dealing with processes."
43   :group 'processes)
44
45 (defgroup execute nil
46   "Executing external commands."
47   :group 'processes)
48
49
50 (defvar shell-command-switch "-c"
51   "Switch used to have the shell execute its command line argument.")
52
53 (defun start-process-shell-command (name buffer &rest args)
54   "Start a program in a subprocess.  Return the process object for it.
55 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
56 NAME is name for process.  It is modified if necessary to make it unique.
57 BUFFER is the buffer or (buffer-name) to associate with the process.
58  Process output goes at end of that buffer, unless you specify
59  an output stream or filter function to handle the output.
60  BUFFER may be also nil, meaning that this process is not associated
61  with any buffer
62 Third arg is command name, the name of a shell command.
63 Remaining arguments are the arguments for the command.
64 Wildcards and redirection are handled as usual in the shell."
65   ;; We used to use `exec' to replace the shell with the command,
66   ;; but that failed to handle (...) and semicolon, etc.
67   (start-process name buffer shell-file-name shell-command-switch
68                  (mapconcat #'identity args " ")))
69
70 (defun call-process (program &optional infile buffer displayp &rest args)
71   "Call PROGRAM synchronously in separate process.
72 The program's input comes from file INFILE (nil means `/dev/null').
73 Insert output in BUFFER before point; t means current buffer;
74  nil for BUFFER means discard it; 0 means discard and don't wait.
75 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
76 REAL-BUFFER says what to do with standard output, as above,
77 while STDERR-FILE says what to do with standard error in the child.
78 STDERR-FILE may be nil (discard standard error output),
79 t (mix it with ordinary output), or a file name string.
80
81 Fourth arg DISPLAYP non-nil means redisplay buffer as output is inserted.
82 Remaining arguments are strings passed as command arguments to PROGRAM.
83
84 If BUFFER is 0, `call-process' returns immediately with value nil.
85 Otherwise it waits for PROGRAM to terminate and returns a numeric exit status
86  or a signal description string.
87 If you quit, the process is killed with SIGINT, or SIGKILL if you
88  quit again."
89   (apply 'call-process-internal program infile buffer displayp args))
90
91 (defun call-process-region (start end program
92                             &optional deletep buffer displayp
93                             &rest args)
94   "Send text from START to END to a synchronous process running PROGRAM.
95 Delete the text if fourth arg DELETEP is non-nil.
96
97 Insert output in BUFFER before point; t means current buffer;
98  nil for BUFFER means discard it; 0 means discard and don't wait.
99 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
100 REAL-BUFFER says what to do with standard output, as above,
101 while STDERR-FILE says what to do with standard error in the child.
102 STDERR-FILE may be nil (discard standard error output),
103 t (mix it with ordinary output), or a file name string.
104
105 Sixth arg DISPLAYP non-nil means redisplay buffer as output is inserted.
106 Remaining args are passed to PROGRAM at startup as command args.
107
108 If BUFFER is 0, returns immediately with value nil.
109 Otherwise waits for PROGRAM to terminate
110 and returns a numeric exit status or a signal description string.
111 If you quit, the process is first killed with SIGINT, then with SIGKILL if
112 you quit again before the process exits."
113   (let ((temp
114          (make-temp-name
115           (concat (file-name-as-directory (temp-directory)) "emacs"))))
116     (unwind-protect
117         (progn
118           (write-region start end temp nil 'silent)
119           (if deletep (delete-region start end))
120           (apply #'call-process program temp buffer displayp args))
121       (ignore-file-errors (delete-file temp)))))
122
123 \f
124 (defun shell-command (command &optional output-buffer)
125   "Execute string COMMAND in inferior shell; display output, if any.
126
127 If COMMAND ends in ampersand, execute it asynchronously.
128 The output appears in the buffer `*Async Shell Command*'.
129 That buffer is in shell mode.
130
131 Otherwise, COMMAND is executed synchronously.  The output appears in the
132 buffer `*Shell Command Output*'.
133 If the output is one line, it is displayed in the echo area *as well*,
134 but it is nonetheless available in buffer `*Shell Command Output*',
135 even though that buffer is not automatically displayed.
136 If there is no output, or if output is inserted in the current buffer,
137 then `*Shell Command Output*' is deleted.
138
139 The optional second argument OUTPUT-BUFFER, if non-nil,
140 says to put the output in some other buffer.
141 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
142 If OUTPUT-BUFFER is not a buffer and not nil,
143 insert output in current buffer.  (This cannot be done asynchronously.)
144 In either case, the output is inserted after point (leaving mark after it)."
145   (interactive (list (read-shell-command "Shell command: ")
146                      current-prefix-arg))
147   (if (and output-buffer
148            (not (or (bufferp output-buffer)  (stringp output-buffer))))
149       (progn (barf-if-buffer-read-only)
150              (push-mark)
151              ;; We do not use -f for csh; we will not support broken use of
152              ;; .cshrcs.  Even the BSD csh manual says to use
153              ;; "if ($?prompt) exit" before things which are not useful
154              ;; non-interactively.  Besides, if someone wants their other
155              ;; aliases for shell commands then they can still have them.
156              (call-process shell-file-name nil t nil
157                            shell-command-switch command)
158              (exchange-point-and-mark t))
159     ;; Preserve the match data in case called from a program.
160     (save-match-data
161       (if (string-match "[ \t]*&[ \t]*$" command)
162           ;; Command ending with ampersand means asynchronous.
163           (progn
164             (background (substring command 0 (match-beginning 0))))
165         (shell-command-on-region (point) (point) command output-buffer)))))
166
167 ;; We have a sentinel to prevent insertion of a termination message
168 ;; in the buffer itself.
169 (defun shell-command-sentinel (process signal)
170   (if (memq (process-status process) '(exit signal))
171       (message "%s: %s."
172                (car (cdr (cdr (process-command process))))
173                (substring signal 0 -1))))
174
175 (defun shell-command-on-region (start end command
176                                       &optional output-buffer replace)
177   "Execute string COMMAND in inferior shell with region as input.
178 Normally display output (if any) in temp buffer `*Shell Command Output*';
179 Prefix arg means replace the region with it.
180
181 The noninteractive arguments are START, END, COMMAND, OUTPUT-BUFFER, REPLACE.
182 If REPLACE is non-nil, that means insert the output
183 in place of text from START to END, putting point and mark around it.
184
185 If the output is one line, it is displayed in the echo area,
186 but it is nonetheless available in buffer `*Shell Command Output*'
187 even though that buffer is not automatically displayed.
188 If there is no output, or if output is inserted in the current buffer,
189 then `*Shell Command Output*' is deleted.
190
191 If the optional fourth argument OUTPUT-BUFFER is non-nil,
192 that says to put the output in some other buffer.
193 If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
194 If OUTPUT-BUFFER is not a buffer and not nil,
195 insert output in the current buffer.
196 In either case, the output is inserted after point (leaving mark after it)."
197   (interactive (let ((string
198                       ;; Do this before calling region-beginning
199                       ;; and region-end, in case subprocess output
200                       ;; relocates them while we are in the minibuffer.
201                       (read-shell-command "Shell command on region: ")))
202                  ;; call-interactively recognizes region-beginning and
203                  ;; region-end specially, leaving them in the history.
204                  (list (region-beginning) (region-end)
205                        string
206                        current-prefix-arg
207                        current-prefix-arg)))
208   (if (or replace
209           (and output-buffer
210                (not (or (bufferp output-buffer) (stringp output-buffer)))))
211       ;; Replace specified region with output from command.
212       (let ((swap (and replace (< start end))))
213         ;; Don't muck with mark unless REPLACE says we should.
214         (goto-char start)
215         (and replace (push-mark))
216         (call-process-region start end shell-file-name t t nil
217                              shell-command-switch command)
218         (let ((shell-buffer (get-buffer "*Shell Command Output*")))
219           (and shell-buffer (not (eq shell-buffer (current-buffer)))
220                (kill-buffer shell-buffer)))
221         ;; Don't muck with mark unless REPLACE says we should.
222         (and replace swap (exchange-point-and-mark t)))
223       ;; No prefix argument: put the output in a temp buffer,
224       ;; replacing its entire contents.
225     (let ((buffer (get-buffer-create
226                    (or output-buffer "*Shell Command Output*")))
227           (success nil)
228           (exit-status nil)
229           (directory default-directory))
230       (unwind-protect
231           (if (eq buffer (current-buffer))
232               ;; If the input is the same buffer as the output,
233               ;; delete everything but the specified region,
234               ;; then replace that region with the output.
235               (progn (setq buffer-read-only nil)
236                      (delete-region (max start end) (point-max))
237                      (delete-region (point-min) (max start end))
238                      (setq exit-status
239                            (call-process-region (point-min) (point-max)
240                                                 shell-file-name t t nil
241                                                 shell-command-switch command))
242                      (setq success t))
243             ;; Clear the output buffer,
244             ;; then run the command with output there.
245             (save-excursion
246               (set-buffer buffer)
247               (setq buffer-read-only nil)
248               ;; XEmacs change
249               (setq default-directory directory)
250               (erase-buffer))
251             (setq exit-status
252                   (call-process-region start end shell-file-name
253                                        nil buffer nil
254                                        shell-command-switch command))
255             (setq success t))
256         ;; Report the amount of output.
257         (let ((lines (save-excursion
258                        (set-buffer buffer)
259                        (if (= (buffer-size) 0)
260                            0
261                          (count-lines (point-min) (point-max))))))
262           (cond ((= lines 0)
263                  (if success
264                      (display-message
265                       'command
266                       (if (eql exit-status 0)
267                           "(Shell command succeeded with no output)"
268                         "(Shell command failed with no output)")))
269                  (kill-buffer buffer))
270                 ((and success (= lines 1))
271                  (message "%s"
272                           (save-excursion
273                             (set-buffer buffer)
274                             (goto-char (point-min))
275                             (buffer-substring (point)
276                                               (progn (end-of-line)
277                                                      (point))))))
278                 (t
279                  (set-window-start (display-buffer buffer) 1))))))))
280
281 \f
282 (defun start-process (name buffer program &rest program-args)
283   "Start a program in a subprocess.  Return the process object for it.
284 Args are NAME BUFFER PROGRAM &rest PROGRAM-ARGS
285 NAME is name for process.  It is modified if necessary to make it unique.
286 BUFFER is the buffer or (buffer-name) to associate with the process.
287  Process output goes at end of that buffer, unless you specify
288  an output stream or filter function to handle the output.
289  BUFFER may be also nil, meaning that this process is not associated
290  with any buffer
291 Third arg is program file name.  It is searched for as in the shell.
292 Remaining arguments are strings to give program as arguments."
293   (apply 'start-process-internal name buffer program program-args))
294
295 (defun open-network-stream (name buffer host service &optional protocol)
296   "Open a TCP connection for a service to a host.
297 Returns a subprocess-object to represent the connection.
298 Input and output work as for subprocesses; `delete-process' closes it.
299 Args are NAME BUFFER HOST SERVICE.
300 NAME is name for process.  It is modified if necessary to make it unique.
301 BUFFER is the buffer (or buffer-name) to associate with the process.
302  Process output goes at end of that buffer, unless you specify
303  an output stream or filter function to handle the output.
304  BUFFER may be also nil, meaning that this process is not associated
305  with any buffer
306 Third arg is name of the host to connect to, or its IP address.
307 Fourth arg SERVICE is name of the service desired, or an integer
308  specifying a port number to connect to.
309 Fifth argument PROTOCOL is a network protocol.  Currently 'tcp
310  (Transmission Control Protocol) and 'udp (User Datagram Protocol) are
311  supported.  When omitted, 'tcp is assumed.
312
313 Ouput via `process-send-string' and input via buffer or filter (see
314 `set-process-filter') are stream-oriented.  That means UDP datagrams are
315 not guaranteed to be sent and received in discrete packets. (But small
316 datagrams around 500 bytes that are not truncated by `process-send-string'
317 are usually fine.)  Note further that UDP protocol does not guard against
318 lost packets."
319   (open-network-stream-internal name buffer host service protocol))
320
321 (defun shell-quote-argument (argument)
322   "Quote an argument for passing as argument to an inferior shell."
323   (if (eq system-type 'windows-nt)
324       (nt-quote-process-args (list shell-file-name argument))
325     ;; Quote everything except POSIX filename characters.
326     ;; This should be safe enough even for really weird shells.
327     (let ((result "") (start 0) end)
328       (while (string-match "[^-0-9a-zA-Z_./]" argument start)
329         (setq end (match-beginning 0)
330               result (concat result (substring argument start end)
331                              "\\" (substring argument end (1+ end)))
332               start (1+ end)))
333       (concat result (substring argument start)))))
334
335 (defun shell-command-to-string (command)
336   "Execute shell command COMMAND and return its output as a string."
337   (with-output-to-string
338     (call-process shell-file-name nil t nil shell-command-switch command)))
339
340 (defalias 'exec-to-string 'shell-command-to-string)
341
342 ;;; process.el ends here