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