1;;; server.el --- Lisp code for GNU Emacs running as server process
2
3;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4;;   2001, 2002, 2003, 2004, 2005, 2006, 2007 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., 51 Franklin Street, Fifth Floor,
27;; Boston, MA 02110-1301, 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 opens up a socket for communication with clients.  If there are no
36;; client buffers to edit, server-edit acts like (switch-to-buffer
37;; (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-use-tcp nil
86  "If non-nil, use TCP sockets instead of local sockets."
87  :set #'(lambda (sym val)
88           (unless (featurep 'make-network-process '(:family local))
89             (setq val t)
90             (unless load-in-progress
91               (message "Local sockets unsupported, using TCP sockets")))
92           (when val (random t))
93           (set-default sym val))
94  :group 'server
95  :type 'boolean
96  :version "22.1")
97
98(defcustom server-host nil
99  "The name or IP address to use as host address of the server process.
100If set, the server accepts remote connections; otherwise it is local."
101  :group 'server
102  :type '(choice
103          (string :tag "Name or IP address")
104          (const :tag "Local" nil))
105  :version "22.1")
106(put 'server-host 'risky-local-variable t)
107
108(defcustom server-auth-dir "~/.emacs.d/server/"
109  "Directory for server authentication files."
110  :group 'server
111  :type 'directory
112  :version "22.1")
113(put 'server-auth-dir 'risky-local-variable t)
114
115(defcustom server-raise-frame t
116  "If non-nil, raise frame when switching to a buffer."
117  :group 'server
118  :type 'boolean
119  :version "22.1")
120
121(defcustom server-visit-hook nil
122  "Hook run when visiting a file for the Emacs server."
123  :group 'server
124  :type 'hook)
125
126(defcustom server-switch-hook nil
127  "Hook run when switching to a buffer for the Emacs server."
128  :group 'server
129  :type 'hook)
130
131(defcustom server-done-hook nil
132  "Hook run when done editing a buffer for the Emacs server."
133  :group 'server
134  :type 'hook)
135
136(defvar server-process nil
137  "The current server process.")
138
139(defvar server-clients nil
140  "List of current server clients.
141Each element is (CLIENTID BUFFERS...) where CLIENTID is a string
142that can be given to the server process to identify a client.
143When a buffer is marked as \"done\", it is removed from this list.")
144
145(defvar server-buffer-clients nil
146  "List of client ids for clients requesting editing of current buffer.")
147(make-variable-buffer-local 'server-buffer-clients)
148;; Changing major modes should not erase this local.
149(put 'server-buffer-clients 'permanent-local t)
150
151(defcustom server-window nil
152  "Specification of the window to use for selecting Emacs server buffers.
153If nil, use the selected window.
154If it is a function, it should take one argument (a buffer) and
155display and select it.  A common value is `pop-to-buffer'.
156If it is a window, use that.
157If it is a frame, use the frame's selected window.
158
159It is not meaningful to set this to a specific frame or window with Custom.
160Only programs can do so."
161  :group 'server
162  :version "22.1"
163  :type '(choice (const :tag "Use selected window"
164			:match (lambda (widget value)
165				 (not (functionp value)))
166			nil)
167		 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
168		 (function :tag "Other function")))
169
170(defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
171  "Regexp matching names of temporary files.
172These are deleted and reused after each edit by the programs that
173invoke the Emacs server."
174  :group 'server
175  :type 'regexp)
176
177(defcustom server-kill-new-buffers t
178  "Whether to kill buffers when done with them.
179If non-nil, kill a buffer unless it already existed before editing
180it with Emacs server.  If nil, kill only buffers as specified by
181`server-temp-file-regexp'.
182Please note that only buffers are killed that still have a client,
183i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
184this way."
185  :group 'server
186  :type 'boolean
187  :version "21.1")
188
189(or (assq 'server-buffer-clients minor-mode-alist)
190    (push '(server-buffer-clients " Server") minor-mode-alist))
191
192(defvar server-existing-buffer nil
193  "Non-nil means the buffer existed before the server was asked to visit it.
194This means that the server should not kill the buffer when you say you
195are done with it in the server.")
196(make-variable-buffer-local 'server-existing-buffer)
197
198(defvar server-name "server")
199
200(defvar server-socket-dir
201  (format "/tmp/emacs%d" (user-uid)))
202
203(defun server-log (string &optional client)
204  "If a *server* buffer exists, write STRING to it for logging purposes."
205  (when (get-buffer "*server*")
206    (with-current-buffer "*server*"
207      (goto-char (point-max))
208      (insert (current-time-string)
209	      (if client (format " %s:" client) " ")
210	      string)
211      (or (bolp) (newline)))))
212
213(defun server-sentinel (proc msg)
214  (let ((client (assq proc server-clients)))
215    ;; Remove PROC from the list of clients.
216    (when client
217      (setq server-clients (delq client server-clients))
218      (dolist (buf (cdr client))
219	(with-current-buffer buf
220	  ;; Remove PROC from the clients of each buffer.
221	  (setq server-buffer-clients (delq proc server-buffer-clients))
222	  ;; Kill the buffer if necessary.
223	  (when (and (null server-buffer-clients)
224		     (or (and server-kill-new-buffers
225			      (not server-existing-buffer))
226			 (server-temp-file-p)))
227	    (kill-buffer (current-buffer)))))))
228  ;; If this is a new client process, set the query-on-exit flag to nil
229  ;; for this process (it isn't inherited from the server process).
230  (when (and (eq (process-status proc) 'open)
231	     (process-query-on-exit-flag proc))
232    (set-process-query-on-exit-flag proc nil))
233  ;; Delete the associated connection file, if applicable.
234  ;; This is actually problematic: the file may have been overwritten by
235  ;; another Emacs server in the mean time, so it's not ours any more.
236  ;; (and (process-contact proc :server)
237  ;;      (eq (process-status proc) 'closed)
238  ;;      (ignore-errors (delete-file (process-get proc :server-file))))
239  (server-log (format "Status changed to %s" (process-status proc)) proc))
240
241(defun server-select-display (display)
242  ;; If the current frame is on `display' we're all set.
243  (unless (equal (frame-parameter (selected-frame) 'display) display)
244    ;; Otherwise, look for an existing frame there and select it.
245    (dolist (frame (frame-list))
246      (when (equal (frame-parameter frame 'display) display)
247	(select-frame frame)))
248    ;; If there's no frame on that display yet, create and select one.
249    (unless (equal (frame-parameter (selected-frame) 'display) display)
250      (let* ((buffer (generate-new-buffer " *server-dummy*"))
251             (frame (make-frame-on-display
252                     display
253                     ;; Make it display (and remember) some dummy buffer, so
254                     ;; we can detect later if the frame is in use or not.
255                     `((server-dummmy-buffer . ,buffer)
256                       ;; This frame may be deleted later (see
257                       ;; server-unselect-display) so we want it to be as
258                       ;; unobtrusive as possible.
259                       (visibility . nil)))))
260        (select-frame frame)
261        (set-window-buffer (selected-window) buffer)))))
262
263(defun server-unselect-display (frame)
264  ;; If the temporary frame is in use (displays something real), make it
265  ;; visible.  If not (which can happen if the user's customizations call
266  ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
267  ;; the last real frame is deleted.
268  (if (and (eq (frame-first-window frame)
269               (next-window (frame-first-window frame) 'nomini))
270           (eq (window-buffer (frame-first-window frame))
271               (frame-parameter frame 'server-dummy-buffer)))
272      ;; The temp frame still only shows one buffer, and that is the
273      ;; internal temp buffer.
274      (delete-frame frame)
275    (set-frame-parameter frame 'visibility t))
276  (kill-buffer (frame-parameter frame 'server-dummy-buffer))
277  (set-frame-parameter frame 'server-dummy-buffer nil))
278
279(defun server-unquote-arg (arg)
280  (replace-regexp-in-string
281   "&." (lambda (s)
282	  (case (aref s 1)
283	    (?& "&")
284	    (?- "-")
285	    (?n "\n")
286	    (t " ")))
287   arg t t))
288
289(defun server-ensure-safe-dir (dir)
290  "Make sure DIR is a directory with no race-condition issues.
291Creates the directory if necessary and makes sure:
292- there's no symlink involved
293- it's owned by us
294- it's not readable/writable by anybody else."
295  (setq dir (directory-file-name dir))
296  (let ((attrs (file-attributes dir)))
297    (unless attrs
298      (letf (((default-file-modes) ?\700)) (make-directory dir t))
299      (setq attrs (file-attributes dir)))
300    ;; Check that it's safe for use.
301    (unless (and (eq t (car attrs)) (eql (nth 2 attrs) (user-uid))
302                 (or (eq system-type 'windows-nt)
303                     (zerop (logand ?\077 (file-modes dir)))))
304      (error "The directory %s is unsafe" dir))))
305
306;;;###autoload
307(defun server-start (&optional leave-dead)
308  "Allow this Emacs process to be a server for client processes.
309This starts a server communications subprocess through which
310client \"editors\" can send your editing commands to this Emacs job.
311To use the server, set up the program `emacsclient' in the
312Emacs distribution as your standard \"editor\".
313
314Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
315kill any existing server communications subprocess."
316  (interactive "P")
317  (when server-process
318    ;; kill it dead!
319    (ignore-errors (delete-process server-process)))
320  ;; If this Emacs already had a server, clear out associated status.
321  (while server-clients
322    (let ((buffer (nth 1 (car server-clients))))
323      (server-buffer-done buffer)))
324  ;; Now any previous server is properly stopped.
325  (unless leave-dead
326    (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
327           (server-file (expand-file-name server-name server-dir)))
328      ;; Make sure there is a safe directory in which to place the socket.
329      (server-ensure-safe-dir server-dir)
330      ;; Remove any leftover socket or authentication file.
331      (ignore-errors (delete-file server-file))
332      (when server-process
333        (server-log (message "Restarting server")))
334      (letf (((default-file-modes) ?\700))
335        (setq server-process
336              (apply #'make-network-process
337                     :name server-name
338                     :server t
339                     :noquery t
340                     :sentinel 'server-sentinel
341                     :filter 'server-process-filter
342                     ;; We must receive file names without being decoded.
343                     ;; Those are decoded by server-process-filter according
344                     ;; to file-name-coding-system.
345                     :coding 'raw-text
346                     ;; The rest of the args depends on the kind of socket used.
347                     (if server-use-tcp
348                         (list :family nil
349                               :service t
350                               :host (or server-host 'local)
351                               :plist '(:authenticated nil))
352                       (list :family 'local
353                             :service server-file
354                             :plist '(:authenticated t)))))
355        (unless server-process (error "Could not start server process"))
356        (when server-use-tcp
357          (let ((auth-key
358                 (loop
359                    ;; The auth key is a 64-byte string of random chars in the
360                    ;; range `!'..`~'.
361                    for i below 64
362                    collect (+ 33 (random 94)) into auth
363                    finally return (concat auth))))
364            (process-put server-process :auth-key auth-key)
365            (with-temp-file server-file
366              (set-buffer-multibyte nil)
367              (setq buffer-file-coding-system 'no-conversion)
368              (insert (format-network-address
369                       (process-contact server-process :local))
370                      " " (int-to-string (emacs-pid))
371                      "\n" auth-key))))))))
372
373;;;###autoload
374(define-minor-mode server-mode
375  "Toggle Server mode.
376With ARG, turn Server mode on if ARG is positive, off otherwise.
377Server mode runs a process that accepts commands from the
378`emacsclient' program.  See `server-start' and Info node `Emacs server'."
379  :global t
380  :group 'server
381  :version "22.1"
382  ;; Fixme: Should this check for an existing server socket and do
383  ;; nothing if there is one (for multiple Emacs sessions)?
384  (server-start (not server-mode)))
385
386(defun* server-process-filter (proc string)
387  "Process a request from the server to edit some files.
388PROC is the server process.  Format of STRING is \"PATH PATH PATH... \\n\"."
389  ;; First things first: let's check the authentication
390  (unless (process-get proc :authenticated)
391    (if (and (string-match "-auth \\(.*?\\)\n" string)
392             (equal (match-string 1 string) (process-get proc :auth-key)))
393        (progn
394          (setq string (substring string (match-end 0)))
395          (process-put proc :authenticated t)
396          (server-log "Authentication successful" proc))
397      (server-log "Authentication failed" proc)
398      (process-send-string proc "Authentication failed")
399      (delete-process proc)
400      ;; We return immediately
401      (return-from server-process-filter)))
402  (server-log string proc)
403  (let ((prev (process-get proc :previous-string)))
404    (when prev
405      (setq string (concat prev string))
406      (process-put proc :previous-string nil)))
407  (when (> (recursion-depth) 0)
408    ;; We're inside a minibuffer already, so if the emacs-client is trying
409    ;; to open a frame on a new display, we might end up with an unusable
410    ;; frame because input from that display will be blocked (until exiting
411    ;; the minibuffer).  Better exit this minibuffer right away.
412    ;; Similarly with recursive-edits such as the splash screen.
413    (process-put proc :previous-string string)
414    (run-with-timer 0 nil (lexical-let ((proc proc))
415                            (lambda () (server-process-filter proc ""))))
416    (top-level))
417  (condition-case nil
418      ;; If we're running isearch, we must abort it to allow Emacs to
419      ;; display the buffer and switch to it.
420      (mapc #'(lambda (buffer)
421		(with-current-buffer buffer
422		  (when (bound-and-true-p isearch-mode)
423		    (isearch-cancel))))
424	    (buffer-list))
425    ;; Signaled by isearch-cancel
426    (quit (message nil)))
427  ;; If the input is multiple lines,
428  ;; process each line individually.
429  (while (string-match "\n" string)
430    (let ((request (substring string 0 (match-beginning 0)))
431	  (coding-system (and default-enable-multibyte-characters
432			      (or file-name-coding-system
433				  default-file-name-coding-system)))
434	  client nowait eval
435	  (files nil)
436	  (lineno 1)
437	  (tmp-frame nil) ;; Sometimes used to embody the selected display.
438	  (columnno 0))
439      ;; Remove this line from STRING.
440      (setq string (substring string (match-end 0)))
441      (setq client (cons proc nil))
442      (while (string-match "[^ ]* " request)
443	(let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
444	  (setq request (substring request (match-end 0)))
445	  (cond
446            ((equal "-nowait" arg) (setq nowait t))
447            ((equal "-eval" arg) (setq eval t))
448            ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
449             (let ((display (server-unquote-arg (match-string 1 request))))
450               (setq request (substring request (match-end 0)))
451               (condition-case err
452                   (setq tmp-frame (server-select-display display))
453                 (error (process-send-string proc (nth 1 err))
454                        (setq request "")))))
455            ;; ARG is a line number option.
456            ((string-match "\\`\\+[0-9]+\\'" arg)
457             (setq lineno (string-to-number (substring arg 1))))
458            ;; ARG is line number:column option.
459            ((string-match "\\`+\\([0-9]+\\):\\([0-9]+\\)\\'" arg)
460             (setq lineno (string-to-number (match-string 1 arg))
461                   columnno (string-to-number (match-string 2 arg))))
462            (t
463             ;; Undo the quoting that emacsclient does
464             ;; for certain special characters.
465             (setq arg (server-unquote-arg arg))
466             ;; Now decode the file name if necessary.
467             (when coding-system
468               (setq arg (decode-coding-string arg coding-system)))
469             (if eval
470                 (let* (errorp
471                        (v (condition-case errobj
472                               (eval (car (read-from-string arg)))
473                             (error (setq errorp t) errobj))))
474                   (when v
475                     (with-temp-buffer
476                       (let ((standard-output (current-buffer)))
477                         (when errorp (princ "error: "))
478                         (pp v)
479                         (ignore-errors
480                           (process-send-region proc (point-min) (point-max)))
481                         ))))
482               ;; ARG is a file name.
483               ;; Collapse multiple slashes to single slashes.
484               (setq arg (command-line-normalize-file-name arg))
485               (push (list arg lineno columnno) files))
486             (setq lineno 1)
487             (setq columnno 0)))))
488      (when files
489	(run-hooks 'pre-command-hook)
490	(server-visit-files files client nowait)
491	(run-hooks 'post-command-hook))
492      ;; CLIENT is now a list (CLIENTNUM BUFFERS...)
493      (if (null (cdr client))
494	  ;; This client is empty; get rid of it immediately.
495	  (progn
496	    (delete-process proc)
497	    (server-log "Close empty client" proc))
498	;; We visited some buffer for this client.
499	(or nowait (push client server-clients))
500	(unless (or isearch-mode (minibufferp))
501	  (server-switch-buffer (nth 1 client))
502	  (run-hooks 'server-switch-hook)
503	  (unless nowait
504	    (message "%s" (substitute-command-keys
505                           "When done with a buffer, type \\[server-edit]")))))
506      (when (frame-live-p tmp-frame)
507        ;; Delete tmp-frame or make it visible depending on whether it's
508        ;; been used or not.
509        (server-unselect-display tmp-frame))))
510  ;; Save for later any partial line that remains.
511  (when (> (length string) 0)
512    (process-put proc :previous-string string)))
513
514(defun server-goto-line-column (file-line-col)
515  (goto-line (nth 1 file-line-col))
516  (let ((column-number (nth 2 file-line-col)))
517    (when (> column-number 0)
518      (move-to-column (1- column-number)))))
519
520(defun server-visit-files (files client &optional nowait)
521  "Find FILES and return the list CLIENT with the buffers nconc'd.
522FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
523NOWAIT non-nil means this client is not waiting for the results,
524so don't mark these buffers specially, just visit them normally."
525  ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
526  (let ((last-nonmenu-event t) client-record)
527    ;; Restore the current buffer afterward, but not using save-excursion,
528    ;; because we don't want to save point in this buffer
529    ;; if it happens to be one of those specified by the server.
530    (save-current-buffer
531      (dolist (file files)
532	;; If there is an existing buffer modified or the file is
533	;; modified, revert it.  If there is an existing buffer with
534	;; deleted file, offer to write it.
535	(let* ((minibuffer-auto-raise (or server-raise-frame
536                                          minibuffer-auto-raise))
537	       (filen (car file))
538	       (obuf (get-file-buffer filen)))
539	  (add-to-history 'file-name-history filen)
540	  (if (and obuf (set-buffer obuf))
541	      (progn
542		(cond ((file-exists-p filen)
543		       (when (not (verify-visited-file-modtime obuf))
544                         (revert-buffer t nil)))
545		      (t
546		       (when (y-or-n-p
547                              (concat "File no longer exists: "
548                                      filen
549                                      ", write buffer to file? "))
550                         (write-file filen))))
551		(setq server-existing-buffer t)
552		(server-goto-line-column file))
553	    (set-buffer (find-file-noselect filen))
554	    (server-goto-line-column file)
555	    (run-hooks 'server-visit-hook)))
556	(unless nowait
557	  ;; When the buffer is killed, inform the clients.
558	  (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
559	  (push (car client) server-buffer-clients))
560	(push (current-buffer) client-record)))
561    (nconc client client-record)))
562
563(defun server-buffer-done (buffer &optional for-killing)
564  "Mark BUFFER as \"done\" for its client(s).
565This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
566NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
567or nil.  KILLED is t if we killed BUFFER (typically, because it was visiting
568a temp file).
569FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
570  (let ((next-buffer nil)
571	(killed nil)
572	(old-clients server-clients))
573    (while old-clients
574      (let ((client (car old-clients)))
575	(or next-buffer
576	    (setq next-buffer (nth 1 (memq buffer client))))
577	(delq buffer client)
578	;; Delete all dead buffers from CLIENT.
579	(let ((tail client))
580	  (while tail
581	    (and (bufferp (car tail))
582		 (null (buffer-name (car tail)))
583		 (delq (car tail) client))
584	    (setq tail (cdr tail))))
585	;; If client now has no pending buffers,
586	;; tell it that it is done, and forget it entirely.
587	(unless (cdr client)
588	  (delete-process (car client))
589	  (server-log "Close" (car client))
590	  (setq server-clients (delq client server-clients))))
591      (setq old-clients (cdr old-clients)))
592    (when (and (bufferp buffer) (buffer-name buffer))
593      ;; We may or may not kill this buffer;
594      ;; if we do, do not call server-buffer-done recursively
595      ;; from kill-buffer-hook.
596      (let ((server-kill-buffer-running t))
597	(with-current-buffer buffer
598	  (setq server-buffer-clients nil)
599	  (run-hooks 'server-done-hook))
600	;; Notice whether server-done-hook killed the buffer.
601	(if (null (buffer-name buffer))
602	    (setq killed t)
603	  ;; Don't bother killing or burying the buffer
604	  ;; when we are called from kill-buffer.
605	  (unless for-killing
606	    (when (and (not killed)
607		       server-kill-new-buffers
608		       (with-current-buffer buffer
609			 (not server-existing-buffer)))
610	      (setq killed t)
611	      (bury-buffer buffer)
612	      (kill-buffer buffer))
613	    (unless killed
614	      (if (server-temp-file-p buffer)
615		  (progn
616		    (kill-buffer buffer)
617		    (setq killed t))
618		(bury-buffer buffer)))))))
619    (list next-buffer killed)))
620
621(defun server-temp-file-p (&optional buffer)
622  "Return non-nil if BUFFER contains a file considered temporary.
623These are files whose names suggest they are repeatedly
624reused to pass information to another program.
625
626The variable `server-temp-file-regexp' controls which filenames
627are considered temporary."
628  (and (buffer-file-name buffer)
629       (string-match server-temp-file-regexp (buffer-file-name buffer))))
630
631(defun server-done ()
632  "Offer to save current buffer, mark it as \"done\" for clients.
633This kills or buries the buffer, then returns a list
634of the form (NEXT-BUFFER KILLED).  NEXT-BUFFER is another server buffer,
635as a suggestion for what to select next, or nil.
636KILLED is t if we killed BUFFER, which happens if it was created
637specifically for the clients and did not exist before their request for it."
638  (when server-buffer-clients
639    (if (server-temp-file-p)
640	;; For a temp file, save, and do make a non-numeric backup
641	;; (unless make-backup-files is nil).
642	(let ((version-control nil)
643	      (buffer-backed-up nil))
644	  (save-buffer))
645      (when (and (buffer-modified-p)
646		 buffer-file-name
647		 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
648	(save-buffer)))
649    (server-buffer-done (current-buffer))))
650
651;; Ask before killing a server buffer.
652;; It was suggested to release its client instead,
653;; but I think that is dangerous--the client would proceed
654;; using whatever is on disk in that file. -- rms.
655(defun server-kill-buffer-query-function ()
656  (or (not server-buffer-clients)
657      (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
658			   (buffer-name (current-buffer))))))
659
660(add-hook 'kill-buffer-query-functions
661 	  'server-kill-buffer-query-function)
662
663(defun server-kill-emacs-query-function ()
664  (let (live-client
665	(tail server-clients))
666    ;; See if any clients have any buffers that are still alive.
667    (while tail
668      (when (memq t (mapcar 'stringp (mapcar 'buffer-name (cdr (car tail)))))
669	(setq live-client t))
670      (setq tail (cdr tail)))
671    (or (not live-client)
672	(yes-or-no-p "Server buffers still have clients; exit anyway? "))))
673
674(add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
675
676(defvar server-kill-buffer-running nil
677  "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
678
679(defun server-kill-buffer ()
680  ;; Prevent infinite recursion if user has made server-done-hook
681  ;; call kill-buffer.
682  (or server-kill-buffer-running
683      (and server-buffer-clients
684	   (let ((server-kill-buffer-running t))
685	     (when server-process
686	       (server-buffer-done (current-buffer) t))))))
687
688(defun server-edit (&optional arg)
689  "Switch to next server editing buffer; say \"Done\" for current buffer.
690If a server buffer is current, it is marked \"done\" and optionally saved.
691The buffer is also killed if it did not exist before the clients asked for it.
692When all of a client's buffers are marked as \"done\", the client is notified.
693
694Temporary files such as MH <draft> files are always saved and backed up,
695no questions asked.  (The variable `make-backup-files', if nil, still
696inhibits a backup; you can set it locally in a particular buffer to
697prevent a backup for it.)  The variable `server-temp-file-regexp' controls
698which filenames are considered temporary.
699
700If invoked with a prefix argument, or if there is no server process running,
701starts server process and that is all.  Invoked by \\[server-edit]."
702  (interactive "P")
703  (cond
704    ((or arg
705         (not server-process)
706         (memq (process-status server-process) '(signal exit)))
707     (server-mode 1))
708    (server-clients (apply 'server-switch-buffer (server-done)))
709    (t (message "No server editing buffers exist"))))
710
711(defun server-switch-buffer (&optional next-buffer killed-one)
712  "Switch to another buffer, preferably one that has a client.
713Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
714  ;; KILLED-ONE is t in a recursive call
715  ;; if we have already killed one temp-file server buffer.
716  ;; This means we should avoid the final "switch to some other buffer"
717  ;; since we've already effectively done that.
718  (if (null next-buffer)
719      (if server-clients
720	  (server-switch-buffer (nth 1 (car server-clients)) killed-one)
721	(unless (or killed-one (window-dedicated-p (selected-window)))
722	  (switch-to-buffer (other-buffer))
723	  (message "No server buffers remain to edit")))
724    (if (not (buffer-name next-buffer))
725	;; If NEXT-BUFFER is a dead buffer, remove the server records for it
726	;; and try the next surviving server buffer.
727	(apply 'server-switch-buffer (server-buffer-done next-buffer))
728      ;; OK, we know next-buffer is live, let's display and select it.
729      (if (functionp server-window)
730	  (funcall server-window next-buffer)
731	(let ((win (get-buffer-window next-buffer 0)))
732	  (if (and win (not server-window))
733	      ;; The buffer is already displayed: just reuse the window.
734              (progn
735                (select-window win)
736                (set-buffer next-buffer))
737	    ;; Otherwise, let's find an appropriate window.
738	    (cond ((and (windowp server-window)
739			(window-live-p server-window))
740		   (select-window server-window))
741		  ((framep server-window)
742		   (unless (frame-live-p server-window)
743		     (setq server-window (make-frame)))
744		   (select-window (frame-selected-window server-window))))
745	    (when (window-minibuffer-p (selected-window))
746	      (select-window (next-window nil 'nomini 0)))
747	    ;; Move to a non-dedicated window, if we have one.
748	    (when (window-dedicated-p (selected-window))
749	      (select-window
750	       (get-window-with-predicate
751		(lambda (w)
752		  (and (not (window-dedicated-p w))
753		       (equal (frame-parameter (window-frame w) 'display)
754			      (frame-parameter (selected-frame) 'display))))
755		'nomini 'visible (selected-window))))
756	    (condition-case nil
757		(switch-to-buffer next-buffer)
758	      ;; After all the above, we might still have ended up with
759	      ;; a minibuffer/dedicated-window (if there's no other).
760	      (error (pop-to-buffer next-buffer)))))))
761    (when server-raise-frame
762      (select-frame-set-input-focus (window-frame (selected-window))))))
763
764(define-key ctl-x-map "#" 'server-edit)
765
766(defun server-unload-hook ()
767  (server-mode -1)
768  (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
769  (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
770  (remove-hook 'kill-buffer-hook 'server-kill-buffer))
771
772(add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
773(add-hook 'server-unload-hook 'server-unload-hook)
774
775(provide 'server)
776
777;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
778;;; server.el ends here
779