Fix interaction of load-theme with cust-theme.el.
[emacs.git] / lisp / server.el
blobed83225eccddd18c263f628a44a6896bb70c9c73
1 ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
3 ;; Copyright (C) 1986-1987, 1992, 1994-2012 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 This variable only takes effect when the Emacs server is using
117 TCP instead of local sockets. A nil value means to use a random
118 port number."
119 :group 'server
120 :type '(choice
121 (string :tag "Port number")
122 (const :tag "Random" nil))
123 :version "24.1")
124 ;;;###autoload
125 (put 'server-port 'risky-local-variable t)
127 (defcustom server-auth-dir (locate-user-emacs-file "server/")
128 "Directory for server authentication files.
129 We only use this if `server-use-tcp' is non-nil.
130 Otherwise we use `server-socket-dir'.
132 NOTE: On FAT32 filesystems, directories are not secure;
133 files can be read and modified by any user or process.
134 It is strongly suggested to set `server-auth-dir' to a
135 directory residing in a NTFS partition instead."
136 :group 'server
137 :type 'directory
138 :version "22.1")
139 ;;;###autoload
140 (put 'server-auth-dir 'risky-local-variable t)
142 (defcustom server-raise-frame t
143 "If non-nil, raise frame when switching to a buffer."
144 :group 'server
145 :type 'boolean
146 :version "22.1")
148 (defcustom server-visit-hook nil
149 "Hook run when visiting a file for the Emacs server."
150 :group 'server
151 :type 'hook)
153 (defcustom server-switch-hook nil
154 "Hook run when switching to a buffer for the Emacs server."
155 :group 'server
156 :type 'hook)
158 (defcustom server-done-hook nil
159 "Hook run when done editing a buffer for the Emacs server."
160 :group 'server
161 :type 'hook)
163 (defvar server-process nil
164 "The current server process.")
166 (defvar server-clients nil
167 "List of current server clients.
168 Each element is a process.")
170 (defvar server-buffer-clients nil
171 "List of client processes requesting editing of current buffer.")
172 (make-variable-buffer-local 'server-buffer-clients)
173 ;; Changing major modes should not erase this local.
174 (put 'server-buffer-clients 'permanent-local t)
176 (defcustom server-window nil
177 "Specification of the window to use for selecting Emacs server buffers.
178 If nil, use the selected window.
179 If it is a function, it should take one argument (a buffer) and
180 display and select it. A common value is `pop-to-buffer'.
181 If it is a window, use that.
182 If it is a frame, use the frame's selected window.
184 It is not meaningful to set this to a specific frame or window with Custom.
185 Only programs can do so."
186 :group 'server
187 :version "22.1"
188 :type '(choice (const :tag "Use selected window"
189 :match (lambda (widget value)
190 (not (functionp value)))
191 nil)
192 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
193 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
194 (function :tag "Other function")))
196 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
197 "Regexp matching names of temporary files.
198 These are deleted and reused after each edit by the programs that
199 invoke the Emacs server."
200 :group 'server
201 :type 'regexp)
203 (defcustom server-kill-new-buffers t
204 "Whether to kill buffers when done with them.
205 If non-nil, kill a buffer unless it already existed before editing
206 it with the Emacs server. If nil, kill only buffers as specified by
207 `server-temp-file-regexp'.
208 Please note that only buffers that still have a client are killed,
209 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
210 in this way."
211 :group 'server
212 :type 'boolean
213 :version "21.1")
215 (or (assq 'server-buffer-clients minor-mode-alist)
216 (push '(server-buffer-clients " Server") minor-mode-alist))
218 (defvar server-existing-buffer nil
219 "Non-nil means the buffer existed before the server was asked to visit it.
220 This means that the server should not kill the buffer when you say you
221 are done with it in the server.")
222 (make-variable-buffer-local 'server-existing-buffer)
224 (defcustom server-name "server"
225 "The name of the Emacs server, if this Emacs process creates one.
226 The command `server-start' makes use of this. It should not be
227 changed while a server is running."
228 :group 'server
229 :type 'string
230 :version "23.1")
232 ;; We do not use `temporary-file-directory' here, because emacsclient
233 ;; does not read the init file.
234 (defvar server-socket-dir
235 (and (featurep 'make-network-process '(:family local))
236 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
237 "The directory in which to place the server socket.
238 If local sockets are not supported, this is nil.")
240 (defun server-clients-with (property value)
241 "Return a list of clients with PROPERTY set to VALUE."
242 (let (result)
243 (dolist (proc server-clients)
244 (when (equal value (process-get proc property))
245 (push proc result)))
246 result))
248 (defun server-add-client (proc)
249 "Create a client for process PROC, if it doesn't already have one.
250 New clients have no properties."
251 (add-to-list 'server-clients proc))
253 (defmacro server-with-environment (env vars &rest body)
254 "Evaluate BODY with environment variables VARS set to those in ENV.
255 The environment variables are then restored to their previous values.
257 VARS should be a list of strings.
258 ENV should be in the same format as `process-environment'."
259 (declare (indent 2))
260 (let ((var (make-symbol "var"))
261 (value (make-symbol "value")))
262 `(let ((process-environment process-environment))
263 (dolist (,var ,vars)
264 (let ((,value (getenv-internal ,var ,env)))
265 (push (if (stringp ,value)
266 (concat ,var "=" ,value)
267 ,var)
268 process-environment)))
269 (progn ,@body))))
271 (defun server-delete-client (proc &optional noframe)
272 "Delete PROC, including its buffers, terminals and frames.
273 If NOFRAME is non-nil, let the frames live.
274 Updates `server-clients'."
275 (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
276 ;; Force a new lookup of client (prevents infinite recursion).
277 (when (memq proc server-clients)
278 (let ((buffers (process-get proc 'buffers)))
280 ;; Kill the client's buffers.
281 (dolist (buf buffers)
282 (when (buffer-live-p buf)
283 (with-current-buffer buf
284 ;; Kill the buffer if necessary.
285 (when (and (equal server-buffer-clients
286 (list proc))
287 (or (and server-kill-new-buffers
288 (not server-existing-buffer))
289 (server-temp-file-p))
290 (not (buffer-modified-p)))
291 (let (flag)
292 (unwind-protect
293 (progn (setq server-buffer-clients nil)
294 (kill-buffer (current-buffer))
295 (setq flag t))
296 (unless flag
297 ;; Restore clients if user pressed C-g in `kill-buffer'.
298 (setq server-buffer-clients (list proc)))))))))
300 ;; Delete the client's frames.
301 (unless noframe
302 (dolist (frame (frame-list))
303 (when (and (frame-live-p frame)
304 (equal proc (frame-parameter frame 'client)))
305 ;; Prevent `server-handle-delete-frame' from calling us
306 ;; recursively.
307 (set-frame-parameter frame 'client nil)
308 (delete-frame frame))))
310 (setq server-clients (delq proc server-clients))
312 ;; Delete the client's tty, except on Windows (both GUI and console),
313 ;; where there's only one terminal and does not make sense to delete it.
314 (unless (eq system-type 'windows-nt)
315 (let ((terminal (process-get proc 'terminal)))
316 ;; Only delete the terminal if it is non-nil.
317 (when (and terminal (eq (terminal-live-p terminal) t))
318 (delete-terminal terminal))))
320 ;; Delete the client's process.
321 (if (eq (process-status proc) 'open)
322 (delete-process proc))
324 (server-log "Deleted" proc))))
326 (defvar server-log-time-function 'current-time-string
327 "Function to generate timestamps for `server-buffer'.")
329 (defconst server-buffer " *server*"
330 "Buffer used internally by Emacs's server.
331 One use is to log the I/O for debugging purposes (see `server-log'),
332 the other is to provide a current buffer in which the process filter can
333 safely let-bind buffer-local variables like `default-directory'.")
335 (defvar server-log nil
336 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
338 (defun server-log (string &optional client)
339 "If `server-log' is non-nil, log STRING to `server-buffer'.
340 If CLIENT is non-nil, add a description of it to the logged message."
341 (when server-log
342 (with-current-buffer (get-buffer-create server-buffer)
343 (goto-char (point-max))
344 (insert (funcall server-log-time-function)
345 (cond
346 ((null client) " ")
347 ((listp client) (format " %s: " (car client)))
348 (t (format " %s: " client)))
349 string)
350 (or (bolp) (newline)))))
352 (defun server-sentinel (proc msg)
353 "The process sentinel for Emacs server connections."
354 ;; If this is a new client process, set the query-on-exit flag to nil
355 ;; for this process (it isn't inherited from the server process).
356 (when (and (eq (process-status proc) 'open)
357 (process-query-on-exit-flag proc))
358 (set-process-query-on-exit-flag proc nil))
359 ;; Delete the associated connection file, if applicable.
360 ;; Although there's no 100% guarantee that the file is owned by the
361 ;; running Emacs instance, server-start uses server-running-p to check
362 ;; for possible servers before doing anything, so it *should* be ours.
363 (and (process-contact proc :server)
364 (eq (process-status proc) 'closed)
365 (ignore-errors
366 (delete-file (process-get proc :server-file))))
367 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
368 (server-delete-client proc))
370 (defun server-select-display (display)
371 ;; If the current frame is on `display' we're all set.
372 ;; Similarly if we are unable to open frames on other displays, there's
373 ;; nothing more we can do.
374 (unless (or (not (fboundp 'make-frame-on-display))
375 (equal (frame-parameter (selected-frame) 'display) display))
376 ;; Otherwise, look for an existing frame there and select it.
377 (dolist (frame (frame-list))
378 (when (equal (frame-parameter frame 'display) display)
379 (select-frame frame)))
380 ;; If there's no frame on that display yet, create and select one.
381 (unless (equal (frame-parameter (selected-frame) 'display) display)
382 (let* ((buffer (generate-new-buffer " *server-dummy*"))
383 (frame (make-frame-on-display
384 display
385 ;; Make it display (and remember) some dummy buffer, so
386 ;; we can detect later if the frame is in use or not.
387 `((server-dummy-buffer . ,buffer)
388 ;; This frame may be deleted later (see
389 ;; server-unselect-display) so we want it to be as
390 ;; unobtrusive as possible.
391 (visibility . nil)))))
392 (select-frame frame)
393 (set-window-buffer (selected-window) buffer)
394 frame))))
396 (defun server-unselect-display (frame)
397 (when (frame-live-p frame)
398 ;; If the temporary frame is in use (displays something real), make it
399 ;; visible. If not (which can happen if the user's customizations call
400 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
401 ;; the last real frame is deleted.
403 ;; Rewritten to avoid inadvertently killing the current buffer after
404 ;; `delete-frame' removed FRAME (Bug#10729).
405 (let ((buffer (frame-parameter frame 'server-dummy-buffer)))
406 (if (and (one-window-p 'nomini frame)
407 (eq (window-buffer (frame-first-window frame)) buffer))
408 ;; The temp frame still only shows one buffer, and that is the
409 ;; internal temp buffer.
410 (delete-frame frame)
411 (set-frame-parameter frame 'visibility t)
412 (set-frame-parameter frame 'server-dummy-buffer nil))
413 (when (buffer-live-p buffer)
414 (kill-buffer buffer)))))
416 (defun server-handle-delete-frame (frame)
417 "Delete the client connection when the emacsclient frame is deleted.
418 \(To be used from `delete-frame-functions'.)"
419 (let ((proc (frame-parameter frame 'client)))
420 (when (and (frame-live-p frame)
421 proc
422 ;; See if this is the last frame for this client.
423 (>= 1 (let ((frame-num 0))
424 (dolist (f (frame-list))
425 (when (eq proc (frame-parameter f 'client))
426 (setq frame-num (1+ frame-num))))
427 frame-num)))
428 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
429 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
431 (defun server-handle-suspend-tty (terminal)
432 "Notify the client process that its tty device is suspended."
433 (dolist (proc (server-clients-with 'terminal terminal))
434 (server-log (format "server-handle-suspend-tty, terminal %s" terminal)
435 proc)
436 (condition-case nil
437 (server-send-string proc "-suspend \n")
438 (file-error ;The pipe/socket was closed.
439 (ignore-errors (server-delete-client proc))))))
441 (defun server-unquote-arg (arg)
442 "Remove &-quotation from ARG.
443 See `server-quote-arg' and `server-process-filter'."
444 (replace-regexp-in-string
445 "&." (lambda (s)
446 (case (aref s 1)
447 (?& "&")
448 (?- "-")
449 (?n "\n")
450 (t " ")))
451 arg t t))
453 (defun server-quote-arg (arg)
454 "In ARG, insert a & before each &, each space, each newline, and -.
455 Change spaces to underscores, too, so that the return value never
456 contains a space.
458 See `server-unquote-arg' and `server-process-filter'."
459 (replace-regexp-in-string
460 "[-&\n ]" (lambda (s)
461 (case (aref s 0)
462 (?& "&&")
463 (?- "&-")
464 (?\n "&n")
465 (?\s "&_")))
466 arg t t))
468 (defun server-send-string (proc string)
469 "A wrapper around `process-send-string' for logging."
470 (server-log (concat "Sent " string) proc)
471 (process-send-string proc string))
473 (defun server-ensure-safe-dir (dir)
474 "Make sure DIR is a directory with no race-condition issues.
475 Creates the directory if necessary and makes sure:
476 - there's no symlink involved
477 - it's owned by us
478 - it's not readable/writable by anybody else."
479 (setq dir (directory-file-name dir))
480 (let ((attrs (file-attributes dir 'integer)))
481 (unless attrs
482 (letf (((default-file-modes) ?\700)) (make-directory dir t))
483 (setq attrs (file-attributes dir 'integer)))
485 ;; Check that it's safe for use.
486 (let* ((uid (nth 2 attrs))
487 (w32 (eq system-type 'windows-nt))
488 (safe (catch :safe
489 (unless (eq t (car attrs)) ; is a dir?
490 (throw :safe nil))
491 (when (and w32 (zerop uid)) ; on FAT32?
492 (display-warning
493 'server
494 (format "Using `%s' to store Emacs-server authentication files.
495 Directories on FAT32 filesystems are NOT secure against tampering.
496 See variable `server-auth-dir' for details."
497 (file-name-as-directory dir))
498 :warning)
499 (throw :safe t))
500 (unless (or (= uid (user-uid)) ; is the dir ours?
501 (and w32
502 ;; Files created on Windows by
503 ;; Administrator (RID=500) have
504 ;; the Administrators (RID=544)
505 ;; group recorded as the owner.
506 (= uid 544) (= (user-uid) 500)))
507 (throw :safe nil))
508 (when w32 ; on NTFS?
509 (throw :safe t))
510 (unless (zerop (logand ?\077 (file-modes dir)))
511 (throw :safe nil))
512 t)))
513 (unless safe
514 (error "The directory `%s' is unsafe" dir)))))
516 ;;;###autoload
517 (defun server-start (&optional leave-dead inhibit-prompt)
518 "Allow this Emacs process to be a server for client processes.
519 This starts a server communications subprocess through which
520 client \"editors\" can send your editing commands to this Emacs
521 job. To use the server, set up the program `emacsclient' in the
522 Emacs distribution as your standard \"editor\".
524 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
525 kill any existing server communications subprocess.
527 If a server is already running, restart it. If clients are
528 running, ask the user for confirmation first, unless optional
529 argument INHIBIT-PROMPT is non-nil.
531 To force-start a server, do \\[server-force-delete] and then
532 \\[server-start]."
533 (interactive "P")
534 (when (or (not server-clients)
535 ;; Ask the user before deleting existing clients---except
536 ;; when we can't get user input, which may happen when
537 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
538 (cond
539 ((and (daemonp)
540 (null (cdr (frame-list)))
541 (eq (selected-frame) terminal-frame))
542 leave-dead)
543 (inhibit-prompt t)
544 (t (yes-or-no-p
545 "The current server still has clients; delete them? "))))
546 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
547 (server-file (expand-file-name server-name server-dir)))
548 (when server-process
549 ;; kill it dead!
550 (ignore-errors (delete-process server-process)))
551 ;; Delete the socket files made by previous server invocations.
552 (if (not (eq t (server-running-p server-name)))
553 ;; Remove any leftover socket or authentication file
554 (ignore-errors
555 (let (delete-by-moving-to-trash)
556 (delete-file server-file)))
557 (setq server-mode nil) ;; already set by the minor mode code
558 (display-warning
559 'server
560 (concat "Unable to start the Emacs server.\n"
561 (format "There is an existing Emacs server, named %S.\n"
562 server-name)
563 "To start the server in this Emacs process, stop the existing
564 server or call `M-x server-force-delete' to forcibly disconnect it.")
565 :warning)
566 (setq leave-dead t))
567 ;; If this Emacs already had a server, clear out associated status.
568 (while server-clients
569 (server-delete-client (car server-clients)))
570 ;; Now any previous server is properly stopped.
571 (if leave-dead
572 (progn
573 (unless (eq t leave-dead) (server-log (message "Server stopped")))
574 (setq server-process nil))
575 ;; Make sure there is a safe directory in which to place the socket.
576 (server-ensure-safe-dir server-dir)
577 (when server-process
578 (server-log (message "Restarting server")))
579 (letf (((default-file-modes) ?\700))
580 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
581 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
582 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
583 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
584 (add-hook 'kill-emacs-hook 'server-force-stop) ;Cleanup upon exit.
585 (setq server-process
586 (apply #'make-network-process
587 :name server-name
588 :server t
589 :noquery t
590 :sentinel 'server-sentinel
591 :filter 'server-process-filter
592 ;; We must receive file names without being decoded.
593 ;; Those are decoded by server-process-filter according
594 ;; to file-name-coding-system. Also don't get
595 ;; confused by CRs since we don't quote them.
596 :coding 'raw-text-unix
597 ;; The other args depend on the kind of socket used.
598 (if server-use-tcp
599 (list :family 'ipv4 ;; We're not ready for IPv6 yet
600 :service (or server-port t)
601 :host (or server-host 'local)
602 :plist '(:authenticated nil))
603 (list :family 'local
604 :service server-file
605 :plist '(:authenticated t)))))
606 (unless server-process (error "Could not start server process"))
607 (process-put server-process :server-file server-file)
608 (when server-use-tcp
609 (let ((auth-key
610 (loop
611 ;; The auth key is a 64-byte string of random chars in the
612 ;; range `!'..`~'.
613 repeat 64
614 collect (+ 33 (random 94)) into auth
615 finally return (concat auth))))
616 (process-put server-process :auth-key auth-key)
617 (with-temp-file server-file
618 (set-buffer-multibyte nil)
619 (setq buffer-file-coding-system 'no-conversion)
620 (insert (format-network-address
621 (process-contact server-process :local))
622 " " (number-to-string (emacs-pid)) ; Kept for compatibility
623 "\n" auth-key)))))))))
625 (defun server-force-stop ()
626 "Kill all connections to the current server.
627 This function is meant to be called from `kill-emacs-hook'."
628 (server-start t t))
630 ;;;###autoload
631 (defun server-force-delete (&optional name)
632 "Unconditionally delete connection file for server NAME.
633 If server is running, it is first stopped.
634 NAME defaults to `server-name'. With argument, ask for NAME."
635 (interactive
636 (list (if current-prefix-arg
637 (read-string "Server name: " nil nil server-name))))
638 (when server-mode (with-temp-message nil (server-mode -1)))
639 (let ((file (expand-file-name (or name server-name)
640 (if server-use-tcp
641 server-auth-dir
642 server-socket-dir))))
643 (condition-case nil
644 (let (delete-by-moving-to-trash)
645 (delete-file file)
646 (message "Connection file %S deleted" file))
647 (file-error
648 (message "No connection file %S" file)))))
650 (defun server-running-p (&optional name)
651 "Test whether server NAME is running.
653 Return values:
654 nil the server is definitely not running.
655 t the server seems to be running.
656 something else we cannot determine whether it's running without using
657 commands which may have to wait for a long time."
658 (unless name (setq name server-name))
659 (condition-case nil
660 (if server-use-tcp
661 (with-temp-buffer
662 (insert-file-contents-literally (expand-file-name name server-auth-dir))
663 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
664 (assq 'comm
665 (process-attributes
666 (string-to-number (match-string 1))))
668 :other))
669 (delete-process
670 (make-network-process
671 :name "server-client-test" :family 'local :server nil :noquery t
672 :service (expand-file-name name server-socket-dir)))
674 (file-error nil)))
676 ;;;###autoload
677 (define-minor-mode server-mode
678 "Toggle Server mode.
679 With a prefix argument ARG, enable Server mode if ARG is
680 positive, and disable it otherwise. If called from Lisp, enable
681 Server mode if ARG is omitted or nil.
683 Server mode runs a process that accepts commands from the
684 `emacsclient' program. See Info node `Emacs server' and
685 `server-start' for details."
686 :global t
687 :group 'server
688 :version "22.1"
689 ;; Fixme: Should this check for an existing server socket and do
690 ;; nothing if there is one (for multiple Emacs sessions)?
691 (server-start (not server-mode)))
693 (defun server-eval-and-print (expr proc)
694 "Eval EXPR and send the result back to client PROC."
695 ;; While we're running asynchronously (from a process filter), it is likely
696 ;; that the emacsclient command was run in response to a user
697 ;; action, so the user probably knows that Emacs is processing this
698 ;; emacsclient request, so if we get a C-g it's likely that the user
699 ;; intended it to interrupt us rather than interrupt whatever Emacs
700 ;; was doing before it started handling the process filter.
701 ;; Hence `with-local-quit' (bug#6585).
702 (let ((v (with-local-quit (eval (car (read-from-string expr))))))
703 (when proc
704 (with-temp-buffer
705 (let ((standard-output (current-buffer)))
706 (pp v)
707 (let ((text (buffer-substring-no-properties
708 (point-min) (point-max))))
709 (server-reply-print (server-quote-arg text) proc)))))))
711 (defconst server-msg-size 1024
712 "Maximum size of a message sent to a client.")
714 (defun server-reply-print (qtext proc)
715 "Send a `-print QTEXT' command to client PROC.
716 QTEXT must be already quoted.
717 This handles splitting the command if it would be bigger than
718 `server-msg-size'."
719 (let ((prefix "-print ")
720 part)
721 (while (> (+ (length qtext) (length prefix) 1) server-msg-size)
722 ;; We have to split the string
723 (setq part (substring qtext 0 (- server-msg-size (length prefix) 1)))
724 ;; Don't split in the middle of a quote sequence
725 (if (string-match "\\(^\\|[^&]\\)\\(&&\\)+$" part)
726 ;; There is an uneven number of & at the end
727 (setq part (substring part 0 -1)))
728 (setq qtext (substring qtext (length part)))
729 (server-send-string proc (concat prefix part "\n"))
730 (setq prefix "-print-nonl "))
731 (server-send-string proc (concat prefix qtext "\n"))))
733 (defun server-create-tty-frame (tty type proc)
734 (unless tty
735 (error "Invalid terminal device"))
736 (unless type
737 (error "Invalid terminal type"))
738 (add-to-list 'frame-inherited-parameters 'client)
739 (let ((frame
740 (server-with-environment (process-get proc 'env)
741 '("LANG" "LC_CTYPE" "LC_ALL"
742 ;; For tgetent(3); list according to ncurses(3).
743 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
744 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
745 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
746 "TERMINFO_DIRS" "TERMPATH"
747 ;; rxvt wants these
748 "COLORFGBG" "COLORTERM")
749 (make-frame `((window-system . nil)
750 (tty . ,tty)
751 (tty-type . ,type)
752 ;; Ignore nowait here; we always need to
753 ;; clean up opened ttys when the client dies.
754 (client . ,proc)
755 ;; This is a leftover from an earlier
756 ;; attempt at making it possible for process
757 ;; run in the server process to use the
758 ;; environment of the client process.
759 ;; It has no effect now and to make it work
760 ;; we'd need to decide how to make
761 ;; process-environment interact with client
762 ;; envvars, and then to change the
763 ;; C functions `child_setup' and
764 ;; `getenv_internal' accordingly.
765 (environment . ,(process-get proc 'env)))))))
767 ;; ttys don't use the `display' parameter, but callproc.c does to set
768 ;; the DISPLAY environment on subprocesses.
769 (set-frame-parameter frame 'display
770 (getenv-internal "DISPLAY" (process-get proc 'env)))
771 (select-frame frame)
772 (process-put proc 'frame frame)
773 (process-put proc 'terminal (frame-terminal frame))
775 ;; Display *scratch* by default.
776 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
778 frame))
780 (defun server-create-window-system-frame (display nowait proc parent-id
781 &optional parameters)
782 (add-to-list 'frame-inherited-parameters 'client)
783 (if (not (fboundp 'make-frame-on-display))
784 (progn
785 ;; This emacs does not support X.
786 (server-log "Window system unsupported" proc)
787 (server-send-string proc "-window-system-unsupported \n")
788 nil)
789 ;; Flag frame as client-created, but use a dummy client.
790 ;; This will prevent the frame from being deleted when
791 ;; emacsclient quits while also preventing
792 ;; `server-save-buffers-kill-terminal' from unexpectedly
793 ;; killing emacs on that frame.
794 (let* ((params `((client . ,(if nowait 'nowait proc))
795 ;; This is a leftover, see above.
796 (environment . ,(process-get proc 'env))
797 ,@parameters))
798 (display (or display
799 (frame-parameter nil 'display)
800 (getenv "DISPLAY")
801 (error "Please specify display")))
802 frame)
803 (if parent-id
804 (push (cons 'parent-id (string-to-number parent-id)) params))
805 (setq frame (make-frame-on-display display params))
806 (server-log (format "%s created" frame) proc)
807 (select-frame frame)
808 (process-put proc 'frame frame)
809 (process-put proc 'terminal (frame-terminal frame))
811 ;; Display *scratch* by default.
812 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
813 frame)))
815 (defun server-goto-toplevel (proc)
816 (condition-case nil
817 ;; If we're running isearch, we must abort it to allow Emacs to
818 ;; display the buffer and switch to it.
819 (dolist (buffer (buffer-list))
820 (with-current-buffer buffer
821 (when (bound-and-true-p isearch-mode)
822 (isearch-cancel))))
823 ;; Signaled by isearch-cancel.
824 (quit (message nil)))
825 (when (> (recursion-depth) 0)
826 ;; We're inside a minibuffer already, so if the emacs-client is trying
827 ;; to open a frame on a new display, we might end up with an unusable
828 ;; frame because input from that display will be blocked (until exiting
829 ;; the minibuffer). Better exit this minibuffer right away.
830 ;; Similarly with recursive-edits such as the splash screen.
831 (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
832 (top-level)))
834 ;; We use various special properties on process objects:
835 ;; - `env' stores the info about the environment of the emacsclient process.
836 ;; - `continuation' is a no-arg function that we need to execute. It contains
837 ;; commands we wanted to execute in some earlier invocation of the process
838 ;; filter but that we somehow were unable to process at that time
839 ;; (e.g. because we first need to throw to the toplevel).
841 (defun server-execute-continuation (proc)
842 (let ((continuation (process-get proc 'continuation)))
843 (process-put proc 'continuation nil)
844 (if continuation (ignore-errors (funcall continuation)))))
846 (defun* server-process-filter (proc string)
847 "Process a request from the server to edit some files.
848 PROC is the server process. STRING consists of a sequence of
849 commands prefixed by a dash. Some commands have arguments;
850 these are &-quoted and need to be decoded by `server-unquote-arg'.
851 The filter parses and executes these commands.
853 To illustrate the protocol, here is an example command that
854 emacsclient sends to create a new X frame (note that the whole
855 sequence is sent on a single line):
857 -env HOME=/home/lorentey
858 -env DISPLAY=:0.0
859 ... lots of other -env commands
860 -display :0.0
861 -window-system
863 The following commands are accepted by the server:
865 `-auth AUTH-STRING'
866 Authenticate the client using the secret authentication string
867 AUTH-STRING.
869 `-env NAME=VALUE'
870 An environment variable on the client side.
872 `-dir DIRNAME'
873 The current working directory of the client process.
875 `-current-frame'
876 Forbid the creation of new frames.
878 `-frame-parameters ALIST'
879 Set the parameters of the created frame.
881 `-nowait'
882 Request that the next frame created should not be
883 associated with this client.
885 `-display DISPLAY'
886 Set the display name to open X frames on.
888 `-position LINE[:COLUMN]'
889 Go to the given line and column number
890 in the next file opened.
892 `-file FILENAME'
893 Load the given file in the current frame.
895 `-eval EXPR'
896 Evaluate EXPR as a Lisp expression and return the
897 result in -print commands.
899 `-window-system'
900 Open a new X frame.
902 `-tty DEVICENAME TYPE'
903 Open a new tty frame at the client.
905 `-suspend'
906 Suspend this tty frame. The client sends this string in
907 response to SIGTSTP and SIGTTOU. The server must cease all I/O
908 on this tty until it gets a -resume command.
910 `-resume'
911 Resume this tty frame. The client sends this string when it
912 gets the SIGCONT signal and it is the foreground process on its
913 controlling tty.
915 `-ignore COMMENT'
916 Do nothing, but put the comment in the server log.
917 Useful for debugging.
920 The following commands are accepted by the client:
922 `-emacs-pid PID'
923 Describes the process id of the Emacs process;
924 used to forward window change signals to it.
926 `-window-system-unsupported'
927 Signals that the server does not support creating X frames;
928 the client must try again with a tty frame.
930 `-print STRING'
931 Print STRING on stdout. Used to send values
932 returned by -eval.
934 `-print-nonl STRING'
935 Print STRING on stdout. Used to continue a
936 preceding -print command that would be too big to send
937 in a single message.
939 `-error DESCRIPTION'
940 Signal an error and delete process PROC.
942 `-suspend'
943 Suspend this terminal, i.e., stop the client process.
944 Sent when the user presses C-z."
945 (server-log (concat "Received " string) proc)
946 ;; First things first: let's check the authentication
947 (unless (process-get proc :authenticated)
948 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
949 (equal (match-string 1 string) (process-get proc :auth-key)))
950 (progn
951 (setq string (substring string (match-end 0)))
952 (process-put proc :authenticated t)
953 (server-log "Authentication successful" proc))
954 (server-log "Authentication failed" proc)
955 (server-send-string
956 proc (concat "-error " (server-quote-arg "Authentication failed")))
957 ;; Before calling `delete-process', give emacsclient time to
958 ;; receive the error string and shut down on its own.
959 (sit-for 1)
960 (delete-process proc)
961 ;; We return immediately
962 (return-from server-process-filter)))
963 (let ((prev (process-get proc 'previous-string)))
964 (when prev
965 (setq string (concat prev string))
966 (process-put proc 'previous-string nil)))
967 (condition-case err
968 (progn
969 (server-add-client proc)
970 ;; Send our pid
971 (server-send-string proc (concat "-emacs-pid "
972 (number-to-string (emacs-pid)) "\n"))
973 (if (not (string-match "\n" string))
974 ;; Save for later any partial line that remains.
975 (when (> (length string) 0)
976 (process-put proc 'previous-string string))
978 ;; In earlier versions of server.el (where we used an `emacsserver'
979 ;; process), there could be multiple lines. Nowadays this is not
980 ;; supported any more.
981 (assert (eq (match-end 0) (length string)))
982 (let ((request (substring string 0 (match-beginning 0)))
983 (coding-system (and (default-value 'enable-multibyte-characters)
984 (or file-name-coding-system
985 default-file-name-coding-system)))
986 nowait ; t if emacsclient does not want to wait for us.
987 frame ; Frame opened for the client (if any).
988 display ; Open frame on this display.
989 parent-id ; Window ID for XEmbed
990 dontkill ; t if client should not be killed.
991 commands
993 use-current-frame
994 frame-parameters ;parameters for newly created frame
995 tty-name ; nil, `window-system', or the tty name.
996 tty-type ; string.
997 files
998 filepos
999 args-left)
1000 ;; Remove this line from STRING.
1001 (setq string (substring string (match-end 0)))
1002 (setq args-left
1003 (mapcar 'server-unquote-arg (split-string request " " t)))
1004 (while args-left
1005 (pcase (pop args-left)
1006 ;; -version CLIENT-VERSION: obsolete at birth.
1007 (`"-version" (pop args-left))
1009 ;; -nowait: Emacsclient won't wait for a result.
1010 (`"-nowait" (setq nowait t))
1012 ;; -current-frame: Don't create frames.
1013 (`"-current-frame" (setq use-current-frame t))
1015 ;; -frame-parameters: Set frame parameters
1016 (`"-frame-parameters"
1017 (let ((alist (pop args-left)))
1018 (if coding-system
1019 (setq alist (decode-coding-string alist coding-system)))
1020 (setq frame-parameters (car (read-from-string alist)))))
1022 ;; -display DISPLAY:
1023 ;; Open X frames on the given display instead of the default.
1024 (`"-display"
1025 (setq display (pop args-left))
1026 (if (zerop (length display)) (setq display nil)))
1028 ;; -parent-id ID:
1029 ;; Open X frame within window ID, via XEmbed.
1030 (`"-parent-id"
1031 (setq parent-id (pop args-left))
1032 (if (zerop (length parent-id)) (setq parent-id nil)))
1034 ;; -window-system: Open a new X frame.
1035 (`"-window-system"
1036 (setq dontkill t)
1037 (setq tty-name 'window-system))
1039 ;; -resume: Resume a suspended tty frame.
1040 (`"-resume"
1041 (let ((terminal (process-get proc 'terminal)))
1042 (setq dontkill t)
1043 (push (lambda ()
1044 (when (eq (terminal-live-p terminal) t)
1045 (resume-tty terminal)))
1046 commands)))
1048 ;; -suspend: Suspend the client's frame. (In case we
1049 ;; get out of sync, and a C-z sends a SIGTSTP to
1050 ;; emacsclient.)
1051 (`"-suspend"
1052 (let ((terminal (process-get proc 'terminal)))
1053 (setq dontkill t)
1054 (push (lambda ()
1055 (when (eq (terminal-live-p terminal) t)
1056 (suspend-tty terminal)))
1057 commands)))
1059 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1060 ;; (The given comment appears in the server log.)
1061 (`"-ignore"
1062 (setq dontkill t)
1063 (pop args-left))
1065 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1066 (`"-tty"
1067 (setq tty-name (pop args-left)
1068 tty-type (pop args-left)
1069 dontkill (or dontkill
1070 (not use-current-frame)))
1071 ;; On Windows, emacsclient always asks for a tty frame.
1072 ;; If running a GUI server, force the frame type to GUI.
1073 (when (eq window-system 'w32)
1074 (push "-window-system" args-left)))
1076 ;; -position LINE[:COLUMN]: Set point to the given
1077 ;; position in the next file.
1078 (`"-position"
1079 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1080 (car args-left)))
1081 (error "Invalid -position command in client args"))
1082 (let ((arg (pop args-left)))
1083 (setq filepos
1084 (cons (string-to-number (match-string 1 arg))
1085 (string-to-number (or (match-string 2 arg)
1086 ""))))))
1088 ;; -file FILENAME: Load the given file.
1089 (`"-file"
1090 (let ((file (pop args-left)))
1091 (if coding-system
1092 (setq file (decode-coding-string file coding-system)))
1093 (setq file (expand-file-name file dir))
1094 (push (cons file filepos) files)
1095 (server-log (format "New file: %s %s"
1096 file (or filepos "")) proc))
1097 (setq filepos nil))
1099 ;; -eval EXPR: Evaluate a Lisp expression.
1100 (`"-eval"
1101 (if use-current-frame
1102 (setq use-current-frame 'always))
1103 (let ((expr (pop args-left)))
1104 (if coding-system
1105 (setq expr (decode-coding-string expr coding-system)))
1106 (push (lambda () (server-eval-and-print expr proc))
1107 commands)
1108 (setq filepos nil)))
1110 ;; -env NAME=VALUE: An environment variable.
1111 (`"-env"
1112 (let ((var (pop args-left)))
1113 ;; XXX Variables should be encoded as in getenv/setenv.
1114 (process-put proc 'env
1115 (cons var (process-get proc 'env)))))
1117 ;; -dir DIRNAME: The cwd of the emacsclient process.
1118 (`"-dir"
1119 (setq dir (pop args-left))
1120 (if coding-system
1121 (setq dir (decode-coding-string dir coding-system)))
1122 (setq dir (command-line-normalize-file-name dir)))
1124 ;; Unknown command.
1125 (arg (error "Unknown command: %s" arg))))
1127 (setq frame
1128 (cond
1129 ((and use-current-frame
1130 (or (eq use-current-frame 'always)
1131 ;; We can't use the Emacs daemon's
1132 ;; terminal frame.
1133 (not (and (daemonp)
1134 (null (cdr (frame-list)))
1135 (eq (selected-frame)
1136 terminal-frame)))))
1137 (setq tty-name nil tty-type nil)
1138 (if display (server-select-display display)))
1139 ((eq tty-name 'window-system)
1140 (server-create-window-system-frame display nowait proc
1141 parent-id
1142 frame-parameters))
1143 ;; When resuming on a tty, tty-name is nil.
1144 (tty-name
1145 (server-create-tty-frame tty-name tty-type proc))))
1147 (process-put
1148 proc 'continuation
1149 (lambda ()
1150 (with-current-buffer (get-buffer-create server-buffer)
1151 ;; Use the same cwd as the emacsclient, if possible, so
1152 ;; relative file names work correctly, even in `eval'.
1153 (let ((default-directory
1154 (if (and dir (file-directory-p dir))
1155 dir default-directory)))
1156 (server-execute proc files nowait commands
1157 dontkill frame tty-name)))))
1159 (when (or frame files)
1160 (server-goto-toplevel proc))
1162 (server-execute-continuation proc))))
1163 ;; condition-case
1164 (error (server-return-error proc err))))
1166 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1167 ;; This is run from timers and process-filters, i.e. "asynchronously".
1168 ;; But w.r.t the user, this is not really asynchronous since the timer
1169 ;; is run after 0s and the process-filter is run in response to the
1170 ;; user running `emacsclient'. So it is OK to override the
1171 ;; inhibit-quit flag, which is good since `commands' (as well as
1172 ;; find-file-noselect via the major-mode) can run arbitrary code,
1173 ;; including code that needs to wait.
1174 (with-local-quit
1175 (condition-case err
1176 (let* ((buffers
1177 (when files
1178 (server-visit-files files proc nowait))))
1180 (mapc 'funcall (nreverse commands))
1182 ;; Delete the client if necessary.
1183 (cond
1184 (nowait
1185 ;; Client requested nowait; return immediately.
1186 (server-log "Close nowait client" proc)
1187 (server-delete-client proc))
1188 ((and (not dontkill) (null buffers))
1189 ;; This client is empty; get rid of it immediately.
1190 (server-log "Close empty client" proc)
1191 (server-delete-client proc)))
1192 (cond
1193 ((or isearch-mode (minibufferp))
1194 nil)
1195 ((and frame (null buffers))
1196 (message "%s" (substitute-command-keys
1197 "When done with this frame, type \\[delete-frame]")))
1198 ((not (null buffers))
1199 (server-switch-buffer (car buffers) nil (cdr (car files)))
1200 (run-hooks 'server-switch-hook)
1201 (unless nowait
1202 (message "%s" (substitute-command-keys
1203 "When done with a buffer, type \\[server-edit]")))))
1204 (when (and frame (null tty-name))
1205 (server-unselect-display frame)))
1206 ((quit error)
1207 (when (eq (car err) 'quit)
1208 (message "Quit emacsclient request"))
1209 (server-return-error proc err)))))
1211 (defun server-return-error (proc err)
1212 (ignore-errors
1213 (server-send-string
1214 proc (concat "-error " (server-quote-arg
1215 (error-message-string err))))
1216 (server-log (error-message-string err) proc)
1217 ;; Before calling `delete-process', give emacsclient time to
1218 ;; receive the error string and shut down on its own.
1219 (sit-for 5)
1220 (delete-process proc)))
1222 (defun server-goto-line-column (line-col)
1223 "Move point to the position indicated in LINE-COL.
1224 LINE-COL should be a pair (LINE . COL)."
1225 (when line-col
1226 (goto-char (point-min))
1227 (forward-line (1- (car line-col)))
1228 (let ((column-number (cdr line-col)))
1229 (when (> column-number 0)
1230 (move-to-column (1- column-number))))))
1232 (defun server-visit-files (files proc &optional nowait)
1233 "Find FILES and return a list of buffers created.
1234 FILES is an alist whose elements are (FILENAME . FILEPOS)
1235 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1236 PROC is the client that requested this operation.
1237 NOWAIT non-nil means this client is not waiting for the results,
1238 so don't mark these buffers specially, just visit them normally."
1239 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1240 (let ((last-nonmenu-event t) client-record)
1241 ;; Restore the current buffer afterward, but not using save-excursion,
1242 ;; because we don't want to save point in this buffer
1243 ;; if it happens to be one of those specified by the server.
1244 (save-current-buffer
1245 (dolist (file files)
1246 ;; If there is an existing buffer modified or the file is
1247 ;; modified, revert it. If there is an existing buffer with
1248 ;; deleted file, offer to write it.
1249 (let* ((minibuffer-auto-raise (or server-raise-frame
1250 minibuffer-auto-raise))
1251 (filen (car file))
1252 (obuf (get-file-buffer filen)))
1253 (add-to-history 'file-name-history filen)
1254 (if (null obuf)
1255 (progn
1256 (run-hooks 'pre-command-hook)
1257 (set-buffer (find-file-noselect filen)))
1258 (set-buffer obuf)
1259 ;; separately for each file, in sync with post-command hooks,
1260 ;; with the new buffer current:
1261 (run-hooks 'pre-command-hook)
1262 (cond ((file-exists-p filen)
1263 (when (not (verify-visited-file-modtime obuf))
1264 (revert-buffer t nil)))
1266 (when (y-or-n-p
1267 (concat "File no longer exists: " filen
1268 ", write buffer to file? "))
1269 (write-file filen))))
1270 (unless server-buffer-clients
1271 (setq server-existing-buffer t)))
1272 (server-goto-line-column (cdr file))
1273 (run-hooks 'server-visit-hook)
1274 ;; hooks may be specific to current buffer:
1275 (run-hooks 'post-command-hook))
1276 (unless nowait
1277 ;; When the buffer is killed, inform the clients.
1278 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1279 (push proc server-buffer-clients))
1280 (push (current-buffer) client-record)))
1281 (unless nowait
1282 (process-put proc 'buffers
1283 (nconc (process-get proc 'buffers) client-record)))
1284 client-record))
1286 (defvar server-kill-buffer-running nil
1287 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1289 (defun server-buffer-done (buffer &optional for-killing)
1290 "Mark BUFFER as \"done\" for its client(s).
1291 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1292 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1293 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1294 a temp file).
1295 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1296 (let ((next-buffer nil)
1297 (killed nil))
1298 (dolist (proc server-clients)
1299 (let ((buffers (process-get proc 'buffers)))
1300 (or next-buffer
1301 (setq next-buffer (nth 1 (memq buffer buffers))))
1302 (when buffers ; Ignore bufferless clients.
1303 (setq buffers (delq buffer buffers))
1304 ;; Delete all dead buffers from PROC.
1305 (dolist (b buffers)
1306 (and (bufferp b)
1307 (not (buffer-live-p b))
1308 (setq buffers (delq b buffers))))
1309 (process-put proc 'buffers buffers)
1310 ;; If client now has no pending buffers,
1311 ;; tell it that it is done, and forget it entirely.
1312 (unless buffers
1313 (server-log "Close" proc)
1314 (if for-killing
1315 ;; `server-delete-client' might delete the client's
1316 ;; frames, which might change the current buffer. We
1317 ;; don't want that (bug#640).
1318 (save-current-buffer
1319 (server-delete-client proc))
1320 (server-delete-client proc))))))
1321 (when (and (bufferp buffer) (buffer-name buffer))
1322 ;; We may or may not kill this buffer;
1323 ;; if we do, do not call server-buffer-done recursively
1324 ;; from kill-buffer-hook.
1325 (let ((server-kill-buffer-running t))
1326 (with-current-buffer buffer
1327 (setq server-buffer-clients nil)
1328 (run-hooks 'server-done-hook))
1329 ;; Notice whether server-done-hook killed the buffer.
1330 (if (null (buffer-name buffer))
1331 (setq killed t)
1332 ;; Don't bother killing or burying the buffer
1333 ;; when we are called from kill-buffer.
1334 (unless for-killing
1335 (when (and (not killed)
1336 server-kill-new-buffers
1337 (with-current-buffer buffer
1338 (not server-existing-buffer)))
1339 (setq killed t)
1340 (bury-buffer buffer)
1341 ;; Prevent kill-buffer from prompting (Bug#3696).
1342 (with-current-buffer buffer
1343 (set-buffer-modified-p nil))
1344 (kill-buffer buffer))
1345 (unless killed
1346 (if (server-temp-file-p buffer)
1347 (progn
1348 (with-current-buffer buffer
1349 (set-buffer-modified-p nil))
1350 (kill-buffer buffer)
1351 (setq killed t))
1352 (bury-buffer buffer)))))))
1353 (list next-buffer killed)))
1355 (defun server-temp-file-p (&optional buffer)
1356 "Return non-nil if BUFFER contains a file considered temporary.
1357 These are files whose names suggest they are repeatedly
1358 reused to pass information to another program.
1360 The variable `server-temp-file-regexp' controls which filenames
1361 are considered temporary."
1362 (and (buffer-file-name buffer)
1363 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1365 (defun server-done ()
1366 "Offer to save current buffer, mark it as \"done\" for clients.
1367 This kills or buries the buffer, then returns a list
1368 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1369 as a suggestion for what to select next, or nil.
1370 KILLED is t if we killed BUFFER, which happens if it was created
1371 specifically for the clients and did not exist before their request for it."
1372 (when server-buffer-clients
1373 (if (server-temp-file-p)
1374 ;; For a temp file, save, and do make a non-numeric backup
1375 ;; (unless make-backup-files is nil).
1376 (let ((version-control nil)
1377 (buffer-backed-up nil))
1378 (save-buffer))
1379 (when (and (buffer-modified-p)
1380 buffer-file-name
1381 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1382 (save-buffer)))
1383 (server-buffer-done (current-buffer))))
1385 ;; Ask before killing a server buffer.
1386 ;; It was suggested to release its client instead,
1387 ;; but I think that is dangerous--the client would proceed
1388 ;; using whatever is on disk in that file. -- rms.
1389 (defun server-kill-buffer-query-function ()
1390 "Ask before killing a server buffer."
1391 (or (not server-buffer-clients)
1392 (let ((res t))
1393 (dolist (proc server-buffer-clients)
1394 (when (and (memq proc server-clients)
1395 (eq (process-status proc) 'open))
1396 (setq res nil)))
1397 res)
1398 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1399 (buffer-name (current-buffer))))))
1401 (defun server-kill-emacs-query-function ()
1402 "Ask before exiting Emacs if it has live clients."
1403 (or (not server-clients)
1404 (let (live-client)
1405 (dolist (proc server-clients)
1406 (when (memq t (mapcar 'buffer-live-p (process-get
1407 proc 'buffers)))
1408 (setq live-client t)))
1409 live-client)
1410 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1412 (defun server-kill-buffer ()
1413 "Remove the current buffer from its clients' buffer list.
1414 Designed to be added to `kill-buffer-hook'."
1415 ;; Prevent infinite recursion if user has made server-done-hook
1416 ;; call kill-buffer.
1417 (or server-kill-buffer-running
1418 (and server-buffer-clients
1419 (let ((server-kill-buffer-running t))
1420 (when server-process
1421 (server-buffer-done (current-buffer) t))))))
1423 (defun server-edit (&optional arg)
1424 "Switch to next server editing buffer; say \"Done\" for current buffer.
1425 If a server buffer is current, it is marked \"done\" and optionally saved.
1426 The buffer is also killed if it did not exist before the clients asked for it.
1427 When all of a client's buffers are marked as \"done\", the client is notified.
1429 Temporary files such as MH <draft> files are always saved and backed up,
1430 no questions asked. (The variable `make-backup-files', if nil, still
1431 inhibits a backup; you can set it locally in a particular buffer to
1432 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1433 which filenames are considered temporary.
1435 If invoked with a prefix argument, or if there is no server process running,
1436 starts server process and that is all. Invoked by \\[server-edit]."
1437 (interactive "P")
1438 (cond
1439 ((or arg
1440 (not server-process)
1441 (memq (process-status server-process) '(signal exit)))
1442 (server-mode 1))
1443 (server-clients (apply 'server-switch-buffer (server-done)))
1444 (t (message "No server editing buffers exist"))))
1446 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1447 "Switch to another buffer, preferably one that has a client.
1448 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1450 KILLED-ONE is t in a recursive call if we have already killed one
1451 temp-file server buffer. This means we should avoid the final
1452 \"switch to some other buffer\" since we've already effectively
1453 done that.
1455 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1456 visit NEXT-BUFFER in an existing window. If non-nil, it should
1457 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1458 (if (null next-buffer)
1459 (progn
1460 (let ((rest server-clients))
1461 (while (and rest (not next-buffer))
1462 (let ((proc (car rest)))
1463 ;; Only look at frameless clients, or those in the selected
1464 ;; frame.
1465 (when (or (not (process-get proc 'frame))
1466 (eq (process-get proc 'frame) (selected-frame)))
1467 (setq next-buffer (car (process-get proc 'buffers))))
1468 (setq rest (cdr rest)))))
1469 (and next-buffer (server-switch-buffer next-buffer killed-one))
1470 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1471 ;; (switch-to-buffer (other-buffer))
1472 (message "No server buffers remain to edit")))
1473 (if (not (buffer-live-p next-buffer))
1474 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1475 ;; and try the next surviving server buffer.
1476 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1477 ;; OK, we know next-buffer is live, let's display and select it.
1478 (if (functionp server-window)
1479 (funcall server-window next-buffer)
1480 (let ((win (get-buffer-window next-buffer 0)))
1481 (if (and win (not server-window))
1482 ;; The buffer is already displayed: just reuse the
1483 ;; window. If FILEPOS is non-nil, use it to replace the
1484 ;; window's own value of point.
1485 (progn
1486 (select-window win)
1487 (set-buffer next-buffer)
1488 (when filepos
1489 (server-goto-line-column filepos)))
1490 ;; Otherwise, let's find an appropriate window.
1491 (cond ((window-live-p server-window)
1492 (select-window server-window))
1493 ((framep server-window)
1494 (unless (frame-live-p server-window)
1495 (setq server-window (make-frame)))
1496 (select-window (frame-selected-window server-window))))
1497 (when (window-minibuffer-p (selected-window))
1498 (select-window (next-window nil 'nomini 0)))
1499 ;; Move to a non-dedicated window, if we have one.
1500 (when (window-dedicated-p (selected-window))
1501 (select-window
1502 (get-window-with-predicate
1503 (lambda (w)
1504 (and (not (window-dedicated-p w))
1505 (equal (frame-terminal (window-frame w))
1506 (frame-terminal (selected-frame)))))
1507 'nomini 'visible (selected-window))))
1508 (condition-case nil
1509 (switch-to-buffer next-buffer)
1510 ;; After all the above, we might still have ended up with
1511 ;; a minibuffer/dedicated-window (if there's no other).
1512 (error (pop-to-buffer next-buffer)))))))
1513 (when server-raise-frame
1514 (select-frame-set-input-focus (window-frame (selected-window))))))
1516 ;;;###autoload
1517 (defun server-save-buffers-kill-terminal (arg)
1518 ;; Called from save-buffers-kill-terminal in files.el.
1519 "Offer to save each buffer, then kill the current client.
1520 With ARG non-nil, silently save all file-visiting buffers, then kill.
1522 If emacsclient was started with a list of filenames to edit, then
1523 only these files will be asked to be saved."
1524 (let ((proc (frame-parameter (selected-frame) 'client)))
1525 (cond ((eq proc 'nowait)
1526 ;; Nowait frames have no client buffer list.
1527 (if (cdr (frame-list))
1528 (progn (save-some-buffers arg)
1529 (delete-frame))
1530 ;; If we're the last frame standing, kill Emacs.
1531 (save-buffers-kill-emacs arg)))
1532 ((processp proc)
1533 (let ((buffers (process-get proc 'buffers)))
1534 ;; If client is bufferless, emulate a normal Emacs exit
1535 ;; and offer to save all buffers. Otherwise, offer to
1536 ;; save only the buffers belonging to the client.
1537 (save-some-buffers
1538 arg (if buffers
1539 (lambda () (memq (current-buffer) buffers))
1541 (server-delete-client proc)))
1542 (t (error "Invalid client frame")))))
1544 (define-key ctl-x-map "#" 'server-edit)
1546 (defun server-unload-function ()
1547 "Unload the server library."
1548 (server-mode -1)
1549 (substitute-key-definition 'server-edit nil ctl-x-map)
1550 (save-current-buffer
1551 (dolist (buffer (buffer-list))
1552 (set-buffer buffer)
1553 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1554 ;; continue standard unloading
1555 nil)
1557 (defun server-eval-at (server form)
1558 "Contact the Emacs server named SERVER and evaluate FORM there.
1559 Returns the result of the evaluation, or signals an error if it
1560 cannot contact the specified server. For example:
1561 \(server-eval-at \"server\" '(emacs-pid))
1562 returns the process ID of the Emacs instance running \"server\"."
1563 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
1564 (server-file (expand-file-name server server-dir))
1565 (coding-system-for-read 'binary)
1566 (coding-system-for-write 'binary)
1567 address port secret process)
1568 (unless (file-exists-p server-file)
1569 (error "No such server: %s" server))
1570 (with-temp-buffer
1571 (when server-use-tcp
1572 (let ((coding-system-for-read 'no-conversion))
1573 (insert-file-contents server-file)
1574 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1575 (error "Invalid auth file"))
1576 (setq address (match-string 1)
1577 port (string-to-number (match-string 2)))
1578 (forward-line 1)
1579 (setq secret (buffer-substring (point) (line-end-position)))
1580 (erase-buffer)))
1581 (unless (setq process (make-network-process
1582 :name "eval-at"
1583 :buffer (current-buffer)
1584 :host address
1585 :service (if server-use-tcp port server-file)
1586 :family (if server-use-tcp 'ipv4 'local)
1587 :noquery t))
1588 (error "Unable to contact the server"))
1589 (if server-use-tcp
1590 (process-send-string process (concat "-auth " secret "\n")))
1591 (process-send-string process
1592 (concat "-eval "
1593 (server-quote-arg (format "%S" form))
1594 "\n"))
1595 (while (memq (process-status process) '(open run))
1596 (accept-process-output process 0 10))
1597 (goto-char (point-min))
1598 ;; If the result is nil, there's nothing in the buffer. If the
1599 ;; result is non-nil, it's after "-print ".
1600 (let ((answer ""))
1601 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t)
1602 (setq answer
1603 (concat answer
1604 (buffer-substring (point)
1605 (progn (skip-chars-forward "^\n")
1606 (point))))))
1607 (if (not (equal answer ""))
1608 (read (decode-coding-string (server-unquote-arg answer)
1609 'emacs-internal)))))))
1612 (provide 'server)
1614 ;;; server.el ends here