]> code.delx.au - gnu-emacs/blob - lisp/server.el
Chris Moore <dooglus at gmail.com>
[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 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 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
12
13 ;; This file is part of GNU Emacs.
14
15 ;; GNU Emacs is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 3, or (at your option)
18 ;; any later version.
19
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING. If not, write to the
27 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28 ;; Boston, MA 02110-1301, USA.
29
30 ;;; Commentary:
31
32 ;; This Lisp code is run in Emacs when it is to operate as
33 ;; a server for other processes.
34
35 ;; Load this library and do M-x server-edit to enable Emacs as a server.
36 ;; Emacs opens up a socket for communication with clients. If there are no
37 ;; client buffers to edit, server-edit acts like (switch-to-buffer
38 ;; (other-buffer))
39
40 ;; When some other program runs "the editor" to edit a file,
41 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
42 ;; This program transmits the file names to Emacs through
43 ;; the server subprocess, and Emacs visits them and lets you edit them.
44
45 ;; Note that any number of clients may dispatch files to Emacs to be edited.
46
47 ;; When you finish editing a Server buffer, again call server-edit
48 ;; to mark that buffer as done for the client and switch to the next
49 ;; Server buffer. When all the buffers for a client have been edited
50 ;; and exited with server-edit, the client "editor" will return
51 ;; to the program that invoked it.
52
53 ;; Your editing commands and Emacs's display output go to and from
54 ;; the terminal in the usual way. Thus, server operation is possible
55 ;; only when Emacs can talk to the terminal at the time you invoke
56 ;; the client. This is possible in four cases:
57
58 ;; 1. On a window system, where Emacs runs in one window and the
59 ;; program that wants to use "the editor" runs in another.
60
61 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
62 ;; program that wants to use "the editor" runs on another.
63
64 ;; 3. When the program that wants to use "the editor" is running
65 ;; as a subprocess of Emacs.
66
67 ;; 4. On a system with job control, when Emacs is suspended, the program
68 ;; that wants to use "the editor" will stop and display
69 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
70 ;; brought into the foreground for editing. When done editing, Emacs is
71 ;; suspended again, and the client program is brought into the foreground.
72
73 ;; The buffer local variable "server-buffer-clients" lists
74 ;; the clients who are waiting for this buffer to be edited.
75 ;; The global variable "server-clients" lists all the waiting clients,
76 ;; and which files are yet to be edited for each.
77
78 ;;; Code:
79
80 (eval-when-compile (require 'cl))
81
82 (defgroup server nil
83 "Emacs running as a server process."
84 :group 'external)
85
86 (defcustom server-use-tcp nil
87 "If non-nil, use TCP sockets instead of local sockets."
88 :set #'(lambda (sym val)
89 (unless (featurep 'make-network-process '(:family local))
90 (setq val t)
91 (unless load-in-progress
92 (message "Local sockets unsupported, using TCP sockets")))
93 (when val (random t))
94 (set-default sym val))
95 :group 'server
96 :type 'boolean
97 :version "22.1")
98
99 (defcustom server-host nil
100 "The name or IP address to use as host address of the server process.
101 If set, the server accepts remote connections; otherwise it is local."
102 :group 'server
103 :type '(choice
104 (string :tag "Name or IP address")
105 (const :tag "Local" nil))
106 :version "22.1")
107 (put 'server-host 'risky-local-variable t)
108
109 (defcustom server-auth-dir (concat user-emacs-directory "server/")
110 "Directory for server authentication files."
111 :group 'server
112 :type 'directory
113 :version "22.1")
114 (put 'server-auth-dir 'risky-local-variable t)
115
116 (defcustom server-raise-frame t
117 "If non-nil, raise frame when switching to a buffer."
118 :group 'server
119 :type 'boolean
120 :version "22.1")
121
122 (defcustom server-visit-hook nil
123 "Hook run when visiting a file for the Emacs server."
124 :group 'server
125 :type 'hook)
126
127 (defcustom server-switch-hook nil
128 "Hook run when switching to a buffer for the Emacs server."
129 :group 'server
130 :type 'hook)
131
132 (defcustom server-done-hook nil
133 "Hook run when done editing a buffer for the Emacs server."
134 :group 'server
135 :type 'hook)
136
137 (defvar server-process nil
138 "The current server process.")
139
140 (defvar server-clients nil
141 "List of current server clients.
142 Each element is a process.")
143
144 (defvar server-buffer-clients nil
145 "List of client processes requesting editing of current buffer.")
146 (make-variable-buffer-local 'server-buffer-clients)
147 ;; Changing major modes should not erase this local.
148 (put 'server-buffer-clients 'permanent-local t)
149
150 (defcustom server-window nil
151 "Specification of the window to use for selecting Emacs server buffers.
152 If nil, use the selected window.
153 If it is a function, it should take one argument (a buffer) and
154 display and select it. A common value is `pop-to-buffer'.
155 If it is a window, use that.
156 If it is a frame, use the frame's selected window.
157
158 It is not meaningful to set this to a specific frame or window with Custom.
159 Only programs can do so."
160 :group 'server
161 :version "22.1"
162 :type '(choice (const :tag "Use selected window"
163 :match (lambda (widget value)
164 (not (functionp value)))
165 nil)
166 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
167 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
168 (function :tag "Other function")))
169
170 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
171 "Regexp matching names of temporary files.
172 These are deleted and reused after each edit by the programs that
173 invoke the Emacs server."
174 :group 'server
175 :type 'regexp)
176
177 (defcustom server-kill-new-buffers t
178 "Whether to kill buffers when done with them.
179 If non-nil, kill a buffer unless it already existed before editing
180 it with the Emacs server. If nil, kill only buffers as specified by
181 `server-temp-file-regexp'.
182 Please note that only buffers that still have a client are killed,
183 i.e. buffers visited with \"emacsclient --no-wait\" are never killed in
184 this way."
185 :group 'server
186 :type 'boolean
187 :version "21.1")
188
189 (or (assq 'server-buffer-clients minor-mode-alist)
190 (push '(server-buffer-clients " Server") minor-mode-alist))
191
192 (defvar server-existing-buffer nil
193 "Non-nil means the buffer existed before the server was asked to visit it.
194 This means that the server should not kill the buffer when you say you
195 are done with it in the server.")
196 (make-variable-buffer-local 'server-existing-buffer)
197
198 (defvar server-name "server")
199
200 (defvar server-socket-dir nil
201 "The directory in which to place the server socket.
202 Initialized by `server-start'.")
203
204 (defun server-clients-with (property value)
205 "Return a list of clients with PROPERTY set to VALUE."
206 (let (result)
207 (dolist (proc server-clients result)
208 (when (equal value (process-get proc property))
209 (push proc result)))))
210
211 (defun server-add-client (proc)
212 "Create a client for process PROC, if it doesn't already have one.
213 New clients have no properties."
214 (add-to-list 'server-clients proc))
215
216 (defmacro server-with-environment (env vars &rest body)
217 "Evaluate BODY with environment variables VARS set to those in ENV.
218 The environment variables are then restored to their previous values.
219
220 VARS should be a list of strings.
221 ENV should be in the same format as `process-environment'."
222 (declare (indent 2))
223 (let ((var (make-symbol "var"))
224 (value (make-symbol "value")))
225 `(let ((process-environment process-environment))
226 (dolist (,var ,vars)
227 (let ((,value (getenv-internal ,var ,env)))
228 (push (if (null ,value)
229 ,var
230 (concat ,var "=" ,value))
231 process-environment)))
232 (progn ,@body))))
233
234 (defun server-delete-client (proc &optional noframe)
235 "Delete CLIENT, including its buffers, terminals and frames.
236 If NOFRAME is non-nil, let the frames live. (To be used from
237 `delete-frame-functions'.)"
238 (server-log (concat "server-delete-client" (if noframe " noframe"))
239 proc)
240 ;; Force a new lookup of client (prevents infinite recursion).
241 (when (memq proc server-clients)
242 (let ((buffers (process-get proc 'buffers)))
243
244 ;; Kill the client's buffers.
245 (dolist (buf buffers)
246 (when (buffer-live-p buf)
247 (with-current-buffer buf
248 ;; Kill the buffer if necessary.
249 (when (and (equal server-buffer-clients
250 (list proc))
251 (or (and server-kill-new-buffers
252 (not server-existing-buffer))
253 (server-temp-file-p))
254 (not (buffer-modified-p)))
255 (let (flag)
256 (unwind-protect
257 (progn (setq server-buffer-clients nil)
258 (kill-buffer (current-buffer))
259 (setq flag t))
260 (unless flag
261 ;; Restore clients if user pressed C-g in `kill-buffer'.
262 (setq server-buffer-clients (list proc)))))))))
263
264 ;; Delete the client's frames.
265 (unless noframe
266 (dolist (frame (frame-list))
267 (when (and (frame-live-p frame)
268 (equal proc (frame-parameter frame 'client)))
269 ;; Prevent `server-handle-delete-frame' from calling us
270 ;; recursively.
271 (set-frame-parameter frame 'client nil)
272 (delete-frame frame))))
273
274 (setq server-clients (delq proc server-clients))
275
276 ;; Delete the client's tty.
277 (let ((terminal (process-get proc 'terminal)))
278 ;; Only delete the terminal if it is non-nil.
279 (when (and terminal (eq (terminal-live-p terminal) t))
280 (delete-terminal terminal)))
281
282 ;; Delete the client's process.
283 (if (eq (process-status proc) 'open)
284 (delete-process proc))
285
286 (server-log "Deleted" proc))))
287
288 (defun server-log (string &optional client)
289 "If a *server* buffer exists, write STRING to it for logging purposes.
290 If CLIENT is non-nil, add a description of it to the logged
291 message."
292 (when (get-buffer "*server*")
293 (with-current-buffer "*server*"
294 (goto-char (point-max))
295 (insert (current-time-string)
296 (cond
297 ((null client) " ")
298 ((listp client) (format " %s: " (car client)))
299 (t (format " %s: " client)))
300 string)
301 (or (bolp) (newline)))))
302
303 (defun server-sentinel (proc msg)
304 "The process sentinel for Emacs server connections."
305 ;; If this is a new client process, set the query-on-exit flag to nil
306 ;; for this process (it isn't inherited from the server process).
307 (when (and (eq (process-status proc) 'open)
308 (process-query-on-exit-flag proc))
309 (set-process-query-on-exit-flag proc nil))
310 ;; Delete the associated connection file, if applicable.
311 ;; This is actually problematic: the file may have been overwritten by
312 ;; another Emacs server in the mean time, so it's not ours any more.
313 ;; (and (process-contact proc :server)
314 ;; (eq (process-status proc) 'closed)
315 ;; (ignore-errors (delete-file (process-get proc :server-file))))
316 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
317 (server-delete-client proc))
318
319 (defun server-select-display (display)
320 ;; If the current frame is on `display' we're all set.
321 (unless (equal (frame-parameter (selected-frame) 'display) display)
322 ;; Otherwise, look for an existing frame there and select it.
323 (dolist (frame (frame-list))
324 (when (equal (frame-parameter frame 'display) display)
325 (select-frame frame)))
326 ;; If there's no frame on that display yet, create and select one.
327 (unless (equal (frame-parameter (selected-frame) 'display) display)
328 (let* ((buffer (generate-new-buffer " *server-dummy*"))
329 (frame (make-frame-on-display
330 display
331 ;; Make it display (and remember) some dummy buffer, so
332 ;; we can detect later if the frame is in use or not.
333 `((server-dummmy-buffer . ,buffer)
334 ;; This frame may be deleted later (see
335 ;; server-unselect-display) so we want it to be as
336 ;; unobtrusive as possible.
337 (visibility . nil)))))
338 (select-frame frame)
339 (set-window-buffer (selected-window) buffer)
340 frame))))
341
342 (defun server-unselect-display (frame)
343 (when (frame-live-p frame)
344 ;; If the temporary frame is in use (displays something real), make it
345 ;; visible. If not (which can happen if the user's customizations call
346 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
347 ;; the last real frame is deleted.
348 (if (and (eq (frame-first-window frame)
349 (next-window (frame-first-window frame) 'nomini))
350 (eq (window-buffer (frame-first-window frame))
351 (frame-parameter frame 'server-dummy-buffer)))
352 ;; The temp frame still only shows one buffer, and that is the
353 ;; internal temp buffer.
354 (delete-frame frame)
355 (set-frame-parameter frame 'visibility t))
356 (kill-buffer (frame-parameter frame 'server-dummy-buffer))
357 (set-frame-parameter frame 'server-dummy-buffer nil)))
358
359 (defun server-handle-delete-frame (frame)
360 "Delete the client connection when the emacsclient frame is deleted."
361 (let ((proc (frame-parameter frame 'client)))
362 (when (and (frame-live-p frame)
363 proc
364 ;; See if this is the last frame for this client.
365 (>= 1 (let ((frame-num 0))
366 (dolist (f (frame-list))
367 (when (eq proc (frame-parameter f 'client))
368 (setq frame-num (1+ frame-num))))
369 frame-num)))
370 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
371 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
372
373 (defun server-handle-suspend-tty (terminal)
374 "Notify the emacsclient process to suspend itself when its tty device is suspended."
375 (dolist (proc (server-clients-with 'terminal terminal))
376 (server-log (format "server-handle-suspend-tty, terminal %s" terminal) proc)
377 (condition-case err
378 (server-send-string proc "-suspend \n")
379 (file-error ;The pipe/socket was closed.
380 (ignore-errors (server-delete-client proc))))))
381
382 (defun server-unquote-arg (arg)
383 "Remove &-quotation from ARG.
384 See `server-quote-arg' and `server-process-filter'."
385 (replace-regexp-in-string
386 "&." (lambda (s)
387 (case (aref s 1)
388 (?& "&")
389 (?- "-")
390 (?n "\n")
391 (t " ")))
392 arg t t))
393
394 (defun server-quote-arg (arg)
395 "In ARG, insert a & before each &, each space, each newline, and -.
396 Change spaces to underscores, too, so that the return value never
397 contains a space.
398
399 See `server-unquote-arg' and `server-process-filter'."
400 (replace-regexp-in-string
401 "[-&\n ]" (lambda (s)
402 (case (aref s 0)
403 (?& "&&")
404 (?- "&-")
405 (?\n "&n")
406 (?\s "&_")))
407 arg t t))
408
409 (defun server-send-string (proc string)
410 "A wrapper around `proc-send-string' for logging."
411 (server-log (concat "Sent " string) proc)
412 (process-send-string proc string))
413
414 (defun server-ensure-safe-dir (dir)
415 "Make sure DIR is a directory with no race-condition issues.
416 Creates the directory if necessary and makes sure:
417 - there's no symlink involved
418 - it's owned by us
419 - it's not readable/writable by anybody else."
420 (setq dir (directory-file-name dir))
421 (let ((attrs (file-attributes dir)))
422 (unless attrs
423 (letf (((default-file-modes) ?\700)) (make-directory dir t))
424 (setq attrs (file-attributes dir)))
425 ;; Check that it's safe for use.
426 (unless (and (eq t (car attrs)) (eql (nth 2 attrs) (user-uid))
427 (or (eq system-type 'windows-nt)
428 (zerop (logand ?\077 (file-modes dir)))))
429 (error "The directory %s is unsafe" dir))))
430
431 ;;;###autoload
432 (defun server-start (&optional leave-dead)
433 "Allow this Emacs process to be a server for client processes.
434 This starts a server communications subprocess through which
435 client \"editors\" can send your editing commands to this Emacs
436 job. To use the server, set up the program `emacsclient' in the
437 Emacs distribution as your standard \"editor\".
438
439 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
440 kill any existing server communications subprocess."
441 (interactive "P")
442 (when (or
443 (not server-clients)
444 (yes-or-no-p
445 "The current server still has clients; delete them? "))
446 ;; It is safe to get the user id now.
447 (setq server-socket-dir (or server-socket-dir
448 (format "/tmp/emacs%d" (user-uid))))
449 (when server-process
450 ;; kill it dead!
451 (ignore-errors (delete-process server-process)))
452 ;; Delete the socket files made by previous server invocations.
453 (condition-case ()
454 (delete-file (expand-file-name server-name server-socket-dir))
455 (error nil))
456 ;; If this Emacs already had a server, clear out associated status.
457 (while server-clients
458 (server-delete-client (car server-clients)))
459 ;; Now any previous server is properly stopped.
460 (if leave-dead
461 (progn
462 (server-log (message "Server stopped"))
463 (setq server-process nil))
464 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
465 (server-file (expand-file-name server-name server-dir)))
466 ;; Make sure there is a safe directory in which to place the socket.
467 (server-ensure-safe-dir server-dir)
468 ;; Remove any leftover socket or authentication file.
469 (ignore-errors (delete-file server-file))
470 (when server-process
471 (server-log (message "Restarting server")))
472 (letf (((default-file-modes) ?\700))
473 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
474 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
475 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
476 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
477 (setq server-process
478 (apply #'make-network-process
479 :name server-name
480 :server t
481 :noquery t
482 :sentinel 'server-sentinel
483 :filter 'server-process-filter
484 ;; We must receive file names without being decoded.
485 ;; Those are decoded by server-process-filter according
486 ;; to file-name-coding-system.
487 :coding 'raw-text
488 ;; The rest of the args depends on the kind of socket used.
489 (if server-use-tcp
490 (list :family nil
491 :service t
492 :host (or server-host 'local)
493 :plist '(:authenticated nil))
494 (list :family 'local
495 :service server-file
496 :plist '(:authenticated t)))))
497 (unless server-process (error "Could not start server process"))
498 (when server-use-tcp
499 (let ((auth-key
500 (loop
501 ;; The auth key is a 64-byte string of random chars in the
502 ;; range `!'..`~'.
503 for i below 64
504 collect (+ 33 (random 94)) into auth
505 finally return (concat auth))))
506 (process-put server-process :auth-key auth-key)
507 (with-temp-file server-file
508 (set-buffer-multibyte nil)
509 (setq buffer-file-coding-system 'no-conversion)
510 (insert (format-network-address
511 (process-contact server-process :local))
512 " " (int-to-string (emacs-pid))
513 "\n" auth-key)))))))))
514
515 (defun server-running-p (&optional name)
516 "Test whether server NAME is running."
517 (interactive
518 (list (if current-prefix-arg
519 (read-string "Server name: " nil nil server-name))))
520 (unless name (setq name server-name))
521 (condition-case nil
522 (progn
523 (delete-process
524 (make-network-process
525 :name "server-client-test" :family 'local :server nil :noquery t
526 :service (expand-file-name name server-socket-dir)))
527 t)
528 (file-error nil)))
529
530 ;;;###autoload
531 (define-minor-mode server-mode
532 "Toggle Server mode.
533 With ARG, turn Server mode on if ARG is positive, off otherwise.
534 Server mode runs a process that accepts commands from the
535 `emacsclient' program. See `server-start' and Info node `Emacs server'."
536 :global t
537 :group 'server
538 :version "22.1"
539 ;; Fixme: Should this check for an existing server socket and do
540 ;; nothing if there is one (for multiple Emacs sessions)?
541 (server-start (not server-mode)))
542 \f
543 (defun server-eval-and-print (expr proc)
544 "Eval EXPR and send the result back to client PROC."
545 (let ((v (eval (car (read-from-string expr)))))
546 (when (and v proc)
547 (with-temp-buffer
548 (let ((standard-output (current-buffer)))
549 (pp v)
550 (let ((text (buffer-substring-no-properties
551 (point-min) (point-max))))
552 (server-send-string
553 proc (format "-print %s\n"
554 (server-quote-arg text)))))))))
555
556 (defun server-create-tty-frame (tty type proc)
557 (let ((frame
558 (server-with-environment (process-get proc 'env)
559 '("LANG" "LC_CTYPE" "LC_ALL"
560 ;; For tgetent(3); list according to ncurses(3).
561 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
562 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
563 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
564 "TERMINFO_DIRS" "TERMPATH"
565 ;; rxvt wants these
566 "COLORFGBG" "COLORTERM")
567 (make-frame-on-tty tty type
568 ;; Ignore nowait here; we always need to
569 ;; clean up opened ttys when the client dies.
570 `((client . ,proc)
571 (environment . ,(process-get proc 'env)))))))
572
573 ;; ttys don't use the `display' parameter, but callproc.c does to set
574 ;; the DISPLAY environment on subprocesses.
575 (set-frame-parameter frame 'display
576 (getenv-internal "DISPLAY" (process-get proc 'env)))
577 (select-frame frame)
578 (process-put proc 'frame frame)
579 (process-put proc 'terminal (frame-terminal frame))
580
581 ;; Display *scratch* by default.
582 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
583
584 ;; Reply with our pid.
585 (server-send-string proc (concat "-emacs-pid "
586 (number-to-string (emacs-pid)) "\n"))
587 frame))
588
589 (defun server-create-window-system-frame (display nowait proc)
590 (if (not (fboundp 'make-frame-on-display))
591 (progn
592 ;; This emacs does not support X.
593 (server-log "Window system unsupported" proc)
594 (server-send-string proc "-window-system-unsupported \n")
595 nil)
596 ;; Flag frame as client-created, but use a dummy client.
597 ;; This will prevent the frame from being deleted when
598 ;; emacsclient quits while also preventing
599 ;; `server-save-buffers-kill-terminal' from unexpectedly
600 ;; killing emacs on that frame.
601 (let* ((params `((client . ,(if nowait 'nowait proc))
602 (environment . ,(process-get proc 'env))))
603 (frame (make-frame-on-display
604 (or display
605 (frame-parameter nil 'display)
606 (getenv "DISPLAY")
607 (error "Please specify display"))
608 params)))
609 (server-log (format "%s created" frame) proc)
610 ;; XXX We need to ensure the parameters are
611 ;; really set because Emacs forgets unhandled
612 ;; initialization parameters for X frames at
613 ;; the moment.
614 (modify-frame-parameters frame params)
615 (select-frame frame)
616 (process-put proc 'frame frame)
617 (process-put proc 'terminal (frame-terminal frame))
618
619 ;; Display *scratch* by default.
620 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
621 frame)))
622
623
624 (defun server-goto-toplevel (proc)
625 (condition-case nil
626 ;; If we're running isearch, we must abort it to allow Emacs to
627 ;; display the buffer and switch to it.
628 (dolist (buffer (buffer-list))
629 (with-current-buffer buffer
630 (when (bound-and-true-p isearch-mode)
631 (isearch-cancel))))
632 ;; Signaled by isearch-cancel.
633 (quit (message nil)))
634 (when (> (recursion-depth) 0)
635 ;; We're inside a minibuffer already, so if the emacs-client is trying
636 ;; to open a frame on a new display, we might end up with an unusable
637 ;; frame because input from that display will be blocked (until exiting
638 ;; the minibuffer). Better exit this minibuffer right away.
639 ;; Similarly with recursive-edits such as the splash screen.
640 (run-with-timer 0 nil (lexical-let ((proc proc))
641 (lambda () (server-execute-continuation proc))))
642 (top-level)))
643
644 ;; We use various special properties on process objects:
645 ;; - `env' stores the info about the environment of the emacsclient process.
646 ;; - `continuation' is a no-arg function that we need to execute. It contains
647 ;; commands we wanted to execute in some earlier invocation of the process
648 ;; filter but that we somehow were unable to process at that time
649 ;; (e.g. because we first need to throw to the toplevel).
650
651 (defun server-execute-continuation (proc)
652 (let ((continuation (process-get proc 'continuation)))
653 (process-put proc 'continuation nil)
654 (if continuation (ignore-errors (funcall continuation)))))
655
656 (defun* server-process-filter (proc string)
657 "Process a request from the server to edit some files.
658 PROC is the server process. STRING consists of a sequence of
659 commands prefixed by a dash. Some commands have arguments; these
660 are &-quoted and need to be decoded by `server-unquote-arg'. The
661 filter parses and executes these commands.
662
663 To illustrate the protocol, here is an example command that
664 emacsclient sends to create a new X frame (note that the whole
665 sequence is sent on a single line):
666
667 -env HOME /home/lorentey
668 -env DISPLAY :0.0
669 ... lots of other -env commands
670 -display :0.0
671 -window-system
672
673 The following commands are accepted by the server:
674
675 `-auth AUTH-STRING'
676 Authenticate the client using the secret authentication string
677 AUTH-STRING.
678
679 `-env NAME=VALUE'
680 An environment variable on the client side.
681
682 `-dir DIRNAME'
683 The current working directory of the client process.
684
685 `-current-frame'
686 Forbid the creation of new frames.
687
688 `-nowait'
689 Request that the next frame created should not be
690 associated with this client.
691
692 `-display DISPLAY'
693 Set the display name to open X frames on.
694
695 `-position LINE[:COLUMN]'
696 Go to the given line and column number
697 in the next file opened.
698
699 `-file FILENAME'
700 Load the given file in the current frame.
701
702 `-eval EXPR'
703 Evaluate EXPR as a Lisp expression and return the
704 result in -print commands.
705
706 `-window-system'
707 Open a new X frame.
708
709 `-tty DEVICENAME TYPE'
710 Open a new tty frame at the client.
711
712 `-suspend'
713 Suspend this tty frame. The client sends this string in
714 response to SIGTSTP and SIGTTOU. The server must cease all I/O
715 on this tty until it gets a -resume command.
716
717 `-resume'
718 Resume this tty frame. The client sends this string when it
719 gets the SIGCONT signal and it is the foreground process on its
720 controlling tty.
721
722 `-ignore COMMENT'
723 Do nothing, but put the comment in the server
724 log. Useful for debugging.
725
726
727 The following commands are accepted by the client:
728
729 `-emacs-pid PID'
730 Describes the process id of the Emacs process;
731 used to forward window change signals to it.
732
733 `-window-system-unsupported'
734 Signals that the server does not
735 support creating X frames; the client must try again with a tty
736 frame.
737
738 `-print STRING'
739 Print STRING on stdout. Used to send values
740 returned by -eval.
741
742 `-error DESCRIPTION'
743 Signal an error (but continue processing).
744
745 `-suspend'
746 Suspend this terminal, i.e., stop the client process. Sent
747 when the user presses C-z."
748 (server-log (concat "Received " string) proc)
749 ;; First things first: let's check the authentication
750 (unless (process-get proc :authenticated)
751 (if (and (string-match "-auth \\(.*?\\)\n" string)
752 (equal (match-string 1 string) (process-get proc :auth-key)))
753 (progn
754 (setq string (substring string (match-end 0)))
755 (process-put proc :authenticated t)
756 (server-log "Authentication successful" proc))
757 (server-log "Authentication failed" proc)
758 (server-send-string
759 proc (concat "-error " (server-quote-arg "Authentication failed")))
760 (delete-process proc)
761 ;; We return immediately
762 (return-from server-process-filter)))
763 (let ((prev (process-get proc 'previous-string)))
764 (when prev
765 (setq string (concat prev string))
766 (process-put proc 'previous-string nil)))
767 (condition-case err
768 (progn
769 (server-add-client proc)
770 (if (not (string-match "\n" string))
771 ;; Save for later any partial line that remains.
772 (when (> (length string) 0)
773 (process-put proc 'previous-string string))
774
775 ;; In earlier versions of server.el (where we used an `emacsserver'
776 ;; process), there could be multiple lines. Nowadays this is not
777 ;; supported any more.
778 (assert (eq (match-end 0) (length string)))
779 (let ((request (substring string 0 (match-beginning 0)))
780 (coding-system (and default-enable-multibyte-characters
781 (or file-name-coding-system
782 default-file-name-coding-system)))
783 nowait ; t if emacsclient does not want to wait for us.
784 frame ; The frame that was opened for the client (if any).
785 display ; Open the frame on this display.
786 dontkill ; t if the client should not be killed.
787 (commands ())
788 dir
789 (tty-name nil) ;nil, `window-system', or the tty name.
790 tty-type ;string.
791 (files nil)
792 (lineno 1)
793 (columnno 0))
794 ;; Remove this line from STRING.
795 (setq string (substring string (match-end 0)))
796 (while (string-match " *[^ ]* " request)
797 (let ((arg (substring request (match-beginning 0)
798 (1- (match-end 0)))))
799 (setq request (substring request (match-end 0)))
800 (cond
801 ;; -version CLIENT-VERSION: obsolete at birth.
802 ((and (equal "-version" arg) (string-match "[^ ]+ " request))
803 (setq request (substring request (match-end 0))))
804
805 ;; -nowait: Emacsclient won't wait for a result.
806 ((equal "-nowait" arg) (setq nowait t))
807
808 ;; -current-frame: Don't create frames.
809 ((equal "-current-frame" arg) (setq tty-name nil))
810
811 ;; -display DISPLAY:
812 ;; Open X frames on the given display instead of the default.
813 ((and (equal "-display" arg)
814 (string-match "\\([^ ]*\\) " request))
815 (setq display (match-string 1 request)
816 request (substring request (match-end 0))))
817
818 ;; -window-system: Open a new X frame.
819 ((equal "-window-system" arg)
820 (setq dontkill t)
821 (setq tty-name 'window-system))
822
823 ;; -resume: Resume a suspended tty frame.
824 ((equal "-resume" arg)
825 (lexical-let ((terminal (process-get proc 'terminal)))
826 (setq dontkill t)
827 (push (lambda ()
828 (when (eq (terminal-live-p terminal) t)
829 (resume-tty terminal)))
830 commands)))
831
832 ;; -suspend: Suspend the client's frame. (In case we
833 ;; get out of sync, and a C-z sends a SIGTSTP to
834 ;; emacsclient.)
835 ((equal "-suspend" arg)
836 (lexical-let ((terminal (process-get proc 'terminal)))
837 (setq dontkill t)
838 (push (lambda ()
839 (when (eq (terminal-live-p terminal) t)
840 (suspend-tty terminal)))
841 commands)))
842
843 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
844 ;; (The given comment appears in the server log.)
845 ((and (equal "-ignore" arg) (string-match "[^ ]* " request))
846 (setq dontkill t
847 request (substring request (match-end 0))))
848
849 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
850 ((and (equal "-tty" arg)
851 (string-match "\\([^ ]*\\) \\([^ ]*\\) " request))
852 (setq tty-name (match-string 1 request))
853 (setq tty-type (match-string 2 request))
854 (setq dontkill t)
855 (setq request (substring request (match-end 0))))
856
857 ;; -position LINE[:COLUMN]: Set point to the given
858 ;; position in the next file.
859 ((and (equal "-position" arg)
860 (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)? "
861 request))
862 (setq lineno (string-to-number (match-string 1 request))
863 columnno (if (null (match-end 2)) 0
864 (string-to-number (match-string 2 request)))
865 request (substring request (match-end 0))))
866
867 ;; -file FILENAME: Load the given file.
868 ((and (equal "-file" arg)
869 (string-match "\\([^ ]+\\) " request))
870 (let ((file (server-unquote-arg (match-string 1 request))))
871 (setq request (substring request (match-end 0)))
872 (if coding-system
873 (setq file (decode-coding-string file coding-system)))
874 (setq file (command-line-normalize-file-name file))
875 (push (list file lineno columnno) files)
876 (server-log (format "New file: %s (%d:%d)"
877 file lineno columnno) proc))
878 (setq lineno 1
879 columnno 0))
880
881 ;; -eval EXPR: Evaluate a Lisp expression.
882 ((and (equal "-eval" arg)
883 (string-match "\\([^ ]+\\) " request))
884 (lexical-let ((expr (server-unquote-arg
885 (match-string 1 request))))
886 (setq request (substring request (match-end 0)))
887 (if coding-system
888 (setq expr (decode-coding-string expr coding-system)))
889 (push (lambda () (server-eval-and-print expr proc))
890 commands)
891 (setq lineno 1
892 columnno 0)))
893
894 ;; -env NAME=VALUE: An environment variable.
895 ((and (equal "-env" arg) (string-match "\\([^ ]+\\) " request))
896 (let ((var (server-unquote-arg (match-string 1 request))))
897 ;; XXX Variables should be encoded as in getenv/setenv.
898 (setq request (substring request (match-end 0)))
899 (process-put proc 'env
900 (cons var (process-get proc 'env)))))
901
902 ;; -dir DIRNAME: The cwd of the emacsclient process.
903 ((and (equal "-dir" arg) (string-match "\\([^ ]+\\) " request))
904 (setq dir (server-unquote-arg (match-string 1 request)))
905 (setq request (substring request (match-end 0)))
906 (if coding-system
907 (setq dir (decode-coding-string dir coding-system)))
908 (setq dir (command-line-normalize-file-name dir)))
909
910 ;; Unknown command.
911 (t (error "Unknown command: %s" arg)))))
912
913 (setq frame
914 (case tty-name
915 ((nil) (if display (server-select-display display)))
916 ((window-system)
917 (server-create-window-system-frame display nowait proc))
918 (t (server-create-tty-frame tty-name tty-type proc))))
919
920 (process-put proc 'continuation
921 (lexical-let ((proc proc)
922 (files files)
923 (nowait nowait)
924 (commands commands)
925 (dontkill dontkill)
926 (frame frame)
927 (tty-name tty-name))
928 (lambda ()
929 (server-execute proc files nowait commands
930 dontkill frame tty-name))))
931
932 (when (or frame files)
933 (server-goto-toplevel proc))
934
935 (server-execute-continuation proc))))
936 ;; condition-case
937 (error (server-return-error proc err))))
938
939 (defun server-execute (proc files nowait commands dontkill frame tty-name)
940 (condition-case err
941 (let* ((buffers
942 (when files
943 (run-hooks 'pre-command-hook)
944 (prog1 (server-visit-files files proc nowait)
945 (run-hooks 'post-command-hook)))))
946
947 (mapc 'funcall (nreverse commands))
948
949 ;; Delete the client if necessary.
950 (cond
951 (nowait
952 ;; Client requested nowait; return immediately.
953 (server-log "Close nowait client" proc)
954 (server-delete-client proc))
955 ((and (not dontkill) (null buffers))
956 ;; This client is empty; get rid of it immediately.
957 (server-log "Close empty client" proc)
958 (server-delete-client proc)))
959 (cond
960 ((or isearch-mode (minibufferp))
961 nil)
962 ((and frame (null buffers))
963 (message "%s" (substitute-command-keys
964 "When done with this frame, type \\[delete-frame]")))
965 ((not (null buffers))
966 (server-switch-buffer (car buffers))
967 (run-hooks 'server-switch-hook)
968 (unless nowait
969 (message "%s" (substitute-command-keys
970 "When done with a buffer, type \\[server-edit]")))))
971 (when (and frame (null tty-name))
972 (server-unselect-display frame)))
973 (error (server-return-error proc err))))
974
975 (defun server-return-error (proc err)
976 (ignore-errors
977 (server-send-string
978 proc (concat "-error " (server-quote-arg
979 (error-message-string err))))
980 (server-log (error-message-string err) proc)
981 (delete-process proc)))
982
983 (defun server-goto-line-column (file-line-col)
984 "Move point to the position indicated in FILE-LINE-COL.
985 FILE-LINE-COL should be a three-element list as described in
986 `server-visit-files'."
987 (goto-line (nth 1 file-line-col))
988 (let ((column-number (nth 2 file-line-col)))
989 (if (> column-number 0)
990 (move-to-column (1- column-number)))))
991
992 (defun server-visit-files (files proc &optional nowait)
993 "Find FILES and return a list of buffers created.
994 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
995 PROC is the client that requested this operation.
996 NOWAIT non-nil means this client is not waiting for the results,
997 so don't mark these buffers specially, just visit them normally."
998 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
999 (let ((last-nonmenu-event t) client-record)
1000 ;; Restore the current buffer afterward, but not using save-excursion,
1001 ;; because we don't want to save point in this buffer
1002 ;; if it happens to be one of those specified by the server.
1003 (save-current-buffer
1004 (dolist (file files)
1005 ;; If there is an existing buffer modified or the file is
1006 ;; modified, revert it. If there is an existing buffer with
1007 ;; deleted file, offer to write it.
1008 (let* ((minibuffer-auto-raise (or server-raise-frame
1009 minibuffer-auto-raise))
1010 (filen (car file))
1011 (obuf (get-file-buffer filen)))
1012 (add-to-history 'file-name-history filen)
1013 (if (and obuf (set-buffer obuf))
1014 (progn
1015 (cond ((file-exists-p filen)
1016 (when (not (verify-visited-file-modtime obuf))
1017 (revert-buffer t nil)))
1018 (t
1019 (when (y-or-n-p
1020 (concat "File no longer exists: " filen
1021 ", write buffer to file? "))
1022 (write-file filen))))
1023 (unless server-buffer-clients
1024 (setq server-existing-buffer t))
1025 (server-goto-line-column file))
1026 (set-buffer (find-file-noselect filen))
1027 (server-goto-line-column file)
1028 (run-hooks 'server-visit-hook)))
1029 (unless nowait
1030 ;; When the buffer is killed, inform the clients.
1031 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1032 (push proc server-buffer-clients))
1033 (push (current-buffer) client-record)))
1034 (unless nowait
1035 (process-put proc 'buffers
1036 (nconc (process-get proc 'buffers) client-record)))
1037 client-record))
1038 \f
1039 (defun server-buffer-done (buffer &optional for-killing)
1040 "Mark BUFFER as \"done\" for its client(s).
1041 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1042 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1043 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1044 a temp file).
1045 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1046 (let ((next-buffer nil)
1047 (killed nil))
1048 (dolist (proc server-clients)
1049 (let ((buffers (process-get proc 'buffers)))
1050 (or next-buffer
1051 (setq next-buffer (nth 1 (memq buffer buffers))))
1052 (when buffers ; Ignore bufferless clients.
1053 (setq buffers (delq buffer buffers))
1054 ;; Delete all dead buffers from PROC.
1055 (dolist (b buffers)
1056 (and (bufferp b)
1057 (not (buffer-live-p b))
1058 (setq buffers (delq b buffers))))
1059 (process-put proc 'buffers buffers)
1060 ;; If client now has no pending buffers,
1061 ;; tell it that it is done, and forget it entirely.
1062 (unless buffers
1063 (server-log "Close" proc)
1064 (server-delete-client proc)))))
1065 (when (and (bufferp buffer) (buffer-name buffer))
1066 ;; We may or may not kill this buffer;
1067 ;; if we do, do not call server-buffer-done recursively
1068 ;; from kill-buffer-hook.
1069 (let ((server-kill-buffer-running t))
1070 (with-current-buffer buffer
1071 (setq server-buffer-clients nil)
1072 (run-hooks 'server-done-hook))
1073 ;; Notice whether server-done-hook killed the buffer.
1074 (if (null (buffer-name buffer))
1075 (setq killed t)
1076 ;; Don't bother killing or burying the buffer
1077 ;; when we are called from kill-buffer.
1078 (unless for-killing
1079 (when (and (not killed)
1080 server-kill-new-buffers
1081 (with-current-buffer buffer
1082 (not server-existing-buffer)))
1083 (setq killed t)
1084 (bury-buffer buffer)
1085 (kill-buffer buffer))
1086 (unless killed
1087 (if (server-temp-file-p buffer)
1088 (progn
1089 (kill-buffer buffer)
1090 (setq killed t))
1091 (bury-buffer buffer)))))))
1092 (list next-buffer killed)))
1093
1094 (defun server-temp-file-p (&optional buffer)
1095 "Return non-nil if BUFFER contains a file considered temporary.
1096 These are files whose names suggest they are repeatedly
1097 reused to pass information to another program.
1098
1099 The variable `server-temp-file-regexp' controls which filenames
1100 are considered temporary."
1101 (and (buffer-file-name buffer)
1102 (string-match server-temp-file-regexp (buffer-file-name buffer))))
1103
1104 (defun server-done ()
1105 "Offer to save current buffer, mark it as \"done\" for clients.
1106 This kills or buries the buffer, then returns a list
1107 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1108 as a suggestion for what to select next, or nil.
1109 KILLED is t if we killed BUFFER, which happens if it was created
1110 specifically for the clients and did not exist before their request for it."
1111 (when server-buffer-clients
1112 (if (server-temp-file-p)
1113 ;; For a temp file, save, and do make a non-numeric backup
1114 ;; (unless make-backup-files is nil).
1115 (let ((version-control nil)
1116 (buffer-backed-up nil))
1117 (save-buffer))
1118 (when (and (buffer-modified-p)
1119 buffer-file-name
1120 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1121 (save-buffer)))
1122 (server-buffer-done (current-buffer))))
1123
1124 ;; Ask before killing a server buffer.
1125 ;; It was suggested to release its client instead,
1126 ;; but I think that is dangerous--the client would proceed
1127 ;; using whatever is on disk in that file. -- rms.
1128 (defun server-kill-buffer-query-function ()
1129 "Ask before killing a server buffer."
1130 (or (not server-buffer-clients)
1131 (let ((res t))
1132 (dolist (proc server-buffer-clients res)
1133 (when (and (memq proc server-clients)
1134 (eq (process-status proc) 'open))
1135 (setq res nil))))
1136 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1137 (buffer-name (current-buffer))))))
1138
1139 (defun server-kill-emacs-query-function ()
1140 "Ask before exiting Emacs it has live clients."
1141 (or (not server-clients)
1142 (let (live-client)
1143 (dolist (proc server-clients live-client)
1144 (when (memq t (mapcar 'buffer-live-p (process-get
1145 proc 'buffers)))
1146 (setq live-client t))))
1147 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1148
1149 (defvar server-kill-buffer-running nil
1150 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1151
1152 (defun server-kill-buffer ()
1153 "Remove the current buffer from its clients' buffer list.
1154 Designed to be added to `kill-buffer-hook'."
1155 ;; Prevent infinite recursion if user has made server-done-hook
1156 ;; call kill-buffer.
1157 (or server-kill-buffer-running
1158 (and server-buffer-clients
1159 (let ((server-kill-buffer-running t))
1160 (when server-process
1161 (server-buffer-done (current-buffer) t))))))
1162 \f
1163 (defun server-edit (&optional arg)
1164 "Switch to next server editing buffer; say \"Done\" for current buffer.
1165 If a server buffer is current, it is marked \"done\" and optionally saved.
1166 The buffer is also killed if it did not exist before the clients asked for it.
1167 When all of a client's buffers are marked as \"done\", the client is notified.
1168
1169 Temporary files such as MH <draft> files are always saved and backed up,
1170 no questions asked. (The variable `make-backup-files', if nil, still
1171 inhibits a backup; you can set it locally in a particular buffer to
1172 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1173 which filenames are considered temporary.
1174
1175 If invoked with a prefix argument, or if there is no server process running,
1176 starts server process and that is all. Invoked by \\[server-edit]."
1177 (interactive "P")
1178 (cond
1179 ((or arg
1180 (not server-process)
1181 (memq (process-status server-process) '(signal exit)))
1182 (server-mode 1))
1183 (server-clients (apply 'server-switch-buffer (server-done)))
1184 (t (message "No server editing buffers exist"))))
1185
1186 (defun server-switch-buffer (&optional next-buffer killed-one)
1187 "Switch to another buffer, preferably one that has a client.
1188 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1189
1190 KILLED-ONE is t in a recursive call if we have already killed one
1191 temp-file server buffer. This means we should avoid the final
1192 \"switch to some other buffer\" since we've already effectively
1193 done that."
1194 (if (null next-buffer)
1195 (progn
1196 (let ((rest server-clients))
1197 (while (and rest (not next-buffer))
1198 (let ((proc (car rest)))
1199 ;; Only look at frameless clients.
1200 (when (not (process-get proc 'frame))
1201 (setq next-buffer (car (process-get proc 'buffers))))
1202 (setq rest (cdr rest)))))
1203 (and next-buffer (server-switch-buffer next-buffer killed-one))
1204 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1205 ;; (switch-to-buffer (other-buffer))
1206 (message "No server buffers remain to edit")))
1207 (if (not (buffer-live-p next-buffer))
1208 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1209 ;; and try the next surviving server buffer.
1210 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1211 ;; OK, we know next-buffer is live, let's display and select it.
1212 (if (functionp server-window)
1213 (funcall server-window next-buffer)
1214 (let ((win (get-buffer-window next-buffer 0)))
1215 (if (and win (not server-window))
1216 ;; The buffer is already displayed: just reuse the window.
1217 (progn
1218 (select-window win)
1219 (set-buffer next-buffer))
1220 ;; Otherwise, let's find an appropriate window.
1221 (cond ((window-live-p server-window)
1222 (select-window server-window))
1223 ((framep server-window)
1224 (unless (frame-live-p server-window)
1225 (setq server-window (make-frame)))
1226 (select-window (frame-selected-window server-window))))
1227 (when (window-minibuffer-p (selected-window))
1228 (select-window (next-window nil 'nomini 0)))
1229 ;; Move to a non-dedicated window, if we have one.
1230 (when (window-dedicated-p (selected-window))
1231 (select-window
1232 (get-window-with-predicate
1233 (lambda (w)
1234 (and (not (window-dedicated-p w))
1235 (equal (frame-terminal (window-frame w))
1236 (frame-terminal (selected-frame)))))
1237 'nomini 'visible (selected-window))))
1238 (condition-case nil
1239 (switch-to-buffer next-buffer)
1240 ;; After all the above, we might still have ended up with
1241 ;; a minibuffer/dedicated-window (if there's no other).
1242 (error (pop-to-buffer next-buffer)))))))
1243 (when server-raise-frame
1244 (select-frame-set-input-focus (window-frame (selected-window))))))
1245
1246 ;;;###autoload
1247 (defun server-save-buffers-kill-terminal (proc &optional arg)
1248 "Offer to save each buffer, then kill PROC.
1249
1250 With prefix arg, silently save all file-visiting buffers, then kill.
1251
1252 If emacsclient was started with a list of filenames to edit, then
1253 only these files will be asked to be saved."
1254 (let ((buffers (process-get proc 'buffers)))
1255 ;; If client is bufferless, emulate a normal Emacs session
1256 ;; exit and offer to save all buffers. Otherwise, offer to
1257 ;; save only the buffers belonging to the client.
1258 (save-some-buffers arg
1259 (if buffers
1260 (lambda () (memq (current-buffer) buffers))
1261 t))
1262 (server-delete-client proc)))
1263
1264 (define-key ctl-x-map "#" 'server-edit)
1265
1266 (defun server-unload-hook ()
1267 "Unload the server library."
1268 (server-mode -1)
1269 (remove-hook 'suspend-tty-functions 'server-handle-suspend-tty)
1270 (remove-hook 'delete-frame-functions 'server-handle-delete-frame)
1271 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
1272 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
1273 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
1274
1275 (add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
1276 (add-hook 'server-unload-hook 'server-unload-hook)
1277 \f
1278 (provide 'server)
1279
1280 ;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1281 ;;; server.el ends here