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