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