2000-11-17 Katsumi Yamaoka <yamaoka@jpl.org>
[bpt/emacs.git] / lisp / server.el
CommitLineData
c88ab9ce
ER
1;;; server.el --- Lisp code for GNU Emacs running as server process.
2
ab1c7f35 3;; Copyright (C) 1986, 87, 92, 94, 95, 96, 1997 Free Software Foundation, Inc.
6d74b528 4
630cc463 5;; Author: William Sommerfeld <wesommer@athena.mit.edu>
e4874521 6;; Maintainer: FSF
d7b4d18f 7;; Keywords: processes
630cc463 8
9ae0f972 9;; Changes by peck@sun.com and by rms.
10
11;; This file is part of GNU Emacs.
12
13;; GNU Emacs is free software; you can redistribute it and/or modify
14;; it under the terms of the GNU General Public License as published by
e5167999 15;; the Free Software Foundation; either version 2, or (at your option)
9ae0f972 16;; any later version.
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
b578f267
EN
24;; along with GNU Emacs; see the file COPYING. If not, write to the
25;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26;; Boston, MA 02111-1307, USA.
9ae0f972 27
630cc463 28;;; Commentary:
9ae0f972 29
b578f267
EN
30;; This Lisp code is run in Emacs when it is to operate as
31;; a server for other processes.
9ae0f972 32
b578f267
EN
33;; Load this library and do M-x server-edit to enable Emacs as a server.
34;; Emacs runs the program ../arch-lib/emacsserver as a subprocess
35;; for communication with clients. If there are no client buffers to edit,
36;; server-edit acts like (switch-to-buffer (other-buffer))
9ae0f972 37
b578f267
EN
38;; When some other program runs "the editor" to edit a file,
39;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
40;; This program transmits the file names to Emacs through
41;; the server subprocess, and Emacs visits them and lets you edit them.
9ae0f972 42
b578f267 43;; Note that any number of clients may dispatch files to emacs to be edited.
9ae0f972 44
b578f267
EN
45;; When you finish editing a Server buffer, again call server-edit
46;; to mark that buffer as done for the client and switch to the next
47;; Server buffer. When all the buffers for a client have been edited
48;; and exited with server-edit, the client "editor" will return
49;; to the program that invoked it.
9ae0f972 50
b578f267
EN
51;; Your editing commands and Emacs's display output go to and from
52;; the terminal in the usual way. Thus, server operation is possible
53;; only when Emacs can talk to the terminal at the time you invoke
54;; the client. This is possible in four cases:
9ae0f972 55
b578f267
EN
56;; 1. On a window system, where Emacs runs in one window and the
57;; program that wants to use "the editor" runs in another.
9ae0f972 58
b578f267
EN
59;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
60;; program that wants to use "the editor" runs on another.
9ae0f972 61
b578f267
EN
62;; 3. When the program that wants to use "the editor" is running
63;; as a subprocess of Emacs.
9ae0f972 64
b578f267
EN
65;; 4. On a system with job control, when Emacs is suspended, the program
66;; that wants to use "the editor" will stop and display
67;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
68;; brought into the foreground for editing. When done editing, Emacs is
69;; suspended again, and the client program is brought into the foreground.
9ae0f972 70
b578f267
EN
71;; The buffer local variable "server-buffer-clients" lists
72;; the clients who are waiting for this buffer to be edited.
73;; The global variable "server-clients" lists all the waiting clients,
74;; and which files are yet to be edited for each.
630cc463
ER
75
76;;; Code:
9ae0f972 77\f
ab1c7f35
RS
78(defgroup server nil
79 "Emacs running as a server process."
80 :group 'external)
81
82(defcustom server-program (expand-file-name "emacsserver" exec-directory)
83 "*The program to use as the edit server."
84 :group 'server
85 :type 'string)
86
87(defcustom server-visit-hook nil
88 "*List of hooks to call when visiting a file for the Emacs server."
89 :group 'server
90 :type '(repeat function))
91
92(defcustom server-switch-hook nil
93 "*List of hooks to call when switching to a buffer for the Emacs server."
94 :group 'server
95 :type '(repeat function))
96
97(defcustom server-done-hook nil
98 "*List of hooks to call when done editing a buffer for the Emacs server."
99 :group 'server
100 :type '(repeat function))
f9b3ef88 101
9ae0f972 102(defvar server-process nil
103 "the current server process")
104
b53d289e
RS
105(defvar server-previous-string "")
106
9ae0f972 107(defvar server-clients nil
108 "List of current server clients.
e82e73c2 109Each element is (CLIENTID BUFFERS...) where CLIENTID is a string
9ae0f972 110that can be given to the server process to identify a client.
111When a buffer is marked as \"done\", it is removed from this list.")
112
113(defvar server-buffer-clients nil
114 "List of clientids for clients requesting editing of current buffer.")
faf931a8 115(make-variable-buffer-local 'server-buffer-clients)
9ae0f972 116;; Changing major modes should not erase this local.
117(put 'server-buffer-clients 'permanent-local t)
118
ec40ed9f
RS
119(defvar server-window nil
120 "*The window to use for selecting Emacs server buffers.
121If nil, use the selected window.
122If it is a frame, use the frame's selected window.")
123
ab1c7f35 124(defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
9ae0f972 125 "*Regexp which should match filenames of temporary files
126which are deleted and reused after each edit
c6a117f0 127by the programs that invoke the Emacs server."
ab1c7f35
RS
128 :group 'server
129 :type 'regexp)
9ae0f972 130
c6a117f0
GM
131(defcustom server-kill-new-buffers t
132 "*Whether to kill buffers when done with them.
133If non-nil, kill a buffer unless it already existed before editing
134it with Emacs server. If nil, kill only buffers as specified by
135`server-temp-file-regexp'.
136Please note that only buffers are killed that still have a client,
137i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
138this way."
139 :group 'server
140 :type 'boolean
141 :version "21.1")
142
9ae0f972 143(or (assq 'server-buffer-clients minor-mode-alist)
144 (setq minor-mode-alist (cons '(server-buffer-clients " Server") minor-mode-alist)))
145
c6a117f0
GM
146(defvar server-existing-buffer nil
147 "Non-nil means a server buffer existed before visiting a file.")
148(make-variable-buffer-local 'server-existing-buffer)
149
9ae0f972 150;; If a *server* buffer exists,
151;; write STRING to it for logging purposes.
152(defun server-log (string)
153 (if (get-buffer "*server*")
154 (save-excursion
155 (set-buffer "*server*")
156 (goto-char (point-max))
74c20cd3
RS
157 (insert (current-time-string) " " string)
158 (or (bolp) (newline)))))
9ae0f972 159
160(defun server-sentinel (proc msg)
161 (cond ((eq (process-status proc) 'exit)
162 (server-log (message "Server subprocess exited")))
163 ((eq (process-status proc) 'signal)
164 (server-log (message "Server subprocess killed")))))
165
7229064d 166;;;###autoload
9ae0f972 167(defun server-start (&optional leave-dead)
168 "Allow this Emacs process to be a server for client processes.
169This starts a server communications subprocess through which
170client \"editors\" can send your editing commands to this Emacs job.
42bbacdf 171To use the server, set up the program `emacsclient' in the
9ae0f972 172Emacs distribution as your standard \"editor\".
173
174Prefix arg means just kill any existing server communications subprocess."
175 (interactive "P")
176 ;; kill it dead!
177 (if server-process
178 (progn
179 (set-process-sentinel server-process nil)
180 (condition-case () (delete-process server-process) (error nil))))
c1148e39 181 ;; Delete the socket files made by previous server invocations.
14f67fa6
RS
182 (let* ((sysname (system-name))
183 (dot-index (string-match "\\." sysname)))
c1148e39
RS
184 (condition-case ()
185 (delete-file (format "~/.emacs-server-%s" sysname))
186 (error nil))
14f67fa6
RS
187 (condition-case ()
188 (delete-file (format "/tmp/esrv%d-%s" (user-uid) sysname))
189 (error nil))
190 ;; In case the server file name was made with a domainless hostname,
191 ;; try deleting that name too.
192 (if dot-index
c1148e39
RS
193 (let ((shortname (substring sysname 0 dot-index)))
194 (condition-case ()
195 (delete-file (format "~/.emacs-server-%s" shortname))
196 (error nil))
197 (condition-case ()
198 (delete-file (format "/tmp/esrv%d-%s" (user-uid) shortname))
199 (error nil)))))
200 ;; If this Emacs already had a server, clear out associated status.
9ae0f972 201 (while server-clients
202 (let ((buffer (nth 1 (car server-clients))))
203 (server-buffer-done buffer)))
204 (if leave-dead
205 nil
206 (if server-process
207 (server-log (message "Restarting server")))
838cd60d
RS
208 ;; Using a pty is wasteful, and the separate session causes
209 ;; annoyance sometimes (some systems kill idle sessions).
210 (let ((process-connection-type nil))
211 (setq server-process (start-process "server" nil server-program)))
9ae0f972 212 (set-process-sentinel server-process 'server-sentinel)
213 (set-process-filter server-process 'server-process-filter)
6b7430a8
KH
214 ;; We must receive file names without being decoded. Those are
215 ;; decoded by server-process-filter accoding to
216 ;; file-name-coding-system.
217 (set-process-coding-system server-process 'raw-text 'raw-text)
9ae0f972 218 (process-kill-without-query server-process)))
219\f
220;Process a request from the server to edit some files.
221;Format of STRING is "Client: CLIENTID PATH PATH PATH... \n"
222(defun server-process-filter (proc string)
223 (server-log string)
b53d289e 224 (setq string (concat server-previous-string string))
68469f74
RS
225 ;; If the input is multiple lines,
226 ;; process each line individually.
227 (while (string-match "\n" string)
228 (let ((request (substring string 0 (match-beginning 0)))
6b7430a8
KH
229 (coding-system (and default-enable-multibyte-characters
230 (or file-name-coding-system
231 default-file-name-coding-system)))
dfa35e6b 232 client nowait
9ae0f972 233 (files nil)
234 (lineno 1))
68469f74
RS
235 ;; Remove this line from STRING.
236 (setq string (substring string (match-end 0)))
7e721a4f 237 (if (string-match "^Error: " request)
26544100 238 (message "Server error: %s" (substring request (match-end 0)))
7e721a4f 239 (if (string-match "^Client: " request)
77e5a3c7
RS
240 (progn
241 (setq request (substring request (match-end 0)))
242 (setq client (list (substring request 0 (string-match " " request))))
243 (setq request (substring request (match-end 0)))
244 (while (string-match "[^ ]+ " request)
245 (let ((arg
8226e01e
RS
246 (substring request (match-beginning 0) (1- (match-end 0))))
247 (pos 0))
77e5a3c7 248 (setq request (substring request (match-end 0)))
dfa35e6b
RS
249 (if (string-match "\\`-nowait" arg)
250 (setq nowait t)
251 (if (string-match "\\`\\+[0-9]+\\'" arg)
252 ;; ARG is a line number option.
253 (setq lineno (read (substring arg 1)))
254 ;; ARG is a file name.
255 ;; Collapse multiple slashes to single slashes.
256 (setq arg (command-line-normalize-file-name arg))
349e3f82
RS
257 ;; Undo the quoting that emacsclient does
258 ;; for certain special characters.
b59a6343 259 (while (string-match "&." arg pos)
349e3f82
RS
260 (setq pos (1+ (match-beginning 0)))
261 (let ((nextchar (aref arg pos)))
b59a6343
RS
262 (cond ((= nextchar ?&)
263 (setq arg (replace-match "&" t t arg)))
349e3f82
RS
264 ((= nextchar ?-)
265 (setq arg (replace-match "-" t t arg)))
266 (t
267 (setq arg (replace-match " " t t arg))))))
6b7430a8
KH
268 ;; Now decode the file name if necessary.
269 (if coding-system
270 (setq arg (decode-coding-string arg coding-system)))
dfa35e6b
RS
271 (setq files
272 (cons (list arg lineno)
273 files))
274 (setq lineno 1)))))
275 (server-visit-files files client nowait)
77e5a3c7 276 ;; CLIENT is now a list (CLIENTNUM BUFFERS...)
0c40a645
KH
277 (if (null (cdr client))
278 ;; This client is empty; get rid of it immediately.
279 (progn
280 (send-string server-process
281 (format "Close: %s Done\n" (car client)))
282 (server-log (format "Close empty client: %s Done\n" (car client))))
283 ;; We visited some buffer for this client.
284 (or nowait
285 (setq server-clients (cons client server-clients)))
286 (server-switch-buffer (nth 1 client))
287 (run-hooks 'server-switch-hook)
288 (message (substitute-command-keys
289 "When done with a buffer, type \\[server-edit]"))))))))
68469f74
RS
290 ;; Save for later any partial line that remains.
291 (setq server-previous-string string))
9ae0f972 292
dfa35e6b 293(defun server-visit-files (files client &optional nowait)
9ae0f972 294 "Finds FILES and returns the list CLIENT with the buffers nconc'd.
dfa35e6b
RS
295FILES is an alist whose elements are (FILENAME LINENUMBER).
296NOWAIT non-nil means this client is not waiting for the results,
297so don't mark these buffers specially, just visit them normally."
e82e73c2
RS
298 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
299 (let (client-record (last-nonmenu-event t) (obuf (current-buffer)))
3a0ce849
RS
300 ;; Restore the current buffer afterward, but not using save-excursion,
301 ;; because we don't want to save point in this buffer
302 ;; if it happens to be one of those specified by the server.
303 (unwind-protect
304 (while files
c6a117f0
GM
305 ;; If there is an existing buffer modified or the file is
306 ;; modified, revert it. If there is an existing buffer with
307 ;; deleted file, offer to write it.
3a0ce849
RS
308 (let* ((filen (car (car files)))
309 (obuf (get-file-buffer filen)))
310 (if (and obuf (set-buffer obuf))
c6a117f0
GM
311 (cond ((file-exists-p filen)
312 (if (or (not (verify-visited-file-modtime obuf))
313 (buffer-modified-p obuf))
314 (revert-buffer t nil)))
315 (t
316 (if (y-or-n-p
317 (concat "File no longer exists: "
318 filen
319 ", write buffer to file? "))
320 (write-file filen))))
3a0ce849 321 (set-buffer (find-file-noselect filen))
c6a117f0 322 (setq server-existing-buffer t)
3a0ce849
RS
323 (run-hooks 'server-visit-hook)))
324 (goto-line (nth 1 (car files)))
dfa35e6b
RS
325 (if (not nowait)
326 (setq server-buffer-clients
327 (cons (car client) server-buffer-clients)))
3a0ce849
RS
328 (setq client-record (cons (current-buffer) client-record))
329 (setq files (cdr files)))
330 (set-buffer obuf))
9ae0f972 331 (nconc client client-record)))
332\f
b392bac9 333(defun server-buffer-done (buffer &optional for-killing)
9ae0f972 334 "Mark BUFFER as \"done\" for its client(s).
9184aafb
RS
335This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
336NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
599f9a5c
RS
337or nil. KILLED is t if we killed BUFFER
338\(typically, because it was visiting a temp file)."
9ae0f972 339 (let ((running (eq (process-status server-process) 'run))
340 (next-buffer nil)
9184aafb 341 (killed nil)
08c22983 342 (first t)
9ae0f972 343 (old-clients server-clients))
344 (while old-clients
345 (let ((client (car old-clients)))
346 (or next-buffer
347 (setq next-buffer (nth 1 (memq buffer client))))
348 (delq buffer client)
68469f74
RS
349 ;; Delete all dead buffers from CLIENT.
350 (let ((tail client))
351 (while tail
352 (and (bufferp (car tail))
353 (null (buffer-name (car tail)))
354 (delq (car tail) client))
355 (setq tail (cdr tail))))
9ae0f972 356 ;; If client now has no pending buffers,
357 ;; tell it that it is done, and forget it entirely.
358 (if (cdr client) nil
359 (if running
360 (progn
68469f74
RS
361 ;; Don't send emacsserver two commands in close succession.
362 ;; It cannot handle that.
08c22983
RS
363 (or first (sit-for 1))
364 (setq first nil)
365 (send-string server-process
366 (format "Close: %s Done\n" (car client)))
367 (server-log (format "Close: %s Done\n" (car client)))))
9ae0f972 368 (setq server-clients (delq client server-clients))))
369 (setq old-clients (cdr old-clients)))
68469f74 370 (if (and (bufferp buffer) (buffer-name buffer))
599f9a5c
RS
371 ;; We may or may not kill this buffer;
372 ;; if we do, do not call server-buffer-done recursively
373 ;; from kill-buffer-hook.
374 (let ((server-kill-buffer-running t))
faf931a8
RS
375 (save-excursion
376 (set-buffer buffer)
f9b3ef88
RS
377 (setq server-buffer-clients nil)
378 (run-hooks 'server-done-hook))
599f9a5c
RS
379 ;; Notice whether server-done-hook killed the buffer.
380 (if (null (buffer-name buffer))
381 (setq killed t)
382 ;; Don't bother killing or burying the buffer
383 ;; when we are called from kill-buffer.
384 (unless for-killing
c6a117f0
GM
385 (when (and (not killed)
386 server-kill-new-buffers
387 (save-excursion
388 (set-buffer buffer)
389 server-existing-buffer))
390 (setq killed t)
391 (kill-buffer buffer))
392 (unless killed
393 (if (server-temp-file-p buffer)
394 (progn
395 (kill-buffer buffer)
396 (setq killed t))
397 (bury-buffer buffer)))))))
9184aafb 398 (list next-buffer killed)))
9ae0f972 399
400(defun server-temp-file-p (buffer)
401 "Return non-nil if BUFFER contains a file considered temporary.
402These are files whose names suggest they are repeatedly
403reused to pass information to another program.
404
405The variable `server-temp-file-regexp' controls which filenames
406are considered temporary."
407 (and (buffer-file-name buffer)
408 (string-match server-temp-file-regexp (buffer-file-name buffer))))
409
410(defun server-done ()
cc9875f9 411 "Offer to save current buffer, mark it as \"done\" for clients.
9184aafb
RS
412This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
413NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
599f9a5c
RS
414or nil. KILLED is t if we killed BUFFER
415\(typically, because it was visiting a temp file)."
9ae0f972 416 (let ((buffer (current-buffer)))
417 (if server-buffer-clients
c58bf9ae 418 (progn
9ae0f972 419 (if (server-temp-file-p buffer)
991298c3
RS
420 ;; For a temp file, save, and do make a non-numeric backup
421 ;; (unless make-backup-files is nil).
422 (let ((version-control nil)
423 (buffer-backed-up nil))
c58bf9ae 424 (save-buffer))
9ae0f972 425 (if (and (buffer-modified-p)
ffdd2796 426 buffer-file-name
9ae0f972 427 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
428 (save-buffer buffer)))
c58bf9ae 429 (server-buffer-done buffer)))))
faf931a8 430
71207de2
RS
431;; Ask before killing a server buffer.
432;; It was suggested to release its client instead,
433;; but I think that is dangerous--the client would proceed
434;; using whatever is on disk in that file. -- rms.
03d78665
RS
435(defun server-kill-buffer-query-function ()
436 (or (not server-buffer-clients)
437 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
438 (buffer-name (current-buffer))))))
439
faf931a8 440(add-hook 'kill-buffer-query-functions
03d78665
RS
441 'server-kill-buffer-query-function)
442
443(defun server-kill-emacs-query-function ()
e82e73c2
RS
444 (let (live-client
445 (tail server-clients))
446 ;; See if any clients have any buffers that are still alive.
447 (while tail
448 (if (memq t (mapcar 'stringp (mapcar 'buffer-name (cdr (car tail)))))
449 (setq live-client t))
450 (setq tail (cdr tail)))
451 (or (not live-client)
452 (yes-or-no-p "Server buffers still have clients; exit anyway? "))))
03d78665
RS
453
454(add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
b392bac9 455
fb873cfc 456(defvar server-kill-buffer-running nil
599f9a5c 457 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
fb873cfc 458
b392bac9
RS
459;; When a buffer is killed, inform the clients.
460(add-hook 'kill-buffer-hook 'server-kill-buffer)
461(defun server-kill-buffer ()
fb873cfc
RS
462 ;; Prevent infinite recursion if user has made server-done-hook
463 ;; call kill-buffer.
464 (or server-kill-buffer-running
599f9a5c
RS
465 (and server-buffer-clients
466 (let ((server-kill-buffer-running t))
467 (when server-process
468 (server-buffer-done (current-buffer) t))))))
9ae0f972 469\f
470(defun server-edit (&optional arg)
471 "Switch to next server editing buffer; say \"Done\" for current buffer.
472If a server buffer is current, it is marked \"done\" and optionally saved.
473When all of a client's buffers are marked as \"done\", the client is notified.
474
475Temporary files such as MH <draft> files are always saved and backed up,
991298c3
RS
476no questions asked. (The variable `make-backup-files', if nil, still
477inhibits a backup; you can set it locally in a particular buffer to
478prevent a backup for it.) The variable `server-temp-file-regexp' controls
9ae0f972 479which filenames are considered temporary.
480
481If invoked with a prefix argument, or if there is no server process running,
482starts server process and that is all. Invoked by \\[server-edit]."
9ae0f972 483 (interactive "P")
484 (if (or arg
485 (not server-process)
486 (memq (process-status server-process) '(signal exit)))
487 (server-start nil)
9184aafb 488 (apply 'server-switch-buffer (server-done))))
9ae0f972 489
98a4349c 490(defun server-switch-buffer (&optional next-buffer killed-one)
9ae0f972 491 "Switch to another buffer, preferably one that has a client.
492Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
9184aafb
RS
493 ;; KILLED-ONE is t in a recursive call
494 ;; if we have already killed one temp-file server buffer.
495 ;; This means we should avoid the final "switch to some other buffer"
496 ;; since we've already effectively done that.
396e0e6a
RS
497 (cond ((and (windowp server-window)
498 (window-live-p server-window))
ec40ed9f
RS
499 (select-window server-window))
500 ((framep server-window)
396e0e6a
RS
501 (if (not (frame-live-p server-window))
502 (setq server-window (make-frame)))
ec40ed9f 503 (select-window (frame-selected-window server-window))))
e5ccf0c1 504 (if (window-minibuffer-p (selected-window))
02a8d137
RS
505 (select-window (next-window nil 'nomini 0)))
506 ;; Move to a non-dedicated window, if we have one.
6d4dd885
GM
507 (select-window (some-window (lambda (w) (not (window-dedicated-p w)))
508 'nomini 0 (selected-window)))
02a8d137 509 (set-window-dedicated-p (selected-window) nil)
9ae0f972 510 (if next-buffer
511 (if (and (bufferp next-buffer)
512 (buffer-name next-buffer))
513 (switch-to-buffer next-buffer)
514 ;; If NEXT-BUFFER is a dead buffer,
515 ;; remove the server records for it
516 ;; and try the next surviving server buffer.
9184aafb
RS
517 (apply 'server-switch-buffer
518 (server-buffer-done next-buffer)))
9ae0f972 519 (if server-clients
9184aafb
RS
520 (server-switch-buffer (nth 1 (car server-clients)) killed-one)
521 (if (not killed-one)
522 (switch-to-buffer (other-buffer))))))
9ae0f972 523
524(global-set-key "\C-x#" 'server-edit)
16c15321
RM
525\f
526(provide 'server)
c88ab9ce
ER
527
528;;; server.el ends here