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