* doc/lispref/variables.texi (Scope): Mention the availability of lexbind.
[emacs.git] / lisp / server.el
blob019a16a43d7f0fb95ac8068c7f25bb237c006c24
1 ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
3 ;; Copyright (C) 1986-1987, 1992, 1994-2011 Free Software Foundation, Inc.
5 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
6 ;; Maintainer: FSF
7 ;; Keywords: processes
9 ;; Changes by peck@sun.com and by rms.
10 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; This Lisp code is run in Emacs when it is to operate as
30 ;; a server for other processes.
32 ;; Load this library and do M-x server-edit to enable Emacs as a server.
33 ;; Emacs opens up a socket for communication with clients. If there are no
34 ;; client buffers to edit, server-edit acts like (switch-to-buffer
35 ;; (other-buffer))
37 ;; When some other program runs "the editor" to edit a file,
38 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
39 ;; This program transmits the file names to Emacs through
40 ;; the server subprocess, and Emacs visits them and lets you edit them.
42 ;; Note that any number of clients may dispatch files to Emacs to be edited.
44 ;; When you finish editing a Server buffer, again call server-edit
45 ;; to mark that buffer as done for the client and switch to the next
46 ;; Server buffer. When all the buffers for a client have been edited
47 ;; and exited with server-edit, the client "editor" will return
48 ;; to the program that invoked it.
50 ;; Your editing commands and Emacs's display output go to and from
51 ;; the terminal in the usual way. Thus, server operation is possible
52 ;; only when Emacs can talk to the terminal at the time you invoke
53 ;; the client. This is possible in four cases:
55 ;; 1. On a window system, where Emacs runs in one window and the
56 ;; program that wants to use "the editor" runs in another.
58 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
59 ;; program that wants to use "the editor" runs on another.
61 ;; 3. When the program that wants to use "the editor" is running
62 ;; as a subprocess of Emacs.
64 ;; 4. On a system with job control, when Emacs is suspended, the program
65 ;; that wants to use "the editor" will stop and display
66 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
67 ;; brought into the foreground for editing. When done editing, Emacs is
68 ;; suspended again, and the client program is brought into the foreground.
70 ;; The buffer local variable "server-buffer-clients" lists
71 ;; the clients who are waiting for this buffer to be edited.
72 ;; The global variable "server-clients" lists all the waiting clients,
73 ;; and which files are yet to be edited for each.
75 ;; Todo:
77 ;; - handle command-line-args-left.
78 ;; - move most of the args processing and decision making from emacsclient.c
79 ;; to here.
80 ;; - fix up handling of the client's environment (place it in the terminal?).
82 ;;; Code:
84 (eval-when-compile (require 'cl))
86 (defgroup server nil
87 "Emacs running as a server process."
88 :group 'external)
90 (defcustom server-use-tcp nil
91 "If non-nil, use TCP sockets instead of local sockets."
92 :set #'(lambda (sym val)
93 (unless (featurep 'make-network-process '(:family local))
94 (setq val t)
95 (unless load-in-progress
96 (message "Local sockets unsupported, using TCP sockets")))
97 (when val (random t))
98 (set-default sym val))
99 :group 'server
100 :type 'boolean
101 :version "22.1")
103 (defcustom server-host nil
104 "The name or IP address to use as host address of the server process.
105 If set, the server accepts remote connections; otherwise it is local."
106 :group 'server
107 :type '(choice
108 (string :tag "Name or IP address")
109 (const :tag "Local" nil))
110 :version "22.1")
111 ;;;###autoload
112 (put 'server-host 'risky-local-variable t)
114 (defcustom server-port nil
115 "The port number that the server process should listen on."
116 :group 'server
117 :type '(choice
118 (string :tag "Port number")
119 (const :tag "Random" nil))
120 :version "24.1")
121 ;;;###autoload
122 (put 'server-port 'risky-local-variable t)
124 (defcustom server-auth-dir (locate-user-emacs-file "server/")
125 "Directory for server authentication files.
127 NOTE: On FAT32 filesystems, directories are not secure;
128 files can be read and modified by any user or process.
129 It is strongly suggested to set `server-auth-dir' to a
130 directory residing in a NTFS partition instead."
131 :group 'server
132 :type 'directory
133 :version "22.1")
134 ;;;###autoload
135 (put 'server-auth-dir 'risky-local-variable t)
137 (defcustom server-raise-frame t
138 "If non-nil, raise frame when switching to a buffer."
139 :group 'server
140 :type 'boolean
141 :version "22.1")
143 (defcustom server-visit-hook nil
144 "Hook run when visiting a file for the Emacs server."
145 :group 'server
146 :type 'hook)
148 (defcustom server-switch-hook nil
149 "Hook run when switching to a buffer for the Emacs server."
150 :group 'server
151 :type 'hook)
153 (defcustom server-done-hook nil
154 "Hook run when done editing a buffer for the Emacs server."
155 :group 'server
156 :type 'hook)
158 (defvar server-process nil
159 "The current server process.")
161 (defvar server-clients nil
162 "List of current server clients.
163 Each element is a process.")
165 (defvar server-buffer-clients nil
166 "List of client processes requesting editing of current buffer.")
167 (make-variable-buffer-local 'server-buffer-clients)
168 ;; Changing major modes should not erase this local.
169 (put 'server-buffer-clients 'permanent-local t)
171 (defcustom server-window nil
172 "Specification of the window to use for selecting Emacs server buffers.
173 If nil, use the selected window.
174 If it is a function, it should take one argument (a buffer) and
175 display and select it. A common value is `pop-to-buffer'.
176 If it is a window, use that.
177 If it is a frame, use the frame's selected window.
179 It is not meaningful to set this to a specific frame or window with Custom.
180 Only programs can do so."
181 :group 'server
182 :version "22.1"
183 :type '(choice (const :tag "Use selected window"
184 :match (lambda (widget value)
185 (not (functionp value)))
186 nil)
187 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
188 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
189 (function :tag "Other function")))
191 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
192 "Regexp matching names of temporary files.
193 These are deleted and reused after each edit by the programs that
194 invoke the Emacs server."
195 :group 'server
196 :type 'regexp)
198 (defcustom server-kill-new-buffers t
199 "Whether to kill buffers when done with them.
200 If non-nil, kill a buffer unless it already existed before editing
201 it with the Emacs server. If nil, kill only buffers as specified by
202 `server-temp-file-regexp'.
203 Please note that only buffers that still have a client are killed,
204 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
205 in this way."
206 :group 'server
207 :type 'boolean
208 :version "21.1")
210 (or (assq 'server-buffer-clients minor-mode-alist)
211 (push '(server-buffer-clients " Server") minor-mode-alist))
213 (defvar server-existing-buffer nil
214 "Non-nil means the buffer existed before the server was asked to visit it.
215 This means that the server should not kill the buffer when you say you
216 are done with it in the server.")
217 (make-variable-buffer-local 'server-existing-buffer)
219 (defcustom server-name "server"
220 "The name of the Emacs server, if this Emacs process creates one.
221 The command `server-start' makes use of this. It should not be
222 changed while a server is running."
223 :group 'server
224 :type 'string
225 :version "23.1")
227 ;; We do not use `temporary-file-directory' here, because emacsclient
228 ;; does not read the init file.
229 (defvar server-socket-dir
230 (and (featurep 'make-network-process '(:family local))
231 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
232 "The directory in which to place the server socket.
233 If local sockets are not supported, this is nil.")
235 (defun server-clients-with (property value)
236 "Return a list of clients with PROPERTY set to VALUE."
237 (let (result)
238 (dolist (proc server-clients result)
239 (when (equal value (process-get proc property))
240 (push proc result)))))
242 (defun server-add-client (proc)
243 "Create a client for process PROC, if it doesn't already have one.
244 New clients have no properties."
245 (add-to-list 'server-clients proc))
247 (defmacro server-with-environment (env vars &rest body)
248 "Evaluate BODY with environment variables VARS set to those in ENV.
249 The environment variables are then restored to their previous values.
251 VARS should be a list of strings.
252 ENV should be in the same format as `process-environment'."
253 (declare (indent 2))
254 (let ((var (make-symbol "var"))
255 (value (make-symbol "value")))
256 `(let ((process-environment process-environment))
257 (dolist (,var ,vars)
258 (let ((,value (getenv-internal ,var ,env)))
259 (push (if (stringp ,value)
260 (concat ,var "=" ,value)
261 ,var)
262 process-environment)))
263 (progn ,@body))))
265 (defun server-delete-client (proc &optional noframe)
266 "Delete PROC, including its buffers, terminals and frames.
267 If NOFRAME is non-nil, let the frames live.
268 Updates `server-clients'."
269 (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
270 ;; Force a new lookup of client (prevents infinite recursion).
271 (when (memq proc server-clients)
272 (let ((buffers (process-get proc 'buffers)))
274 ;; Kill the client's buffers.
275 (dolist (buf buffers)
276 (when (buffer-live-p buf)
277 (with-current-buffer buf
278 ;; Kill the buffer if necessary.
279 (when (and (equal server-buffer-clients
280 (list proc))
281 (or (and server-kill-new-buffers
282 (not server-existing-buffer))
283 (server-temp-file-p))
284 (not (buffer-modified-p)))
285 (let (flag)
286 (unwind-protect
287 (progn (setq server-buffer-clients nil)
288 (kill-buffer (current-buffer))
289 (setq flag t))
290 (unless flag
291 ;; Restore clients if user pressed C-g in `kill-buffer'.
292 (setq server-buffer-clients (list proc)))))))))
294 ;; Delete the client's frames.
295 (unless noframe
296 (dolist (frame (frame-list))
297 (when (and (frame-live-p frame)
298 (equal proc (frame-parameter frame 'client)))
299 ;; Prevent `server-handle-delete-frame' from calling us
300 ;; recursively.
301 (set-frame-parameter frame 'client nil)
302 (delete-frame frame))))
304 (setq server-clients (delq proc server-clients))
306 ;; Delete the client's tty.
307 (let ((terminal (process-get proc 'terminal)))
308 ;; Only delete the terminal if it is non-nil.
309 (when (and terminal (eq (terminal-live-p terminal) t))
310 (delete-terminal terminal)))
312 ;; Delete the client's process.
313 (if (eq (process-status proc) 'open)
314 (delete-process proc))
316 (server-log "Deleted" proc))))
318 (defvar server-log-time-function 'current-time-string
319 "Function to generate timestamps for `server-buffer'.")
321 (defconst server-buffer " *server*"
322 "Buffer used internally by Emacs's server.
323 One use is to log the I/O for debugging purposes (see `server-log'),
324 the other is to provide a current buffer in which the process filter can
325 safely let-bind buffer-local variables like `default-directory'.")
327 (defvar server-log nil
328 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
330 (defun server-log (string &optional client)
331 "If `server-log' is non-nil, log STRING to `server-buffer'.
332 If CLIENT is non-nil, add a description of it to the logged message."
333 (when server-log
334 (with-current-buffer (get-buffer-create server-buffer)
335 (goto-char (point-max))
336 (insert (funcall server-log-time-function)
337 (cond
338 ((null client) " ")
339 ((listp client) (format " %s: " (car client)))
340 (t (format " %s: " client)))
341 string)
342 (or (bolp) (newline)))))
344 (defun server-sentinel (proc msg)
345 "The process sentinel for Emacs server connections."
346 ;; If this is a new client process, set the query-on-exit flag to nil
347 ;; for this process (it isn't inherited from the server process).
348 (when (and (eq (process-status proc) 'open)
349 (process-query-on-exit-flag proc))
350 (set-process-query-on-exit-flag proc nil))
351 ;; Delete the associated connection file, if applicable.
352 ;; Although there's no 100% guarantee that the file is owned by the
353 ;; running Emacs instance, server-start uses server-running-p to check
354 ;; for possible servers before doing anything, so it *should* be ours.
355 (and (process-contact proc :server)
356 (eq (process-status proc) 'closed)
357 (ignore-errors
358 (delete-file (process-get proc :server-file))))
359 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
360 (server-delete-client proc))
362 (defun server-select-display (display)
363 ;; If the current frame is on `display' we're all set.
364 ;; Similarly if we are unable to open frames on other displays, there's
365 ;; nothing more we can do.
366 (unless (or (not (fboundp 'make-frame-on-display))
367 (equal (frame-parameter (selected-frame) 'display) display))
368 ;; Otherwise, look for an existing frame there and select it.
369 (dolist (frame (frame-list))
370 (when (equal (frame-parameter frame 'display) display)
371 (select-frame frame)))
372 ;; If there's no frame on that display yet, create and select one.
373 (unless (equal (frame-parameter (selected-frame) 'display) display)
374 (let* ((buffer (generate-new-buffer " *server-dummy*"))
375 (frame (make-frame-on-display
376 display
377 ;; Make it display (and remember) some dummy buffer, so
378 ;; we can detect later if the frame is in use or not.
379 `((server-dummy-buffer . ,buffer)
380 ;; This frame may be deleted later (see
381 ;; server-unselect-display) so we want it to be as
382 ;; unobtrusive as possible.
383 (visibility . nil)))))
384 (select-frame frame)
385 (set-window-buffer (selected-window) buffer)
386 frame))))
388 (defun server-unselect-display (frame)
389 (when (frame-live-p frame)
390 ;; If the temporary frame is in use (displays something real), make it
391 ;; visible. If not (which can happen if the user's customizations call
392 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
393 ;; the last real frame is deleted.
394 (if (and (eq (frame-first-window frame)
395 (next-window (frame-first-window frame) 'nomini))
396 (eq (window-buffer (frame-first-window frame))
397 (frame-parameter frame 'server-dummy-buffer)))
398 ;; The temp frame still only shows one buffer, and that is the
399 ;; internal temp buffer.
400 (delete-frame frame)
401 (set-frame-parameter frame 'visibility t))
402 (kill-buffer (frame-parameter frame 'server-dummy-buffer))
403 (set-frame-parameter frame 'server-dummy-buffer nil)))
405 (defun server-handle-delete-frame (frame)
406 "Delete the client connection when the emacsclient frame is deleted.
407 \(To be used from `delete-frame-functions'.)"
408 (let ((proc (frame-parameter frame 'client)))
409 (when (and (frame-live-p frame)
410 proc
411 ;; See if this is the last frame for this client.
412 (>= 1 (let ((frame-num 0))
413 (dolist (f (frame-list))
414 (when (eq proc (frame-parameter f 'client))
415 (setq frame-num (1+ frame-num))))
416 frame-num)))
417 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
418 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
420 (defun server-handle-suspend-tty (terminal)
421 "Notify the client process that its tty device is suspended."
422 (dolist (proc (server-clients-with 'terminal terminal))
423 (server-log (format "server-handle-suspend-tty, terminal %s" terminal)
424 proc)
425 (condition-case nil
426 (server-send-string proc "-suspend \n")
427 (file-error ;The pipe/socket was closed.
428 (ignore-errors (server-delete-client proc))))))
430 (defun server-unquote-arg (arg)
431 "Remove &-quotation from ARG.
432 See `server-quote-arg' and `server-process-filter'."
433 (replace-regexp-in-string
434 "&." (lambda (s)
435 (case (aref s 1)
436 (?& "&")
437 (?- "-")
438 (?n "\n")
439 (t " ")))
440 arg t t))
442 (defun server-quote-arg (arg)
443 "In ARG, insert a & before each &, each space, each newline, and -.
444 Change spaces to underscores, too, so that the return value never
445 contains a space.
447 See `server-unquote-arg' and `server-process-filter'."
448 (replace-regexp-in-string
449 "[-&\n ]" (lambda (s)
450 (case (aref s 0)
451 (?& "&&")
452 (?- "&-")
453 (?\n "&n")
454 (?\s "&_")))
455 arg t t))
457 (defun server-send-string (proc string)
458 "A wrapper around `process-send-string' for logging."
459 (server-log (concat "Sent " string) proc)
460 (process-send-string proc string))
462 (defun server-ensure-safe-dir (dir)
463 "Make sure DIR is a directory with no race-condition issues.
464 Creates the directory if necessary and makes sure:
465 - there's no symlink involved
466 - it's owned by us
467 - it's not readable/writable by anybody else."
468 (setq dir (directory-file-name dir))
469 (let ((attrs (file-attributes dir 'integer)))
470 (unless attrs
471 (letf (((default-file-modes) ?\700)) (make-directory dir t))
472 (setq attrs (file-attributes dir 'integer)))
474 ;; Check that it's safe for use.
475 (let* ((uid (nth 2 attrs))
476 (w32 (eq system-type 'windows-nt))
477 (safe (catch :safe
478 (unless (eq t (car attrs)) ; is a dir?
479 (throw :safe nil))
480 (when (and w32 (zerop uid)) ; on FAT32?
481 (display-warning
482 'server
483 (format "Using `%s' to store Emacs-server authentication files.
484 Directories on FAT32 filesystems are NOT secure against tampering.
485 See variable `server-auth-dir' for details."
486 (file-name-as-directory dir))
487 :warning)
488 (throw :safe t))
489 (unless (eql uid (user-uid)) ; is the dir ours?
490 (throw :safe nil))
491 (when w32 ; on NTFS?
492 (throw :safe t))
493 (unless (zerop (logand ?\077 (file-modes dir)))
494 (throw :safe nil))
495 t)))
496 (unless safe
497 (error "The directory `%s' is unsafe" dir)))))
499 ;;;###autoload
500 (defun server-start (&optional leave-dead inhibit-prompt)
501 "Allow this Emacs process to be a server for client processes.
502 This starts a server communications subprocess through which
503 client \"editors\" can send your editing commands to this Emacs
504 job. To use the server, set up the program `emacsclient' in the
505 Emacs distribution as your standard \"editor\".
507 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
508 kill any existing server communications subprocess.
510 If a server is already running, restart it. If clients are
511 running, ask the user for confirmation first, unless optional
512 argument INHIBIT-PROMPT is non-nil.
514 To force-start a server, do \\[server-force-delete] and then
515 \\[server-start]."
516 (interactive "P")
517 (when (or (not server-clients)
518 ;; Ask the user before deleting existing clients---except
519 ;; when we can't get user input, which may happen when
520 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
521 (cond
522 ((and (daemonp)
523 (null (cdr (frame-list)))
524 (eq (selected-frame) terminal-frame))
525 leave-dead)
526 (inhibit-prompt t)
527 (t (yes-or-no-p
528 "The current server still has clients; delete them? "))))
529 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
530 (server-file (expand-file-name server-name server-dir)))
531 (when server-process
532 ;; kill it dead!
533 (ignore-errors (delete-process server-process)))
534 ;; Delete the socket files made by previous server invocations.
535 (if (not (eq t (server-running-p server-name)))
536 ;; Remove any leftover socket or authentication file
537 (ignore-errors
538 (let (delete-by-moving-to-trash)
539 (delete-file server-file)))
540 (setq server-mode nil) ;; already set by the minor mode code
541 (display-warning
542 'server
543 (concat "Unable to start the Emacs server.\n"
544 (format "There is an existing Emacs server, named %S.\n"
545 server-name)
546 "To start the server in this Emacs process, stop the existing
547 server or call `M-x server-force-delete' to forcibly disconnect it.")
548 :warning)
549 (setq leave-dead t))
550 ;; If this Emacs already had a server, clear out associated status.
551 (while server-clients
552 (server-delete-client (car server-clients)))
553 ;; Now any previous server is properly stopped.
554 (if leave-dead
555 (progn
556 (unless (eq t leave-dead) (server-log (message "Server stopped")))
557 (setq server-process nil))
558 ;; Make sure there is a safe directory in which to place the socket.
559 (server-ensure-safe-dir server-dir)
560 (when server-process
561 (server-log (message "Restarting server")))
562 (letf (((default-file-modes) ?\700))
563 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
564 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
565 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
566 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
567 (add-hook 'kill-emacs-hook 'server-force-stop) ;Cleanup upon exit.
568 (setq server-process
569 (apply #'make-network-process
570 :name server-name
571 :server t
572 :noquery t
573 :sentinel 'server-sentinel
574 :filter 'server-process-filter
575 ;; We must receive file names without being decoded.
576 ;; Those are decoded by server-process-filter according
577 ;; to file-name-coding-system. Also don't get
578 ;; confused by CRs since we don't quote them.
579 :coding 'raw-text-unix
580 ;; The other args depend on the kind of socket used.
581 (if server-use-tcp
582 (list :family 'ipv4 ;; We're not ready for IPv6 yet
583 :service (or server-port t)
584 :host (or server-host 'local)
585 :plist '(:authenticated nil))
586 (list :family 'local
587 :service server-file
588 :plist '(:authenticated t)))))
589 (unless server-process (error "Could not start server process"))
590 (process-put server-process :server-file server-file)
591 (when server-use-tcp
592 (let ((auth-key
593 (loop
594 ;; The auth key is a 64-byte string of random chars in the
595 ;; range `!'..`~'.
596 repeat 64
597 collect (+ 33 (random 94)) into auth
598 finally return (concat auth))))
599 (process-put server-process :auth-key auth-key)
600 (with-temp-file server-file
601 (set-buffer-multibyte nil)
602 (setq buffer-file-coding-system 'no-conversion)
603 (insert (format-network-address
604 (process-contact server-process :local))
605 " " (number-to-string (emacs-pid)) ; Kept for compatibility
606 "\n" auth-key)))))))))
608 (defun server-force-stop ()
609 "Kill all connections to the current server.
610 This function is meant to be called from `kill-emacs-hook'."
611 (server-start t t))
613 ;;;###autoload
614 (defun server-force-delete (&optional name)
615 "Unconditionally delete connection file for server NAME.
616 If server is running, it is first stopped.
617 NAME defaults to `server-name'. With argument, ask for NAME."
618 (interactive
619 (list (if current-prefix-arg
620 (read-string "Server name: " nil nil server-name))))
621 (when server-mode (with-temp-message nil (server-mode -1)))
622 (let ((file (expand-file-name (or name server-name)
623 (if server-use-tcp
624 server-auth-dir
625 server-socket-dir))))
626 (condition-case nil
627 (let (delete-by-moving-to-trash)
628 (delete-file file)
629 (message "Connection file %S deleted" file))
630 (file-error
631 (message "No connection file %S" file)))))
633 (defun server-running-p (&optional name)
634 "Test whether server NAME is running.
636 Return values:
637 nil the server is definitely not running.
638 t the server seems to be running.
639 something else we cannot determine whether it's running without using
640 commands which may have to wait for a long time."
641 (unless name (setq name server-name))
642 (condition-case nil
643 (if server-use-tcp
644 (with-temp-buffer
645 (insert-file-contents-literally (expand-file-name name server-auth-dir))
646 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
647 (assq 'comm
648 (process-attributes
649 (string-to-number (match-string 1))))
651 :other))
652 (delete-process
653 (make-network-process
654 :name "server-client-test" :family 'local :server nil :noquery t
655 :service (expand-file-name name server-socket-dir)))
657 (file-error nil)))
659 ;;;###autoload
660 (define-minor-mode server-mode
661 "Toggle Server mode.
662 With ARG, turn Server mode on if ARG is positive, off otherwise.
663 Server mode runs a process that accepts commands from the
664 `emacsclient' program. See `server-start' and Info node `Emacs server'."
665 :global t
666 :group 'server
667 :version "22.1"
668 ;; Fixme: Should this check for an existing server socket and do
669 ;; nothing if there is one (for multiple Emacs sessions)?
670 (server-start (not server-mode)))
672 (defun server-eval-and-print (expr proc)
673 "Eval EXPR and send the result back to client PROC."
674 (let ((v (eval (car (read-from-string expr)))))
675 (when (and v proc)
676 (with-temp-buffer
677 (let ((standard-output (current-buffer)))
678 (pp v)
679 (let ((text (buffer-substring-no-properties
680 (point-min) (point-max))))
681 (server-send-string
682 proc (format "-print %s\n"
683 (server-quote-arg text)))))))))
685 (defun server-create-tty-frame (tty type proc)
686 (unless tty
687 (error "Invalid terminal device"))
688 (unless type
689 (error "Invalid terminal type"))
690 (add-to-list 'frame-inherited-parameters 'client)
691 (let ((frame
692 (server-with-environment (process-get proc 'env)
693 '("LANG" "LC_CTYPE" "LC_ALL"
694 ;; For tgetent(3); list according to ncurses(3).
695 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
696 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
697 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
698 "TERMINFO_DIRS" "TERMPATH"
699 ;; rxvt wants these
700 "COLORFGBG" "COLORTERM")
701 (make-frame `((window-system . nil)
702 (tty . ,tty)
703 (tty-type . ,type)
704 ;; Ignore nowait here; we always need to
705 ;; clean up opened ttys when the client dies.
706 (client . ,proc)
707 ;; This is a leftover from an earlier
708 ;; attempt at making it possible for process
709 ;; run in the server process to use the
710 ;; environment of the client process.
711 ;; It has no effect now and to make it work
712 ;; we'd need to decide how to make
713 ;; process-environment interact with client
714 ;; envvars, and then to change the
715 ;; C functions `child_setup' and
716 ;; `getenv_internal' accordingly.
717 (environment . ,(process-get proc 'env)))))))
719 ;; ttys don't use the `display' parameter, but callproc.c does to set
720 ;; the DISPLAY environment on subprocesses.
721 (set-frame-parameter frame 'display
722 (getenv-internal "DISPLAY" (process-get proc 'env)))
723 (select-frame frame)
724 (process-put proc 'frame frame)
725 (process-put proc 'terminal (frame-terminal frame))
727 ;; Display *scratch* by default.
728 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
730 frame))
732 (defun server-create-window-system-frame (display nowait proc parent-id)
733 (add-to-list 'frame-inherited-parameters 'client)
734 (if (not (fboundp 'make-frame-on-display))
735 (progn
736 ;; This emacs does not support X.
737 (server-log "Window system unsupported" proc)
738 (server-send-string proc "-window-system-unsupported \n")
739 nil)
740 ;; Flag frame as client-created, but use a dummy client.
741 ;; This will prevent the frame from being deleted when
742 ;; emacsclient quits while also preventing
743 ;; `server-save-buffers-kill-terminal' from unexpectedly
744 ;; killing emacs on that frame.
745 (let* ((params `((client . ,(if nowait 'nowait proc))
746 ;; This is a leftover, see above.
747 (environment . ,(process-get proc 'env))))
748 (display (or display
749 (frame-parameter nil 'display)
750 (getenv "DISPLAY")
751 (error "Please specify display")))
752 frame)
753 (if parent-id
754 (push (cons 'parent-id (string-to-number parent-id)) params))
755 (setq frame (make-frame-on-display display params))
756 (server-log (format "%s created" frame) proc)
757 (select-frame frame)
758 (process-put proc 'frame frame)
759 (process-put proc 'terminal (frame-terminal frame))
761 ;; Display *scratch* by default.
762 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
763 frame)))
765 (defun server-goto-toplevel (proc)
766 (condition-case nil
767 ;; If we're running isearch, we must abort it to allow Emacs to
768 ;; display the buffer and switch to it.
769 (dolist (buffer (buffer-list))
770 (with-current-buffer buffer
771 (when (bound-and-true-p isearch-mode)
772 (isearch-cancel))))
773 ;; Signaled by isearch-cancel.
774 (quit (message nil)))
775 (when (> (recursion-depth) 0)
776 ;; We're inside a minibuffer already, so if the emacs-client is trying
777 ;; to open a frame on a new display, we might end up with an unusable
778 ;; frame because input from that display will be blocked (until exiting
779 ;; the minibuffer). Better exit this minibuffer right away.
780 ;; Similarly with recursive-edits such as the splash screen.
781 (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
782 (top-level)))
784 ;; We use various special properties on process objects:
785 ;; - `env' stores the info about the environment of the emacsclient process.
786 ;; - `continuation' is a no-arg function that we need to execute. It contains
787 ;; commands we wanted to execute in some earlier invocation of the process
788 ;; filter but that we somehow were unable to process at that time
789 ;; (e.g. because we first need to throw to the toplevel).
791 (defun server-execute-continuation (proc)
792 (let ((continuation (process-get proc 'continuation)))
793 (process-put proc 'continuation nil)
794 (if continuation (ignore-errors (funcall continuation)))))
796 (defun* server-process-filter (proc string)
797 "Process a request from the server to edit some files.
798 PROC is the server process. STRING consists of a sequence of
799 commands prefixed by a dash. Some commands have arguments;
800 these are &-quoted and need to be decoded by `server-unquote-arg'.
801 The filter parses and executes these commands.
803 To illustrate the protocol, here is an example command that
804 emacsclient sends to create a new X frame (note that the whole
805 sequence is sent on a single line):
807 -env HOME=/home/lorentey
808 -env DISPLAY=:0.0
809 ... lots of other -env commands
810 -display :0.0
811 -window-system
813 The following commands are accepted by the server:
815 `-auth AUTH-STRING'
816 Authenticate the client using the secret authentication string
817 AUTH-STRING.
819 `-env NAME=VALUE'
820 An environment variable on the client side.
822 `-dir DIRNAME'
823 The current working directory of the client process.
825 `-current-frame'
826 Forbid the creation of new frames.
828 `-nowait'
829 Request that the next frame created should not be
830 associated with this client.
832 `-display DISPLAY'
833 Set the display name to open X frames on.
835 `-position LINE[:COLUMN]'
836 Go to the given line and column number
837 in the next file opened.
839 `-file FILENAME'
840 Load the given file in the current frame.
842 `-eval EXPR'
843 Evaluate EXPR as a Lisp expression and return the
844 result in -print commands.
846 `-window-system'
847 Open a new X frame.
849 `-tty DEVICENAME TYPE'
850 Open a new tty frame at the client.
852 `-suspend'
853 Suspend this tty frame. The client sends this string in
854 response to SIGTSTP and SIGTTOU. The server must cease all I/O
855 on this tty until it gets a -resume command.
857 `-resume'
858 Resume this tty frame. The client sends this string when it
859 gets the SIGCONT signal and it is the foreground process on its
860 controlling tty.
862 `-ignore COMMENT'
863 Do nothing, but put the comment in the server log.
864 Useful for debugging.
867 The following commands are accepted by the client:
869 `-emacs-pid PID'
870 Describes the process id of the Emacs process;
871 used to forward window change signals to it.
873 `-window-system-unsupported'
874 Signals that the server does not support creating X frames;
875 the client must try again with a tty frame.
877 `-print STRING'
878 Print STRING on stdout. Used to send values
879 returned by -eval.
881 `-error DESCRIPTION'
882 Signal an error and delete process PROC.
884 `-suspend'
885 Suspend this terminal, i.e., stop the client process.
886 Sent when the user presses C-z."
887 (server-log (concat "Received " string) proc)
888 ;; First things first: let's check the authentication
889 (unless (process-get proc :authenticated)
890 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
891 (equal (match-string 1 string) (process-get proc :auth-key)))
892 (progn
893 (setq string (substring string (match-end 0)))
894 (process-put proc :authenticated t)
895 (server-log "Authentication successful" proc))
896 (server-log "Authentication failed" proc)
897 (server-send-string
898 proc (concat "-error " (server-quote-arg "Authentication failed")))
899 ;; Before calling `delete-process', give emacsclient time to
900 ;; receive the error string and shut down on its own.
901 (sit-for 1)
902 (delete-process proc)
903 ;; We return immediately
904 (return-from server-process-filter)))
905 (let ((prev (process-get proc 'previous-string)))
906 (when prev
907 (setq string (concat prev string))
908 (process-put proc 'previous-string nil)))
909 (condition-case err
910 (progn
911 (server-add-client proc)
912 ;; Send our pid
913 (server-send-string proc (concat "-emacs-pid "
914 (number-to-string (emacs-pid)) "\n"))
915 (if (not (string-match "\n" string))
916 ;; Save for later any partial line that remains.
917 (when (> (length string) 0)
918 (process-put proc 'previous-string string))
920 ;; In earlier versions of server.el (where we used an `emacsserver'
921 ;; process), there could be multiple lines. Nowadays this is not
922 ;; supported any more.
923 (assert (eq (match-end 0) (length string)))
924 (let ((request (substring string 0 (match-beginning 0)))
925 (coding-system (and (default-value 'enable-multibyte-characters)
926 (or file-name-coding-system
927 default-file-name-coding-system)))
928 nowait ; t if emacsclient does not want to wait for us.
929 frame ; Frame opened for the client (if any).
930 display ; Open frame on this display.
931 parent-id ; Window ID for XEmbed
932 dontkill ; t if client should not be killed.
933 commands
935 use-current-frame
936 tty-name ; nil, `window-system', or the tty name.
937 tty-type ; string.
938 files
939 filepos
940 args-left)
941 ;; Remove this line from STRING.
942 (setq string (substring string (match-end 0)))
943 (setq args-left
944 (mapcar 'server-unquote-arg (split-string request " " t)))
945 (while args-left
946 (pcase (pop args-left)
947 ;; -version CLIENT-VERSION: obsolete at birth.
948 (`"-version" (pop args-left))
950 ;; -nowait: Emacsclient won't wait for a result.
951 (`"-nowait" (setq nowait t))
953 ;; -current-frame: Don't create frames.
954 (`"-current-frame" (setq use-current-frame t))
956 ;; -display DISPLAY:
957 ;; Open X frames on the given display instead of the default.
958 (`"-display"
959 (setq display (pop args-left))
960 (if (zerop (length display)) (setq display nil)))
962 ;; -parent-id ID:
963 ;; Open X frame within window ID, via XEmbed.
964 (`"-parent-id"
965 (setq parent-id (pop args-left))
966 (if (zerop (length parent-id)) (setq parent-id nil)))
968 ;; -window-system: Open a new X frame.
969 (`"-window-system"
970 (setq dontkill t)
971 (setq tty-name 'window-system))
973 ;; -resume: Resume a suspended tty frame.
974 (`"-resume"
975 (let ((terminal (process-get proc 'terminal)))
976 (setq dontkill t)
977 (push (lambda ()
978 (when (eq (terminal-live-p terminal) t)
979 (resume-tty terminal)))
980 commands)))
982 ;; -suspend: Suspend the client's frame. (In case we
983 ;; get out of sync, and a C-z sends a SIGTSTP to
984 ;; emacsclient.)
985 (`"-suspend"
986 (let ((terminal (process-get proc 'terminal)))
987 (setq dontkill t)
988 (push (lambda ()
989 (when (eq (terminal-live-p terminal) t)
990 (suspend-tty terminal)))
991 commands)))
993 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
994 ;; (The given comment appears in the server log.)
995 (`"-ignore"
996 (setq dontkill t)
997 (pop args-left))
999 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1000 (`"-tty"
1001 (setq tty-name (pop args-left)
1002 tty-type (pop args-left)
1003 dontkill (or dontkill
1004 (not use-current-frame))))
1006 ;; -position LINE[:COLUMN]: Set point to the given
1007 ;; position in the next file.
1008 (`"-position"
1009 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1010 (car args-left)))
1011 (error "Invalid -position command in client args"))
1012 (let ((arg (pop args-left)))
1013 (setq filepos
1014 (cons (string-to-number (match-string 1 arg))
1015 (string-to-number (or (match-string 2 arg)
1016 ""))))))
1018 ;; -file FILENAME: Load the given file.
1019 (`"-file"
1020 (let ((file (pop args-left)))
1021 (if coding-system
1022 (setq file (decode-coding-string file coding-system)))
1023 (setq file (expand-file-name file dir))
1024 (push (cons file filepos) files)
1025 (server-log (format "New file: %s %s"
1026 file (or filepos "")) proc))
1027 (setq filepos nil))
1029 ;; -eval EXPR: Evaluate a Lisp expression.
1030 (`"-eval"
1031 (if use-current-frame
1032 (setq use-current-frame 'always))
1033 (let ((expr (pop args-left)))
1034 (if coding-system
1035 (setq expr (decode-coding-string expr coding-system)))
1036 (push (lambda () (server-eval-and-print expr proc))
1037 commands)
1038 (setq filepos nil)))
1040 ;; -env NAME=VALUE: An environment variable.
1041 (`"-env"
1042 (let ((var (pop args-left)))
1043 ;; XXX Variables should be encoded as in getenv/setenv.
1044 (process-put proc 'env
1045 (cons var (process-get proc 'env)))))
1047 ;; -dir DIRNAME: The cwd of the emacsclient process.
1048 (`"-dir"
1049 (setq dir (pop args-left))
1050 (if coding-system
1051 (setq dir (decode-coding-string dir coding-system)))
1052 (setq dir (command-line-normalize-file-name dir)))
1054 ;; Unknown command.
1055 (arg (error "Unknown command: %s" arg))))
1057 (setq frame
1058 (cond
1059 ((and use-current-frame
1060 (or (eq use-current-frame 'always)
1061 ;; We can't use the Emacs daemon's
1062 ;; terminal frame.
1063 (not (and (daemonp)
1064 (null (cdr (frame-list)))
1065 (eq (selected-frame)
1066 terminal-frame)))))
1067 (setq tty-name nil tty-type nil)
1068 (if display (server-select-display display)))
1069 ((eq tty-name 'window-system)
1070 (server-create-window-system-frame display nowait proc
1071 parent-id))
1072 ;; When resuming on a tty, tty-name is nil.
1073 (tty-name
1074 (server-create-tty-frame tty-name tty-type proc))))
1076 (process-put
1077 proc 'continuation
1078 (lambda ()
1079 (with-current-buffer (get-buffer-create server-buffer)
1080 ;; Use the same cwd as the emacsclient, if possible, so
1081 ;; relative file names work correctly, even in `eval'.
1082 (let ((default-directory
1083 (if (and dir (file-directory-p dir))
1084 dir default-directory)))
1085 (server-execute proc files nowait commands
1086 dontkill frame tty-name)))))
1088 (when (or frame files)
1089 (server-goto-toplevel proc))
1091 (server-execute-continuation proc))))
1092 ;; condition-case
1093 (error (server-return-error proc err))))
1095 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1096 ;; This is run from timers and process-filters, i.e. "asynchronously".
1097 ;; But w.r.t the user, this is not really asynchronous since the timer
1098 ;; is run after 0s and the process-filter is run in response to the
1099 ;; user running `emacsclient'. So it is OK to override the
1100 ;; inhibit-quit flag, which is good since `commands' (as well as
1101 ;; find-file-noselect via the major-mode) can run arbitrary code,
1102 ;; including code that needs to wait.
1103 (with-local-quit
1104 (condition-case err
1105 (let* ((buffers
1106 (when files
1107 (server-visit-files files proc nowait))))
1109 (mapc 'funcall (nreverse commands))
1111 ;; Delete the client if necessary.
1112 (cond
1113 (nowait
1114 ;; Client requested nowait; return immediately.
1115 (server-log "Close nowait client" proc)
1116 (server-delete-client proc))
1117 ((and (not dontkill) (null buffers))
1118 ;; This client is empty; get rid of it immediately.
1119 (server-log "Close empty client" proc)
1120 (server-delete-client proc)))
1121 (cond
1122 ((or isearch-mode (minibufferp))
1123 nil)
1124 ((and frame (null buffers))
1125 (message "%s" (substitute-command-keys
1126 "When done with this frame, type \\[delete-frame]")))
1127 ((not (null buffers))
1128 (server-switch-buffer (car buffers) nil (cdr (car files)))
1129 (run-hooks 'server-switch-hook)
1130 (unless nowait
1131 (message "%s" (substitute-command-keys
1132 "When done with a buffer, type \\[server-edit]")))))
1133 (when (and frame (null tty-name))
1134 (server-unselect-display frame)))
1135 (error (server-return-error proc err)))))
1137 (defun server-return-error (proc err)
1138 (ignore-errors
1139 (server-send-string
1140 proc (concat "-error " (server-quote-arg
1141 (error-message-string err))))
1142 (server-log (error-message-string err) proc)
1143 ;; Before calling `delete-process', give emacsclient time to
1144 ;; receive the error string and shut down on its own.
1145 (sit-for 5)
1146 (delete-process proc)))
1148 (defun server-goto-line-column (line-col)
1149 "Move point to the position indicated in LINE-COL.
1150 LINE-COL should be a pair (LINE . COL)."
1151 (when line-col
1152 (goto-char (point-min))
1153 (forward-line (1- (car line-col)))
1154 (let ((column-number (cdr line-col)))
1155 (when (> column-number 0)
1156 (move-to-column (1- column-number))))))
1158 (defun server-visit-files (files proc &optional nowait)
1159 "Find FILES and return a list of buffers created.
1160 FILES is an alist whose elements are (FILENAME . FILEPOS)
1161 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1162 PROC is the client that requested this operation.
1163 NOWAIT non-nil means this client is not waiting for the results,
1164 so don't mark these buffers specially, just visit them normally."
1165 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1166 (let ((last-nonmenu-event t) client-record)
1167 ;; Restore the current buffer afterward, but not using save-excursion,
1168 ;; because we don't want to save point in this buffer
1169 ;; if it happens to be one of those specified by the server.
1170 (save-current-buffer
1171 (dolist (file files)
1172 ;; If there is an existing buffer modified or the file is
1173 ;; modified, revert it. If there is an existing buffer with
1174 ;; deleted file, offer to write it.
1175 (let* ((minibuffer-auto-raise (or server-raise-frame
1176 minibuffer-auto-raise))
1177 (filen (car file))
1178 (obuf (get-file-buffer filen)))
1179 (add-to-history 'file-name-history filen)
1180 (if (null obuf)
1181 (progn
1182 (run-hooks 'pre-command-hook)
1183 (set-buffer (find-file-noselect filen)))
1184 (set-buffer obuf)
1185 ;; separately for each file, in sync with post-command hooks,
1186 ;; with the new buffer current:
1187 (run-hooks 'pre-command-hook)
1188 (cond ((file-exists-p filen)
1189 (when (not (verify-visited-file-modtime obuf))
1190 (revert-buffer t nil)))
1192 (when (y-or-n-p
1193 (concat "File no longer exists: " filen
1194 ", write buffer to file? "))
1195 (write-file filen))))
1196 (unless server-buffer-clients
1197 (setq server-existing-buffer t)))
1198 (server-goto-line-column (cdr file))
1199 (run-hooks 'server-visit-hook)
1200 ;; hooks may be specific to current buffer:
1201 (run-hooks 'post-command-hook))
1202 (unless nowait
1203 ;; When the buffer is killed, inform the clients.
1204 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1205 (push proc server-buffer-clients))
1206 (push (current-buffer) client-record)))
1207 (unless nowait
1208 (process-put proc 'buffers
1209 (nconc (process-get proc 'buffers) client-record)))
1210 client-record))
1212 (defvar server-kill-buffer-running nil
1213 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1215 (defun server-buffer-done (buffer &optional for-killing)
1216 "Mark BUFFER as \"done\" for its client(s).
1217 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1218 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1219 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1220 a temp file).
1221 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1222 (let ((next-buffer nil)
1223 (killed nil))
1224 (dolist (proc server-clients)
1225 (let ((buffers (process-get proc 'buffers)))
1226 (or next-buffer
1227 (setq next-buffer (nth 1 (memq buffer buffers))))
1228 (when buffers ; Ignore bufferless clients.
1229 (setq buffers (delq buffer buffers))
1230 ;; Delete all dead buffers from PROC.
1231 (dolist (b buffers)
1232 (and (bufferp b)
1233 (not (buffer-live-p b))
1234 (setq buffers (delq b buffers))))
1235 (process-put proc 'buffers buffers)
1236 ;; If client now has no pending buffers,
1237 ;; tell it that it is done, and forget it entirely.
1238 (unless buffers
1239 (server-log "Close" proc)
1240 (if for-killing
1241 ;; `server-delete-client' might delete the client's
1242 ;; frames, which might change the current buffer. We
1243 ;; don't want that (bug#640).
1244 (save-current-buffer
1245 (server-delete-client proc))
1246 (server-delete-client proc))))))
1247 (when (and (bufferp buffer) (buffer-name buffer))
1248 ;; We may or may not kill this buffer;
1249 ;; if we do, do not call server-buffer-done recursively
1250 ;; from kill-buffer-hook.
1251 (let ((server-kill-buffer-running t))
1252 (with-current-buffer buffer
1253 (setq server-buffer-clients nil)
1254 (run-hooks 'server-done-hook))
1255 ;; Notice whether server-done-hook killed the buffer.
1256 (if (null (buffer-name buffer))
1257 (setq killed t)
1258 ;; Don't bother killing or burying the buffer
1259 ;; when we are called from kill-buffer.
1260 (unless for-killing
1261 (when (and (not killed)
1262 server-kill-new-buffers
1263 (with-current-buffer buffer
1264 (not server-existing-buffer)))
1265 (setq killed t)
1266 (bury-buffer buffer)
1267 ;; Prevent kill-buffer from prompting (Bug#3696).
1268 (with-current-buffer buffer
1269 (set-buffer-modified-p nil))
1270 (kill-buffer buffer))
1271 (unless killed
1272 (if (server-temp-file-p buffer)
1273 (progn
1274 (with-current-buffer buffer
1275 (set-buffer-modified-p nil))
1276 (kill-buffer buffer)
1277 (setq killed t))
1278 (bury-buffer buffer)))))))
1279 (list next-buffer killed)))
1281 (defun server-temp-file-p (&optional buffer)
1282 "Return non-nil if BUFFER contains a file considered temporary.
1283 These are files whose names suggest they are repeatedly
1284 reused to pass information to another program.
1286 The variable `server-temp-file-regexp' controls which filenames
1287 are considered temporary."
1288 (and (buffer-file-name buffer)
1289 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1291 (defun server-done ()
1292 "Offer to save current buffer, mark it as \"done\" for clients.
1293 This kills or buries the buffer, then returns a list
1294 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1295 as a suggestion for what to select next, or nil.
1296 KILLED is t if we killed BUFFER, which happens if it was created
1297 specifically for the clients and did not exist before their request for it."
1298 (when server-buffer-clients
1299 (if (server-temp-file-p)
1300 ;; For a temp file, save, and do make a non-numeric backup
1301 ;; (unless make-backup-files is nil).
1302 (let ((version-control nil)
1303 (buffer-backed-up nil))
1304 (save-buffer))
1305 (when (and (buffer-modified-p)
1306 buffer-file-name
1307 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1308 (save-buffer)))
1309 (server-buffer-done (current-buffer))))
1311 ;; Ask before killing a server buffer.
1312 ;; It was suggested to release its client instead,
1313 ;; but I think that is dangerous--the client would proceed
1314 ;; using whatever is on disk in that file. -- rms.
1315 (defun server-kill-buffer-query-function ()
1316 "Ask before killing a server buffer."
1317 (or (not server-buffer-clients)
1318 (let ((res t))
1319 (dolist (proc server-buffer-clients res)
1320 (when (and (memq proc server-clients)
1321 (eq (process-status proc) 'open))
1322 (setq res nil))))
1323 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1324 (buffer-name (current-buffer))))))
1326 (defun server-kill-emacs-query-function ()
1327 "Ask before exiting Emacs if it has live clients."
1328 (or (not server-clients)
1329 (let (live-client)
1330 (dolist (proc server-clients live-client)
1331 (when (memq t (mapcar 'buffer-live-p (process-get
1332 proc 'buffers)))
1333 (setq live-client t))))
1334 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1336 (defun server-kill-buffer ()
1337 "Remove the current buffer from its clients' buffer list.
1338 Designed to be added to `kill-buffer-hook'."
1339 ;; Prevent infinite recursion if user has made server-done-hook
1340 ;; call kill-buffer.
1341 (or server-kill-buffer-running
1342 (and server-buffer-clients
1343 (let ((server-kill-buffer-running t))
1344 (when server-process
1345 (server-buffer-done (current-buffer) t))))))
1347 (defun server-edit (&optional arg)
1348 "Switch to next server editing buffer; say \"Done\" for current buffer.
1349 If a server buffer is current, it is marked \"done\" and optionally saved.
1350 The buffer is also killed if it did not exist before the clients asked for it.
1351 When all of a client's buffers are marked as \"done\", the client is notified.
1353 Temporary files such as MH <draft> files are always saved and backed up,
1354 no questions asked. (The variable `make-backup-files', if nil, still
1355 inhibits a backup; you can set it locally in a particular buffer to
1356 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1357 which filenames are considered temporary.
1359 If invoked with a prefix argument, or if there is no server process running,
1360 starts server process and that is all. Invoked by \\[server-edit]."
1361 (interactive "P")
1362 (cond
1363 ((or arg
1364 (not server-process)
1365 (memq (process-status server-process) '(signal exit)))
1366 (server-mode 1))
1367 (server-clients (apply 'server-switch-buffer (server-done)))
1368 (t (message "No server editing buffers exist"))))
1370 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1371 "Switch to another buffer, preferably one that has a client.
1372 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1374 KILLED-ONE is t in a recursive call if we have already killed one
1375 temp-file server buffer. This means we should avoid the final
1376 \"switch to some other buffer\" since we've already effectively
1377 done that.
1379 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1380 visit NEXT-BUFFER in an existing window. If non-nil, it should
1381 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1382 (if (null next-buffer)
1383 (progn
1384 (let ((rest server-clients))
1385 (while (and rest (not next-buffer))
1386 (let ((proc (car rest)))
1387 ;; Only look at frameless clients, or those in the selected
1388 ;; frame.
1389 (when (or (not (process-get proc 'frame))
1390 (eq (process-get proc 'frame) (selected-frame)))
1391 (setq next-buffer (car (process-get proc 'buffers))))
1392 (setq rest (cdr rest)))))
1393 (and next-buffer (server-switch-buffer next-buffer killed-one))
1394 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1395 ;; (switch-to-buffer (other-buffer))
1396 (message "No server buffers remain to edit")))
1397 (if (not (buffer-live-p next-buffer))
1398 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1399 ;; and try the next surviving server buffer.
1400 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1401 ;; OK, we know next-buffer is live, let's display and select it.
1402 (if (functionp server-window)
1403 (funcall server-window next-buffer)
1404 (let ((win (get-buffer-window next-buffer 0)))
1405 (if (and win (not server-window))
1406 ;; The buffer is already displayed: just reuse the
1407 ;; window. If FILEPOS is non-nil, use it to replace the
1408 ;; window's own value of point.
1409 (progn
1410 (select-window win)
1411 (set-buffer next-buffer)
1412 (when filepos
1413 (server-goto-line-column filepos)))
1414 ;; Otherwise, let's find an appropriate window.
1415 (cond ((window-live-p server-window)
1416 (select-window server-window))
1417 ((framep server-window)
1418 (unless (frame-live-p server-window)
1419 (setq server-window (make-frame)))
1420 (select-window (frame-selected-window server-window))))
1421 (when (window-minibuffer-p (selected-window))
1422 (select-window (next-window nil 'nomini 0)))
1423 ;; Move to a non-dedicated window, if we have one.
1424 (when (window-dedicated-p (selected-window))
1425 (select-window
1426 (get-window-with-predicate
1427 (lambda (w)
1428 (and (not (window-dedicated-p w))
1429 (equal (frame-terminal (window-frame w))
1430 (frame-terminal (selected-frame)))))
1431 'nomini 'visible (selected-window))))
1432 (condition-case nil
1433 (switch-to-buffer next-buffer)
1434 ;; After all the above, we might still have ended up with
1435 ;; a minibuffer/dedicated-window (if there's no other).
1436 (error (pop-to-buffer next-buffer)))))))
1437 (when server-raise-frame
1438 (select-frame-set-input-focus (window-frame (selected-window))))))
1440 ;;;###autoload
1441 (defun server-save-buffers-kill-terminal (arg)
1442 ;; Called from save-buffers-kill-terminal in files.el.
1443 "Offer to save each buffer, then kill the current client.
1444 With ARG non-nil, silently save all file-visiting buffers, then kill.
1446 If emacsclient was started with a list of filenames to edit, then
1447 only these files will be asked to be saved."
1448 (let ((proc (frame-parameter (selected-frame) 'client)))
1449 (cond ((eq proc 'nowait)
1450 ;; Nowait frames have no client buffer list.
1451 (if (cdr (frame-list))
1452 (progn (save-some-buffers arg)
1453 (delete-frame))
1454 ;; If we're the last frame standing, kill Emacs.
1455 (save-buffers-kill-emacs arg)))
1456 ((processp proc)
1457 (let ((buffers (process-get proc 'buffers)))
1458 ;; If client is bufferless, emulate a normal Emacs exit
1459 ;; and offer to save all buffers. Otherwise, offer to
1460 ;; save only the buffers belonging to the client.
1461 (save-some-buffers
1462 arg (if buffers
1463 (lambda () (memq (current-buffer) buffers))
1465 (server-delete-client proc)))
1466 (t (error "Invalid client frame")))))
1468 (define-key ctl-x-map "#" 'server-edit)
1470 (defun server-unload-function ()
1471 "Unload the server library."
1472 (server-mode -1)
1473 (substitute-key-definition 'server-edit nil ctl-x-map)
1474 (save-current-buffer
1475 (dolist (buffer (buffer-list))
1476 (set-buffer buffer)
1477 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1478 ;; continue standard unloading
1479 nil)
1482 (provide 'server)
1484 ;;; server.el ends here