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