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