1 ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
3 ;; Copyright (C) 1986-1987, 1992, 1994-2016 Free Software Foundation,
6 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
7 ;; Maintainer: emacs-devel@gnu.org
10 ;; Changes by peck@sun.com and by rms.
11 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
30 ;; This Lisp code is run in Emacs when it is to operate as
31 ;; a server for other processes.
33 ;; Load this library and do M-x server-edit to enable Emacs as a server.
34 ;; Emacs opens up a socket for communication with clients. If there are no
35 ;; client buffers to edit, server-edit acts like (switch-to-buffer
38 ;; When some other program runs "the editor" to edit a file,
39 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
40 ;; This program transmits the file names to Emacs through
41 ;; the server subprocess, and Emacs visits them and lets you edit them.
43 ;; Note that any number of clients may dispatch files to Emacs to be edited.
45 ;; When you finish editing a Server buffer, again call server-edit
46 ;; to mark that buffer as done for the client and switch to the next
47 ;; Server buffer. When all the buffers for a client have been edited
48 ;; and exited with server-edit, the client "editor" will return
49 ;; to the program that invoked it.
51 ;; Your editing commands and Emacs's display output go to and from
52 ;; the terminal in the usual way. Thus, server operation is possible
53 ;; only when Emacs can talk to the terminal at the time you invoke
54 ;; the client. This is possible in four cases:
56 ;; 1. On a window system, where Emacs runs in one window and the
57 ;; program that wants to use "the editor" runs in another.
59 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
60 ;; program that wants to use "the editor" runs on another.
62 ;; 3. When the program that wants to use "the editor" is running
63 ;; as a subprocess of Emacs.
65 ;; 4. On a system with job control, when Emacs is suspended, the program
66 ;; that wants to use "the editor" will stop and display
67 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
68 ;; brought into the foreground for editing. When done editing, Emacs is
69 ;; suspended again, and the client program is brought into the foreground.
71 ;; The buffer local variable "server-buffer-clients" lists
72 ;; the clients who are waiting for this buffer to be edited.
73 ;; The global variable "server-clients" lists all the waiting clients,
74 ;; and which files are yet to be edited for each.
78 ;; - handle command-line-args-left.
79 ;; - move most of the args processing and decision making from emacsclient.c
81 ;; - fix up handling of the client's environment (place it in the terminal?).
85 (eval-when-compile (require 'cl-lib
))
88 "Emacs running as a server process."
91 (defcustom server-use-tcp nil
92 "If non-nil, use TCP sockets instead of local sockets."
93 :set
#'(lambda (sym val
)
94 (unless (featurep 'make-network-process
'(:family local
))
96 (unless load-in-progress
97 (message "Local sockets unsupported, using TCP sockets")))
98 (set-default sym val
))
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.
107 DO NOT give this a non-nil value unless you know what you are doing!
108 On unsecured networks, accepting remote connections is very dangerous,
109 because server-client communication (including session authentication)
113 (string :tag
"Name or IP address")
114 (const :tag
"Local" nil
))
117 (put 'server-host
'risky-local-variable t
)
119 (defcustom server-port nil
120 "The port number that the server process should listen on.
121 This variable only takes effect when the Emacs server is using
122 TCP instead of local sockets. A nil value means to use a random
126 (string :tag
"Port number")
127 (const :tag
"Random" nil
))
130 (put 'server-port
'risky-local-variable t
)
132 (defcustom server-auth-dir
(locate-user-emacs-file "server/")
133 "Directory for server authentication files.
134 We only use this if `server-use-tcp' is non-nil.
135 Otherwise we use `server-socket-dir'.
137 NOTE: On FAT32 filesystems, directories are not secure;
138 files can be read and modified by any user or process.
139 It is strongly suggested to set `server-auth-dir' to a
140 directory residing in a NTFS partition instead."
145 (put 'server-auth-dir
'risky-local-variable t
)
147 (defcustom server-auth-key nil
148 "Server authentication key.
149 This is only used if `server-use-tcp' is non-nil.
151 Normally, the authentication key is randomly generated when the
152 server starts. It is recommended to leave it that way. Using a
153 long-lived shared key will decrease security (especially since
154 the key is transmitted as plain-text).
156 In some situations however, it can be difficult to share randomly
157 generated passwords with remote hosts (e.g., no shared directory),
158 so you can set the key with this variable and then copy the
159 server file to the remote host (with possible changes to IP
160 address and/or port if that applies).
162 Note that the usual security risks of using the server over
163 remote TCP, arising from the fact that client-server
164 communications are unencrypted, still apply.
166 The key must consist of 64 ASCII printable characters except for
167 space (this means characters from ! to ~; or from code 33 to
168 126). You can use \\[server-generate-key] to get a random key."
171 (const :tag
"Random" nil
)
172 (string :tag
"Password"))
175 (defcustom server-raise-frame t
176 "If non-nil, raise frame when switching to a buffer."
181 (defcustom server-visit-hook nil
182 "Hook run when visiting a file for the Emacs server."
186 (defcustom server-switch-hook nil
187 "Hook run when switching to a buffer for the Emacs server."
191 (defcustom server-done-hook nil
192 "Hook run when done editing a buffer for the Emacs server."
196 (defvar server-process nil
197 "The current server process.")
199 (defvar server-clients nil
200 "List of current server clients.
201 Each element is a process.")
203 (defvar server-buffer-clients nil
204 "List of client processes requesting editing of current buffer.")
205 (make-variable-buffer-local 'server-buffer-clients
)
206 ;; Changing major modes should not erase this local.
207 (put 'server-buffer-clients
'permanent-local t
)
209 (defcustom server-window nil
210 "Specification of the window to use for selecting Emacs server buffers.
211 If nil, use the selected window.
212 If it is a function, it should take one argument (a buffer) and
213 display and select it. A common value is `pop-to-buffer'.
214 If it is a window, use that.
215 If it is a frame, use the frame's selected window.
217 It is not meaningful to set this to a specific frame or window with Custom.
218 Only programs can do so."
221 :type
'(choice (const :tag
"Use selected window"
222 :match
(lambda (widget value
)
223 (not (functionp value
)))
225 (function-item :tag
"Display in new frame" switch-to-buffer-other-frame
)
226 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
227 (function :tag
"Other function")))
229 (defcustom server-temp-file-regexp
"^/tmp/Re\\|/draft$"
230 "Regexp matching names of temporary files.
231 These are deleted and reused after each edit by the programs that
232 invoke the Emacs server."
236 (defcustom server-kill-new-buffers t
237 "Whether to kill buffers when done with them.
238 If non-nil, kill a buffer unless it already existed before editing
239 it with the Emacs server. If nil, kill only buffers as specified by
240 `server-temp-file-regexp'.
241 Please note that only buffers that still have a client are killed,
242 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
248 ;; FIXME? This is not a minor mode; what's the point of this? (See bug#20201)
249 (or (assq 'server-buffer-clients minor-mode-alist
)
250 (push '(server-buffer-clients " Server") minor-mode-alist
))
252 (defvar server-existing-buffer nil
253 "Non-nil means the buffer existed before the server was asked to visit it.
254 This means that the server should not kill the buffer when you say you
255 are done with it in the server.")
256 (make-variable-buffer-local 'server-existing-buffer
)
259 (defcustom server-name
"server"
260 "The name of the Emacs server, if this Emacs process creates one.
261 The command `server-start' makes use of this. It should not be
262 changed while a server is running."
267 ;; We do not use `temporary-file-directory' here, because emacsclient
268 ;; does not read the init file.
269 (defvar server-socket-dir
270 (and (featurep 'make-network-process
'(:family local
))
271 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
272 "The directory in which to place the server socket.
273 If local sockets are not supported, this is nil.")
275 (defun server-clients-with (property value
)
276 "Return a list of clients with PROPERTY set to VALUE."
278 (dolist (proc server-clients
)
279 (when (equal value
(process-get proc property
))
283 (defun server-add-client (proc)
284 "Create a client for process PROC, if it doesn't already have one.
285 New clients have no properties."
286 (add-to-list 'server-clients proc
))
288 (defmacro server-with-environment
(env vars
&rest body
)
289 "Evaluate BODY with environment variables VARS set to those in ENV.
290 The environment variables are then restored to their previous values.
292 VARS should be a list of strings.
293 ENV should be in the same format as `process-environment'."
295 (let ((var (make-symbol "var"))
296 (value (make-symbol "value")))
297 `(let ((process-environment process-environment
))
299 (let ((,value
(getenv-internal ,var
,env
)))
300 (push (if (stringp ,value
)
301 (concat ,var
"=" ,value
)
303 process-environment
)))
306 (defun server-delete-client (proc &optional noframe
)
307 "Delete PROC, including its buffers, terminals and frames.
308 If NOFRAME is non-nil, let the frames live.
309 Updates `server-clients'."
310 (server-log (concat "server-delete-client" (if noframe
" noframe")) proc
)
311 ;; Force a new lookup of client (prevents infinite recursion).
312 (when (memq proc server-clients
)
313 (let ((buffers (process-get proc
'buffers
)))
315 ;; Kill the client's buffers.
316 (dolist (buf buffers
)
317 (when (buffer-live-p buf
)
318 (with-current-buffer buf
319 ;; Kill the buffer if necessary.
320 (when (and (equal server-buffer-clients
322 (or (and server-kill-new-buffers
323 (not server-existing-buffer
))
324 (server-temp-file-p))
325 (not (buffer-modified-p)))
328 (progn (setq server-buffer-clients nil
)
329 (kill-buffer (current-buffer))
332 ;; Restore clients if user pressed C-g in `kill-buffer'.
333 (setq server-buffer-clients
(list proc
)))))))))
335 ;; Delete the client's frames.
337 (dolist (frame (frame-list))
338 (when (and (frame-live-p frame
)
339 (equal proc
(frame-parameter frame
'client
)))
340 ;; Prevent `server-handle-delete-frame' from calling us
342 (set-frame-parameter frame
'client nil
)
343 (delete-frame frame
))))
345 (setq server-clients
(delq proc server-clients
))
347 ;; Delete the client's tty, except on Windows (both GUI and console),
348 ;; where there's only one terminal and does not make sense to delete it.
349 (unless (eq system-type
'windows-nt
)
350 (let ((terminal (process-get proc
'terminal
)))
351 ;; Only delete the terminal if it is non-nil.
352 (when (and terminal
(eq (terminal-live-p terminal
) t
))
353 (delete-terminal terminal
))))
355 ;; Delete the client's process.
356 (if (eq (process-status proc
) 'open
)
357 (delete-process proc
))
359 (server-log "Deleted" proc
))))
361 (defvar server-log-time-function
'current-time-string
362 "Function to generate timestamps for `server-buffer'.")
364 (defconst server-buffer
" *server*"
365 "Buffer used internally by Emacs's server.
366 One use is to log the I/O for debugging purposes (see option `server-log'),
367 the other is to provide a current buffer in which the process filter can
368 safely let-bind buffer-local variables like `default-directory'.")
370 (defvar server-log nil
371 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
373 (defun server-log (string &optional client
)
374 "If option `server-log' is non-nil, log STRING to `server-buffer'.
375 If CLIENT is non-nil, add a description of it to the logged message."
377 (with-current-buffer (get-buffer-create server-buffer
)
378 (goto-char (point-max))
379 (insert (funcall server-log-time-function
)
382 ((listp client
) (format " %s: " (car client
)))
383 (t (format " %s: " client
)))
385 (or (bolp) (newline)))))
387 (defun server-sentinel (proc msg
)
388 "The process sentinel for Emacs server connections."
389 ;; If this is a new client process, set the query-on-exit flag to nil
390 ;; for this process (it isn't inherited from the server process).
391 (when (and (eq (process-status proc
) 'open
)
392 (process-query-on-exit-flag proc
))
393 (set-process-query-on-exit-flag proc nil
))
394 ;; Delete the associated connection file, if applicable.
395 ;; Although there's no 100% guarantee that the file is owned by the
396 ;; running Emacs instance, server-start uses server-running-p to check
397 ;; for possible servers before doing anything, so it *should* be ours.
398 (and (process-contact proc
:server
)
399 (eq (process-status proc
) 'closed
)
401 (delete-file (process-get proc
:server-file
))))
402 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
403 (server-delete-client proc
))
405 (defun server--on-display-p (frame display
)
406 (and (equal (frame-parameter frame
'display
) display
)
407 ;; Note: TTY frames still get a `display' parameter set to the value of
408 ;; $DISPLAY. This is useful when running from that tty frame
409 ;; sub-processes that want to connect to the X server, but that means we
410 ;; have to be careful here not to be tricked into thinking those frames
412 (not (eq (framep frame
) t
))))
414 (defun server-select-display (display)
415 ;; If the current frame is on `display' we're all set.
416 ;; Similarly if we are unable to open frames on other displays, there's
417 ;; nothing more we can do.
418 (unless (or (not (fboundp 'make-frame-on-display
))
419 (server--on-display-p (selected-frame) display
))
420 ;; Otherwise, look for an existing frame there and select it.
421 (dolist (frame (frame-list))
422 (when (server--on-display-p frame display
)
423 (select-frame frame
)))
424 ;; If there's no frame on that display yet, create and select one.
425 (unless (server--on-display-p (selected-frame) display
)
426 (let* ((buffer (generate-new-buffer " *server-dummy*"))
427 (frame (make-frame-on-display
429 ;; Make it display (and remember) some dummy buffer, so
430 ;; we can detect later if the frame is in use or not.
431 `((server-dummy-buffer .
,buffer
)
432 ;; This frame may be deleted later (see
433 ;; server-unselect-display) so we want it to be as
434 ;; unobtrusive as possible.
435 (visibility . nil
)))))
437 (set-window-buffer (selected-window) buffer
)
440 (defun server-unselect-display (frame)
441 (when (frame-live-p frame
)
442 ;; If the temporary frame is in use (displays something real), make it
443 ;; visible. If not (which can happen if the user's customizations call
444 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
445 ;; the last real frame is deleted.
447 ;; Rewritten to avoid inadvertently killing the current buffer after
448 ;; `delete-frame' removed FRAME (Bug#10729).
449 (let ((buffer (frame-parameter frame
'server-dummy-buffer
)))
450 (if (and (one-window-p 'nomini frame
)
451 (eq (window-buffer (frame-first-window frame
)) buffer
))
452 ;; The temp frame still only shows one buffer, and that is the
453 ;; internal temp buffer.
455 (set-frame-parameter frame
'visibility t
)
456 (set-frame-parameter frame
'server-dummy-buffer nil
))
457 (when (buffer-live-p buffer
)
458 (kill-buffer buffer
)))))
460 (defun server-handle-delete-frame (frame)
461 "Delete the client connection when the emacsclient frame is deleted.
462 \(To be used from `delete-frame-functions'.)"
463 (let ((proc (frame-parameter frame
'client
)))
464 (when (and (frame-live-p frame
)
466 ;; See if this is the last frame for this client.
467 (>= 1 (let ((frame-num 0))
468 (dolist (f (frame-list))
469 (when (eq proc
(frame-parameter f
'client
))
470 (setq frame-num
(1+ frame-num
))))
472 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
473 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
475 (defun server-handle-suspend-tty (terminal)
476 "Notify the client process that its tty device is suspended."
477 (dolist (proc (server-clients-with 'terminal terminal
))
478 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
)
481 (server-send-string proc
"-suspend \n")
482 (file-error ;The pipe/socket was closed.
483 (ignore-errors (server-delete-client proc
))))))
485 (defun server-unquote-arg (arg)
486 "Remove &-quotation from ARG.
487 See `server-quote-arg' and `server-process-filter'."
488 (replace-regexp-in-string
497 (defun server-quote-arg (arg)
498 "In ARG, insert a & before each &, each space, each newline, and -.
499 Change spaces to underscores, too, so that the return value never
502 See `server-unquote-arg' and `server-process-filter'."
503 (replace-regexp-in-string
504 "[-&\n ]" (lambda (s)
512 (defun server-send-string (proc string
)
513 "A wrapper around `process-send-string' for logging."
514 (server-log (concat "Sent " string
) proc
)
515 (process-send-string proc string
))
517 (defun server-ensure-safe-dir (dir)
518 "Make sure DIR is a directory with no race-condition issues.
519 Creates the directory if necessary and makes sure:
520 - there's no symlink involved
522 - it's not readable/writable by anybody else."
523 (setq dir
(directory-file-name dir
))
524 (let ((attrs (file-attributes dir
'integer
)))
526 (cl-letf (((default-file-modes) ?
\700)) (make-directory dir t
))
527 (setq attrs
(file-attributes dir
'integer
)))
529 ;; Check that it's safe for use.
530 (let* ((uid (nth 2 attrs
))
531 (w32 (eq system-type
'windows-nt
))
533 ((not (eq t
(car attrs
))) nil
) ; is a dir?
534 ((and w32
(zerop uid
)) ; on FAT32?
538 Using `%s' to store Emacs-server authentication files.
539 Directories on FAT32 filesystems are NOT secure against tampering.
540 See variable `server-auth-dir' for details."
541 (file-name-as-directory dir
))
544 ((and (/= uid
(user-uid)) ; is the dir ours?
546 ;; Files created on Windows by Administrator
547 ;; (RID=500) have the Administrators (RID=544)
548 ;; group recorded as the owner.
549 (/= uid
544) (/= (user-uid) 500)))
552 (t ; else, check permissions
553 (zerop (logand ?
\077 (file-modes dir
)))))))
555 (error "The directory `%s' is unsafe" dir
)))))
557 (defun server-generate-key ()
558 "Generate and return a random authentication key.
559 The key is a 64-byte string of random chars in the range `!'..`~'.
560 If called interactively, also inserts it into current buffer."
564 collect
(+ 33 (random 94)) into auth
565 finally return
(concat auth
))))
566 (if (called-interactively-p 'interactive
)
570 (defun server-get-auth-key ()
571 "Return server's authentication key.
573 If `server-auth-key' is nil, just call `server-generate-key'.
574 Otherwise, if `server-auth-key' is a valid key, return it.
575 If the key is not valid, signal an error."
577 (if (string-match-p "^[!-~]\\{64\\}$" server-auth-key
)
579 (error "The key `%s' is invalid" server-auth-key
))
580 (server-generate-key)))
583 (defun server-start (&optional leave-dead inhibit-prompt
)
584 "Allow this Emacs process to be a server for client processes.
585 This starts a server communications subprocess through which client
586 \"editors\" can send your editing commands to this Emacs job.
587 To use the server, set up the program `emacsclient' in the Emacs
588 distribution as your standard \"editor\".
590 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
591 kill any existing server communications subprocess.
593 If a server is already running, restart it. If clients are
594 running, ask the user for confirmation first, unless optional
595 argument INHIBIT-PROMPT is non-nil.
597 To force-start a server, do \\[server-force-delete] and then
600 (when (or (not server-clients
)
601 ;; Ask the user before deleting existing clients---except
602 ;; when we can't get user input, which may happen when
603 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
606 (null (cdr (frame-list)))
607 (eq (selected-frame) terminal-frame
))
611 "The current server still has clients; delete them? "))))
612 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
613 (server-file (expand-file-name server-name server-dir
)))
616 (ignore-errors (delete-process server-process
)))
617 ;; Delete the socket files made by previous server invocations.
618 (if (not (eq t
(server-running-p server-name
)))
619 ;; Remove any leftover socket or authentication file
621 (let (delete-by-moving-to-trash)
622 (delete-file server-file
)))
623 (setq server-mode nil
) ;; already set by the minor mode code
626 (concat "Unable to start the Emacs server.\n"
627 (format "There is an existing Emacs server, named %S.\n"
629 (substitute-command-keys
630 "To start the server in this Emacs process, stop the existing
631 server or call `\\[server-force-delete]' to forcibly disconnect it."))
634 ;; If this Emacs already had a server, clear out associated status.
635 (while server-clients
636 (server-delete-client (car server-clients
)))
637 ;; Now any previous server is properly stopped.
640 (unless (eq t leave-dead
) (server-log (message "Server stopped")))
641 (setq server-process nil
))
642 ;; Make sure there is a safe directory in which to place the socket.
643 (server-ensure-safe-dir server-dir
)
645 (server-log (message "Restarting server")))
646 (cl-letf (((default-file-modes) ?
\700))
647 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
648 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
649 (add-hook 'kill-emacs-query-functions
650 'server-kill-emacs-query-function
)
651 (add-hook 'kill-emacs-hook
'server-force-stop
) ;Cleanup upon exit.
653 (apply #'make-network-process
657 :sentinel
#'server-sentinel
658 :filter
#'server-process-filter
659 :use-external-socket t
660 ;; We must receive file names without being decoded.
661 ;; Those are decoded by server-process-filter according
662 ;; to file-name-coding-system. Also don't get
663 ;; confused by CRs since we don't quote them.
664 :coding
'raw-text-unix
665 ;; The other args depend on the kind of socket used.
667 (list :family
'ipv4
;; We're not ready for IPv6 yet
668 :service
(or server-port t
)
669 :host
(or server-host
'local
)
670 :plist
'(:authenticated nil
))
673 :plist
'(:authenticated t
)))))
674 (unless server-process
(error "Could not start server process"))
675 (process-put server-process
:server-file server-file
)
677 (let ((auth-key (server-get-auth-key)))
678 (process-put server-process
:auth-key auth-key
)
679 (with-temp-file server-file
680 (set-buffer-multibyte nil
)
681 (setq buffer-file-coding-system
'no-conversion
)
682 (insert (format-network-address
683 (process-contact server-process
:local
))
684 " " (number-to-string (emacs-pid)) ; Kept for compatibility
685 "\n" auth-key
)))))))))
687 (defun server-force-stop ()
688 "Kill all connections to the current server.
689 This function is meant to be called from `kill-emacs-hook'."
693 (defun server-force-delete (&optional name
)
694 "Unconditionally delete connection file for server NAME.
695 If server is running, it is first stopped.
696 NAME defaults to `server-name'. With argument, ask for NAME."
698 (list (if current-prefix-arg
699 (read-string "Server name: " nil nil server-name
))))
700 (when server-mode
(with-temp-message nil
(server-mode -
1)))
701 (let ((file (expand-file-name (or name server-name
)
704 server-socket-dir
))))
706 (let (delete-by-moving-to-trash)
708 (message "Connection file %S deleted" file
))
710 (message "No connection file %S" file
)))))
712 (defun server-running-p (&optional name
)
713 "Test whether server NAME is running.
716 nil the server is definitely not running.
717 t the server seems to be running.
718 something else we cannot determine whether it's running without using
719 commands which may have to wait for a long time."
720 (unless name
(setq name server-name
))
724 (insert-file-contents-literally (expand-file-name name server-auth-dir
))
725 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
728 (string-to-number (match-string 1))))
732 (make-network-process
733 :name
"server-client-test" :family
'local
:server nil
:noquery t
734 :service
(expand-file-name name server-socket-dir
)))
739 (define-minor-mode server-mode
741 With a prefix argument ARG, enable Server mode if ARG is
742 positive, and disable it otherwise. If called from Lisp, enable
743 Server mode if ARG is omitted or nil.
745 Server mode runs a process that accepts commands from the
746 `emacsclient' program. See Info node `Emacs server' and
747 `server-start' for details."
751 ;; Fixme: Should this check for an existing server socket and do
752 ;; nothing if there is one (for multiple Emacs sessions)?
753 (server-start (not server-mode
)))
755 (defun server-eval-and-print (expr proc
)
756 "Eval EXPR and send the result back to client PROC."
757 ;; While we're running asynchronously (from a process filter), it is likely
758 ;; that the emacsclient command was run in response to a user
759 ;; action, so the user probably knows that Emacs is processing this
760 ;; emacsclient request, so if we get a C-g it's likely that the user
761 ;; intended it to interrupt us rather than interrupt whatever Emacs
762 ;; was doing before it started handling the process filter.
763 ;; Hence `with-local-quit' (bug#6585).
764 (let ((v (with-local-quit (eval (car (read-from-string expr
))))))
767 (let ((standard-output (current-buffer)))
769 (let ((text (buffer-substring-no-properties
770 (point-min) (point-max))))
771 (server-reply-print (server-quote-arg text
) proc
)))))))
773 (defconst server-msg-size
1024
774 "Maximum size of a message sent to a client.")
776 (defun server-reply-print (qtext proc
)
777 "Send a `-print QTEXT' command to client PROC.
778 QTEXT must be already quoted.
779 This handles splitting the command if it would be bigger than
781 (let ((prefix "-print ")
783 (while (> (+ (length qtext
) (length prefix
) 1) server-msg-size
)
784 ;; We have to split the string
785 (setq part
(substring qtext
0 (- server-msg-size
(length prefix
) 1)))
786 ;; Don't split in the middle of a quote sequence
787 (if (string-match "\\(^\\|[^&]\\)\\(&&\\)+$" part
)
788 ;; There is an uneven number of & at the end
789 (setq part
(substring part
0 -
1)))
790 (setq qtext
(substring qtext
(length part
)))
791 (server-send-string proc
(concat prefix part
"\n"))
792 (setq prefix
"-print-nonl "))
793 (server-send-string proc
(concat prefix qtext
"\n"))))
795 (defun server-create-tty-frame (tty type proc
)
797 (error "Invalid terminal device"))
799 (error "Invalid terminal type"))
800 (add-to-list 'frame-inherited-parameters
'client
)
802 (server-with-environment
803 (process-get proc
'env
)
804 '("LANG" "LC_CTYPE" "LC_ALL"
805 ;; For tgetent(3); list according to ncurses(3).
806 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
807 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
808 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
809 "TERMINFO_DIRS" "TERMPATH"
811 "COLORFGBG" "COLORTERM")
812 (make-frame `((window-system . nil
)
815 ;; Ignore nowait here; we always need to
816 ;; clean up opened ttys when the client dies.
818 ;; This is a leftover from an earlier
819 ;; attempt at making it possible for process
820 ;; run in the server process to use the
821 ;; environment of the client process.
822 ;; It has no effect now and to make it work
823 ;; we'd need to decide how to make
824 ;; process-environment interact with client
825 ;; envvars, and then to change the
826 ;; C functions `child_setup' and
827 ;; `getenv_internal' accordingly.
828 (environment .
,(process-get proc
'env
)))))))
830 ;; ttys don't use the `display' parameter, but callproc.c does to set
831 ;; the DISPLAY environment on subprocesses.
832 (set-frame-parameter frame
'display
833 (getenv-internal "DISPLAY" (process-get proc
'env
)))
835 (process-put proc
'frame frame
)
836 (process-put proc
'terminal
(frame-terminal frame
))
839 (defun server-create-window-system-frame (display nowait proc parent-id
840 &optional parameters
)
841 (let* ((display (or display
842 (frame-parameter nil
'display
)
843 (error "Please specify display.")))
844 (w (or (cdr (assq 'window-system parameters
))
845 (window-system-for-display display
))))
847 ;; Special case for ns. This is because DISPLAY may not be set at all
848 ;; which in the ns case isn't an error. The variable display then becomes
849 ;; the fully qualified hostname, which make-frame-on-display below
850 ;; does not understand and throws an error.
851 ;; It may also be a valid X display, but if Emacs is compiled for ns, it
852 ;; can not make X frames.
853 (if (featurep 'ns-win
)
854 (setq w
'ns display
"ns")
855 ;; FIXME! Not sure what this was for, and not sure how it should work
856 ;; in the cl-defmethod new world!
857 ;;(unless (assq w window-system-initialization-alist)
862 ;; Flag frame as client-created, but use a dummy client.
863 ;; This will prevent the frame from being deleted when
864 ;; emacsclient quits while also preventing
865 ;; `server-save-buffers-kill-terminal' from unexpectedly
866 ;; killing emacs on that frame.
867 (let* ((params `((client .
,(if nowait
'nowait proc
))
868 ;; This is a leftover, see above.
869 (environment .
,(process-get proc
'env
))
873 (push (cons 'parent-id
(string-to-number parent-id
)) params
))
874 (add-to-list 'frame-inherited-parameters
'client
)
875 (setq frame
(make-frame-on-display display params
))
876 (server-log (format "%s created" frame
) proc
)
878 (process-put proc
'frame frame
)
879 (process-put proc
'terminal
(frame-terminal frame
))
883 (server-log "Window system unsupported" proc
)
884 (server-send-string proc
"-window-system-unsupported \n")
887 (defun server-goto-toplevel (proc)
889 ;; If we're running isearch, we must abort it to allow Emacs to
890 ;; display the buffer and switch to it.
891 (dolist (buffer (buffer-list))
892 (with-current-buffer buffer
893 (when (bound-and-true-p isearch-mode
)
895 ;; Signaled by isearch-cancel.
896 (quit (message nil
)))
897 (when (> (recursion-depth) 0)
898 ;; We're inside a minibuffer already, so if the emacs-client is trying
899 ;; to open a frame on a new display, we might end up with an unusable
900 ;; frame because input from that display will be blocked (until exiting
901 ;; the minibuffer). Better exit this minibuffer right away.
902 ;; Similarly with recursive-edits such as the splash screen.
903 (run-with-timer 0 nil
(lambda () (server-execute-continuation proc
)))
906 ;; We use various special properties on process objects:
907 ;; - `env' stores the info about the environment of the emacsclient process.
908 ;; - `continuation' is a no-arg function that we need to execute. It contains
909 ;; commands we wanted to execute in some earlier invocation of the process
910 ;; filter but that we somehow were unable to process at that time
911 ;; (e.g. because we first need to throw to the toplevel).
913 (defun server-execute-continuation (proc)
914 (let ((continuation (process-get proc
'continuation
)))
915 (process-put proc
'continuation nil
)
916 (if continuation
(ignore-errors (funcall continuation
)))))
918 (cl-defun server-process-filter (proc string
)
919 "Process a request from the server to edit some files.
920 PROC is the server process. STRING consists of a sequence of
921 commands prefixed by a dash. Some commands have arguments;
922 these are &-quoted and need to be decoded by `server-unquote-arg'.
923 The filter parses and executes these commands.
925 To illustrate the protocol, here is an example command that
926 emacsclient sends to create a new X frame (note that the whole
927 sequence is sent on a single line):
929 -env HOME=/home/lorentey
931 ... lots of other -env commands
935 The following commands are accepted by the server:
938 Authenticate the client using the secret authentication string
942 An environment variable on the client side.
945 The current working directory of the client process.
948 Forbid the creation of new frames.
950 `-frame-parameters ALIST'
951 Set the parameters of the created frame.
954 Request that the next frame created should not be
955 associated with this client.
958 Set the display name to open X frames on.
960 `-position LINE[:COLUMN]'
961 Go to the given line and column number
962 in the next file opened.
965 Load the given file in the current frame.
968 Evaluate EXPR as a Lisp expression and return the
969 result in -print commands.
974 `-tty DEVICENAME TYPE'
975 Open a new tty frame at the client.
978 Suspend this tty frame. The client sends this string in
979 response to SIGTSTP and SIGTTOU. The server must cease all I/O
980 on this tty until it gets a -resume command.
983 Resume this tty frame. The client sends this string when it
984 gets the SIGCONT signal and it is the foreground process on its
988 Do nothing, but put the comment in the server log.
989 Useful for debugging.
992 The following commands are accepted by the client:
995 Describes the process id of the Emacs process;
996 used to forward window change signals to it.
998 `-window-system-unsupported'
999 Signals that the server does not support creating X frames;
1000 the client must try again with a tty frame.
1003 Print STRING on stdout. Used to send values
1006 `-print-nonl STRING'
1007 Print STRING on stdout. Used to continue a
1008 preceding -print command that would be too big to send
1009 in a single message.
1011 `-error DESCRIPTION'
1012 Signal an error and delete process PROC.
1015 Suspend this terminal, i.e., stop the client process.
1016 Sent when the user presses C-z."
1017 (server-log (concat "Received " string
) proc
)
1018 ;; First things first: let's check the authentication
1019 (unless (process-get proc
:authenticated
)
1020 (if (and (string-match "-auth \\([!-~]+\\)\n?" string
)
1021 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
1023 (setq string
(substring string
(match-end 0)))
1024 (process-put proc
:authenticated t
)
1025 (server-log "Authentication successful" proc
))
1026 (server-log "Authentication failed" proc
)
1028 proc
(concat "-error " (server-quote-arg "Authentication failed")))
1029 ;; Before calling `delete-process', give emacsclient time to
1030 ;; receive the error string and shut down on its own.
1032 (delete-process proc
)
1033 ;; We return immediately.
1034 (cl-return-from server-process-filter
)))
1035 (let ((prev (process-get proc
'previous-string
)))
1037 (setq string
(concat prev string
))
1038 (process-put proc
'previous-string nil
)))
1041 (server-add-client proc
)
1043 (server-send-string proc
(concat "-emacs-pid "
1044 (number-to-string (emacs-pid)) "\n"))
1045 (if (not (string-match "\n" string
))
1046 ;; Save for later any partial line that remains.
1047 (when (> (length string
) 0)
1048 (process-put proc
'previous-string string
))
1050 ;; In earlier versions of server.el (where we used an `emacsserver'
1051 ;; process), there could be multiple lines. Nowadays this is not
1052 ;; supported any more.
1053 (cl-assert (eq (match-end 0) (length string
)))
1054 (let ((request (substring string
0 (match-beginning 0)))
1055 (coding-system (and (default-value 'enable-multibyte-characters
)
1056 (or file-name-coding-system
1057 default-file-name-coding-system
)))
1058 nowait
; t if emacsclient does not want to wait for us.
1059 frame
; Frame opened for the client (if any).
1060 display
; Open frame on this display.
1061 parent-id
; Window ID for XEmbed
1062 dontkill
; t if client should not be killed.
1066 frame-parameters
;parameters for newly created frame
1067 tty-name
; nil, `window-system', or the tty name.
1072 ;; Remove this line from STRING.
1073 (setq string
(substring string
(match-end 0)))
1075 (mapcar 'server-unquote-arg
(split-string request
" " t
)))
1077 (pcase (pop args-left
)
1078 ;; -version CLIENT-VERSION: obsolete at birth.
1079 (`"-version" (pop args-left
))
1081 ;; -nowait: Emacsclient won't wait for a result.
1082 (`"-nowait" (setq nowait t
))
1084 ;; -current-frame: Don't create frames.
1085 (`"-current-frame" (setq use-current-frame t
))
1087 ;; -frame-parameters: Set frame parameters
1088 (`"-frame-parameters"
1089 (let ((alist (pop args-left
)))
1091 (setq alist
(decode-coding-string alist coding-system
)))
1092 (setq frame-parameters
(car (read-from-string alist
)))))
1094 ;; -display DISPLAY:
1095 ;; Open X frames on the given display instead of the default.
1097 (setq display
(pop args-left
))
1098 (if (zerop (length display
)) (setq display nil
)))
1101 ;; Open X frame within window ID, via XEmbed.
1103 (setq parent-id
(pop args-left
))
1104 (if (zerop (length parent-id
)) (setq parent-id nil
)))
1106 ;; -window-system: Open a new X frame.
1108 (if (fboundp 'x-create-frame
)
1110 tty-name
'window-system
)))
1112 ;; -resume: Resume a suspended tty frame.
1114 (let ((terminal (process-get proc
'terminal
)))
1117 (when (eq (terminal-live-p terminal
) t
)
1118 (resume-tty terminal
)))
1121 ;; -suspend: Suspend the client's frame. (In case we
1122 ;; get out of sync, and a C-z sends a SIGTSTP to
1125 (let ((terminal (process-get proc
'terminal
)))
1128 (when (eq (terminal-live-p terminal
) t
)
1129 (suspend-tty terminal
)))
1132 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1133 ;; (The given comment appears in the server log.)
1138 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1139 ;; (But if we see -window-system later, use that.)
1141 (setq tty-name
(pop args-left
)
1142 tty-type
(pop args-left
)
1143 dontkill
(or dontkill
1144 (not use-current-frame
)))
1145 ;; On Windows, emacsclient always asks for a tty
1146 ;; frame. If running a GUI server, force the frame
1147 ;; type to GUI. (Cygwin is perfectly happy with
1148 ;; multi-tty support, so don't override the user's
1149 ;; choice there.) In daemon mode on Windows, we can't
1150 ;; make tty frames, so force the frame type to GUI
1152 (when (and (eq system-type
'windows-nt
)
1154 (eq window-system
'w32
)))
1155 (push "-window-system" args-left
)))
1157 ;; -position LINE[:COLUMN]: Set point to the given
1158 ;; position in the next file.
1160 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1162 (error "Invalid -position command in client args"))
1163 (let ((arg (pop args-left
)))
1165 (cons (string-to-number (match-string 1 arg
))
1166 (string-to-number (or (match-string 2 arg
)
1169 ;; -file FILENAME: Load the given file.
1171 (let ((file (pop args-left
)))
1173 (setq file
(decode-coding-string file coding-system
)))
1174 ;; Allow Cygwin's emacsclient to be used as a file
1175 ;; handler on MS-Windows, in which case FILENAME
1176 ;; might start with a drive letter.
1177 (when (and (fboundp 'cygwin-convert-file-name-from-windows
)
1178 (string-match "\\`[A-Za-z]:" file
))
1179 (setq file
(cygwin-convert-file-name-from-windows file
)))
1180 (setq file
(expand-file-name file dir
))
1181 (push (cons file filepos
) files
)
1182 (server-log (format "New file: %s %s"
1183 file
(or filepos
""))
1187 ;; -eval EXPR: Evaluate a Lisp expression.
1189 (if use-current-frame
1190 (setq use-current-frame
'always
))
1191 (let ((expr (pop args-left
)))
1193 (setq expr
(decode-coding-string expr coding-system
)))
1194 (push (lambda () (server-eval-and-print expr proc
))
1196 (setq filepos nil
)))
1198 ;; -env NAME=VALUE: An environment variable.
1200 (let ((var (pop args-left
)))
1201 ;; XXX Variables should be encoded as in getenv/setenv.
1202 (process-put proc
'env
1203 (cons var
(process-get proc
'env
)))))
1205 ;; -dir DIRNAME: The cwd of the emacsclient process.
1207 (setq dir
(pop args-left
))
1209 (setq dir
(decode-coding-string dir coding-system
)))
1210 (setq dir
(command-line-normalize-file-name dir
))
1211 (process-put proc
'server-client-directory dir
))
1214 (arg (error "Unknown command: %s" arg
))))
1216 ;; If both -no-wait and -tty are given with file or sexp
1217 ;; arguments, use an existing frame.
1219 (not (eq tty-name
'window-system
))
1221 (setq use-current-frame t
))
1225 ((and use-current-frame
1226 (or (eq use-current-frame
'always
)
1227 ;; We can't use the Emacs daemon's
1230 (null (cdr (frame-list)))
1231 (eq (selected-frame)
1233 (setq tty-name nil tty-type nil
)
1234 (if display
(server-select-display display
)))
1235 ((or (and (eq system-type
'windows-nt
)
1237 (setq display
"w32"))
1238 (eq tty-name
'window-system
))
1239 (server-create-window-system-frame display nowait proc
1242 ;; When resuming on a tty, tty-name is nil.
1244 (server-create-tty-frame tty-name tty-type proc
))))
1249 (with-current-buffer (get-buffer-create server-buffer
)
1250 ;; Use the same cwd as the emacsclient, if possible, so
1251 ;; relative file names work correctly, even in `eval'.
1252 (let ((default-directory
1253 (if (and dir
(file-directory-p dir
))
1254 dir default-directory
)))
1255 (server-execute proc files nowait commands
1256 dontkill frame tty-name
)))))
1258 (when (or frame files
)
1259 (server-goto-toplevel proc
))
1261 (server-execute-continuation proc
))))
1263 (error (server-return-error proc err
))))
1265 (defun server-execute (proc files nowait commands dontkill frame tty-name
)
1266 ;; This is run from timers and process-filters, i.e. "asynchronously".
1267 ;; But w.r.t the user, this is not really asynchronous since the timer
1268 ;; is run after 0s and the process-filter is run in response to the
1269 ;; user running `emacsclient'. So it is OK to override the
1270 ;; inhibit-quit flag, which is good since `commands' (as well as
1271 ;; find-file-noselect via the major-mode) can run arbitrary code,
1272 ;; including code that needs to wait.
1275 (let ((buffers (server-visit-files files proc nowait
)))
1276 (mapc 'funcall
(nreverse commands
))
1278 ;; If we were told only to open a new client, obey
1279 ;; `initial-buffer-choice' if it specifies a file
1281 (unless (or files commands
)
1283 (cond ((stringp initial-buffer-choice
)
1284 (find-file-noselect initial-buffer-choice
))
1285 ((functionp initial-buffer-choice
)
1286 (funcall initial-buffer-choice
)))))
1288 (if (buffer-live-p buf
) buf
(get-buffer-create "*scratch*"))
1291 ;; Delete the client if necessary.
1294 ;; Client requested nowait; return immediately.
1295 (server-log "Close nowait client" proc
)
1296 (server-delete-client proc
))
1297 ((and (not dontkill
) (null buffers
))
1298 ;; This client is empty; get rid of it immediately.
1299 (server-log "Close empty client" proc
)
1300 (server-delete-client proc
)))
1302 ((or isearch-mode
(minibufferp))
1304 ((and frame
(null buffers
))
1305 (message "%s" (substitute-command-keys
1306 "When done with this frame, type \\[delete-frame]")))
1307 ((not (null buffers
))
1308 (server-switch-buffer (car buffers
) nil
(cdr (car files
)))
1309 (run-hooks 'server-switch-hook
)
1311 (message "%s" (substitute-command-keys
1312 "When done with a buffer, type \\[server-edit]")))))
1313 (when (and frame
(null tty-name
))
1314 (server-unselect-display frame
)))
1316 (when (eq (car err
) 'quit
)
1317 (message "Quit emacsclient request"))
1318 (server-return-error proc err
)))))
1320 (defun server-return-error (proc err
)
1323 proc
(concat "-error " (server-quote-arg
1324 (error-message-string err
))))
1325 (server-log (error-message-string err
) proc
)
1326 ;; Before calling `delete-process', give emacsclient time to
1327 ;; receive the error string and shut down on its own.
1329 (delete-process proc
)))
1331 (defun server-goto-line-column (line-col)
1332 "Move point to the position indicated in LINE-COL.
1333 LINE-COL should be a pair (LINE . COL)."
1335 (goto-char (point-min))
1336 (forward-line (1- (car line-col
)))
1337 (let ((column-number (cdr line-col
)))
1338 (when (> column-number
0)
1339 (move-to-column (1- column-number
))))))
1341 (defun server-visit-files (files proc
&optional nowait
)
1342 "Find FILES and return a list of buffers created.
1343 FILES is an alist whose elements are (FILENAME . FILEPOS)
1344 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1345 PROC is the client that requested this operation.
1346 NOWAIT non-nil means this client is not waiting for the results,
1347 so don't mark these buffers specially, just visit them normally."
1348 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1349 (let ((last-nonmenu-event t
) client-record
)
1350 ;; Restore the current buffer afterward, but not using save-excursion,
1351 ;; because we don't want to save point in this buffer
1352 ;; if it happens to be one of those specified by the server.
1353 (save-current-buffer
1354 (dolist (file files
)
1355 ;; If there is an existing buffer modified or the file is
1356 ;; modified, revert it. If there is an existing buffer with
1357 ;; deleted file, offer to write it.
1358 (let* ((minibuffer-auto-raise (or server-raise-frame
1359 minibuffer-auto-raise
))
1361 (obuf (get-file-buffer filen
)))
1362 (add-to-history 'file-name-history filen
)
1365 (run-hooks 'pre-command-hook
)
1366 (set-buffer (find-file-noselect filen
)))
1368 ;; separately for each file, in sync with post-command hooks,
1369 ;; with the new buffer current:
1370 (run-hooks 'pre-command-hook
)
1371 (cond ((file-exists-p filen
)
1372 (when (not (verify-visited-file-modtime obuf
))
1373 (revert-buffer t nil
)))
1376 (concat "File no longer exists: " filen
1377 ", write buffer to file? "))
1378 (write-file filen
))))
1379 (unless server-buffer-clients
1380 (setq server-existing-buffer t
)))
1381 (server-goto-line-column (cdr file
))
1382 (run-hooks 'server-visit-hook
)
1383 ;; hooks may be specific to current buffer:
1384 (run-hooks 'post-command-hook
))
1386 ;; When the buffer is killed, inform the clients.
1387 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1388 (push proc server-buffer-clients
))
1389 (push (current-buffer) client-record
)))
1391 (process-put proc
'buffers
1392 (nconc (process-get proc
'buffers
) client-record
)))
1395 (defvar server-kill-buffer-running nil
1396 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1398 (defun server-buffer-done (buffer &optional for-killing
)
1399 "Mark BUFFER as \"done\" for its client(s).
1400 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1401 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1402 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1404 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1405 (let ((next-buffer nil
)
1407 (dolist (proc server-clients
)
1408 (let ((buffers (process-get proc
'buffers
)))
1410 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1411 (when buffers
; Ignore bufferless clients.
1412 (setq buffers
(delq buffer buffers
))
1413 ;; Delete all dead buffers from PROC.
1416 (not (buffer-live-p b
))
1417 (setq buffers
(delq b buffers
))))
1418 (process-put proc
'buffers buffers
)
1419 ;; If client now has no pending buffers,
1420 ;; tell it that it is done, and forget it entirely.
1422 (server-log "Close" proc
)
1424 ;; `server-delete-client' might delete the client's
1425 ;; frames, which might change the current buffer. We
1426 ;; don't want that (bug#640).
1427 (save-current-buffer
1428 (server-delete-client proc
))
1429 (server-delete-client proc
))))))
1430 (when (and (bufferp buffer
) (buffer-name buffer
))
1431 ;; We may or may not kill this buffer;
1432 ;; if we do, do not call server-buffer-done recursively
1433 ;; from kill-buffer-hook.
1434 (let ((server-kill-buffer-running t
))
1435 (with-current-buffer buffer
1436 (setq server-buffer-clients nil
)
1437 (run-hooks 'server-done-hook
))
1438 ;; Notice whether server-done-hook killed the buffer.
1439 (if (null (buffer-name buffer
))
1441 ;; Don't bother killing or burying the buffer
1442 ;; when we are called from kill-buffer.
1444 (when (and (not killed
)
1445 server-kill-new-buffers
1446 (with-current-buffer buffer
1447 (not server-existing-buffer
)))
1449 (bury-buffer buffer
)
1450 ;; Prevent kill-buffer from prompting (Bug#3696).
1451 (with-current-buffer buffer
1452 (set-buffer-modified-p nil
))
1453 (kill-buffer buffer
))
1455 (if (server-temp-file-p buffer
)
1457 (with-current-buffer buffer
1458 (set-buffer-modified-p nil
))
1459 (kill-buffer buffer
)
1461 (bury-buffer buffer
)))))))
1462 (list next-buffer killed
)))
1464 (defun server-temp-file-p (&optional buffer
)
1465 "Return non-nil if BUFFER contains a file considered temporary.
1466 These are files whose names suggest they are repeatedly
1467 reused to pass information to another program.
1469 The variable `server-temp-file-regexp' controls which filenames
1470 are considered temporary."
1471 (and (buffer-file-name buffer
)
1472 (string-match-p server-temp-file-regexp
(buffer-file-name buffer
))))
1474 (defun server-done ()
1475 "Offer to save current buffer, mark it as \"done\" for clients.
1476 This kills or buries the buffer, then returns a list
1477 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1478 as a suggestion for what to select next, or nil.
1479 KILLED is t if we killed BUFFER, which happens if it was created
1480 specifically for the clients and did not exist before their request for it."
1481 (when server-buffer-clients
1482 (if (server-temp-file-p)
1483 ;; For a temp file, save, and do make a non-numeric backup
1484 ;; (unless make-backup-files is nil).
1485 (let ((version-control nil
)
1486 (buffer-backed-up nil
))
1488 (when (and (buffer-modified-p)
1490 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1492 (server-buffer-done (current-buffer))))
1494 (defun server-kill-emacs-query-function ()
1495 "Ask before exiting Emacs if it has live clients."
1496 (or (not (let (live-client)
1497 (dolist (proc server-clients
)
1498 (when (memq t
(mapcar 'buffer-live-p
(process-get
1500 (setq live-client t
)))
1502 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1504 (defun server-kill-buffer ()
1505 "Remove the current buffer from its clients' buffer list.
1506 Designed to be added to `kill-buffer-hook'."
1507 ;; Prevent infinite recursion if user has made server-done-hook
1508 ;; call kill-buffer.
1509 (or server-kill-buffer-running
1510 (and server-buffer-clients
1511 (let ((server-kill-buffer-running t
))
1512 (when server-process
1513 (server-buffer-done (current-buffer) t
))))))
1515 (defun server-edit (&optional arg
)
1516 "Switch to next server editing buffer; say \"Done\" for current buffer.
1517 If a server buffer is current, it is marked \"done\" and optionally saved.
1518 The buffer is also killed if it did not exist before the clients asked for it.
1519 When all of a client's buffers are marked as \"done\", the client is notified.
1521 Temporary files such as MH <draft> files are always saved and backed up,
1522 no questions asked. (The variable `make-backup-files', if nil, still
1523 inhibits a backup; you can set it locally in a particular buffer to
1524 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1525 which filenames are considered temporary.
1527 If invoked with a prefix argument, or if there is no server process running,
1528 starts server process and that is all. Invoked by \\[server-edit]."
1532 (not server-process
)
1533 (memq (process-status server-process
) '(signal exit
)))
1535 (server-clients (apply 'server-switch-buffer
(server-done)))
1536 (t (message "No server editing buffers exist"))))
1538 (defun server-switch-buffer (&optional next-buffer killed-one filepos
)
1539 "Switch to another buffer, preferably one that has a client.
1540 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1542 KILLED-ONE is t in a recursive call if we have already killed one
1543 temp-file server buffer. This means we should avoid the final
1544 \"switch to some other buffer\" since we've already effectively
1547 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1548 visit NEXT-BUFFER in an existing window. If non-nil, it should
1549 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1550 (if (null next-buffer
)
1552 (let ((rest server-clients
))
1553 (while (and rest
(not next-buffer
))
1554 (let ((proc (car rest
)))
1555 ;; Only look at frameless clients, or those in the selected
1557 (when (or (not (process-get proc
'frame
))
1558 (eq (process-get proc
'frame
) (selected-frame)))
1559 (setq next-buffer
(car (process-get proc
'buffers
))))
1560 (setq rest
(cdr rest
)))))
1561 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1562 (unless (or next-buffer killed-one
(window-dedicated-p))
1563 ;; (switch-to-buffer (other-buffer))
1564 (message "No server buffers remain to edit")))
1565 (if (not (buffer-live-p next-buffer
))
1566 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1567 ;; and try the next surviving server buffer.
1568 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1569 ;; OK, we know next-buffer is live, let's display and select it.
1570 (if (functionp server-window
)
1571 (funcall server-window next-buffer
)
1572 (let ((win (get-buffer-window next-buffer
0)))
1573 (if (and win
(not server-window
))
1574 ;; The buffer is already displayed: just reuse the
1575 ;; window. If FILEPOS is non-nil, use it to replace the
1576 ;; window's own value of point.
1579 (set-buffer next-buffer
)
1581 (server-goto-line-column filepos
)))
1582 ;; Otherwise, let's find an appropriate window.
1583 (cond ((window-live-p server-window
)
1584 (select-window server-window
))
1585 ((framep server-window
)
1586 (unless (frame-live-p server-window
)
1587 (setq server-window
(make-frame)))
1588 (select-window (frame-selected-window server-window
))))
1589 (when (window-minibuffer-p)
1590 (select-window (next-window nil
'nomini
0)))
1591 ;; Move to a non-dedicated window, if we have one.
1592 (when (window-dedicated-p)
1594 (get-window-with-predicate
1596 (and (not (window-dedicated-p w
))
1597 (equal (frame-terminal (window-frame w
))
1599 'nomini
'visible
(selected-window))))
1601 (switch-to-buffer next-buffer
)
1602 ;; After all the above, we might still have ended up with
1603 ;; a minibuffer/dedicated-window (if there's no other).
1604 (error (pop-to-buffer next-buffer
)))))))
1605 (when server-raise-frame
1606 (select-frame-set-input-focus (window-frame)))))
1609 (defun server-save-buffers-kill-terminal (arg)
1610 ;; Called from save-buffers-kill-terminal in files.el.
1611 "Offer to save each buffer, then kill the current client.
1612 With ARG non-nil, silently save all file-visiting buffers, then kill.
1614 If emacsclient was started with a list of filenames to edit, then
1615 only these files will be asked to be saved."
1616 (let ((proc (frame-parameter nil
'client
)))
1617 (cond ((eq proc
'nowait
)
1618 ;; Nowait frames have no client buffer list.
1619 (if (cdr (frame-list))
1620 (progn (save-some-buffers arg
)
1622 ;; If we're the last frame standing, kill Emacs.
1623 (save-buffers-kill-emacs arg
)))
1625 (let ((buffers (process-get proc
'buffers
)))
1626 ;; If client is bufferless, emulate a normal Emacs exit
1627 ;; and offer to save all buffers. Otherwise, offer to
1628 ;; save only the buffers belonging to the client.
1631 (lambda () (memq (current-buffer) buffers
))
1633 (server-delete-client proc
)))
1634 (t (error "Invalid client frame")))))
1636 (define-key ctl-x-map
"#" 'server-edit
)
1638 (defun server-unload-function ()
1639 "Unload the Server library."
1641 (substitute-key-definition 'server-edit nil ctl-x-map
)
1642 (save-current-buffer
1643 (dolist (buffer (buffer-list))
1645 (remove-hook 'kill-buffer-hook
'server-kill-buffer t
)))
1646 ;; continue standard unloading
1649 (defun server-eval-at (server form
)
1650 "Contact the Emacs server named SERVER and evaluate FORM there.
1651 Returns the result of the evaluation, or signals an error if it
1652 cannot contact the specified server. For example:
1653 (server-eval-at \"server\" \\='(emacs-pid))
1654 returns the process ID of the Emacs instance running \"server\"."
1655 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
1656 (server-file (expand-file-name server server-dir
))
1657 (coding-system-for-read 'binary
)
1658 (coding-system-for-write 'binary
)
1659 address port secret process
)
1660 (unless (file-exists-p server-file
)
1661 (error "No such server: %s" server
))
1663 (when server-use-tcp
1664 (let ((coding-system-for-read 'no-conversion
))
1665 (insert-file-contents server-file
)
1666 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1667 (error "Invalid auth file"))
1668 (setq address
(match-string 1)
1669 port
(string-to-number (match-string 2)))
1671 (setq secret
(buffer-substring (point) (line-end-position)))
1673 (unless (setq process
(make-network-process
1675 :buffer
(current-buffer)
1677 :service
(if server-use-tcp port server-file
)
1678 :family
(if server-use-tcp
'ipv4
'local
)
1680 (error "Unable to contact the server"))
1682 (process-send-string process
(concat "-auth " secret
"\n")))
1683 (process-send-string process
1685 (server-quote-arg (format "%S" form
))
1687 (while (memq (process-status process
) '(open run
))
1688 (accept-process-output process
0 10))
1689 (goto-char (point-min))
1690 ;; If the result is nil, there's nothing in the buffer. If the
1691 ;; result is non-nil, it's after "-print ".
1693 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t
)
1696 (buffer-substring (point)
1697 (progn (skip-chars-forward "^\n")
1699 (if (not (equal answer
""))
1700 (read (decode-coding-string (server-unquote-arg answer
)
1701 'emacs-internal
)))))))
1706 ;;; server.el ends here