1 ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
3 ;; Copyright (C) 1986-1987, 1992, 1994-2018 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 <https://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-after-make-frame-hook nil
192 "Hook run when the Emacs server creates a client frame.
193 The created frame is selected when the hook is called."
198 (defcustom server-done-hook nil
199 "Hook run when done editing a buffer for the Emacs server."
203 (defvar server-process nil
204 "The current server process.")
206 (defvar server-clients nil
207 "List of current server clients.
208 Each element is a process.")
210 (defvar server-buffer-clients nil
211 "List of client processes requesting editing of current buffer.")
212 (make-variable-buffer-local 'server-buffer-clients
)
213 ;; Changing major modes should not erase this local.
214 (put 'server-buffer-clients
'permanent-local t
)
216 (defcustom server-window nil
217 "Specification of the window to use for selecting Emacs server buffers.
218 If nil, use the selected window.
219 If it is a function, it should take one argument (a buffer) and
220 display and select it. A common value is `pop-to-buffer'.
221 If it is a window, use that.
222 If it is a frame, use the frame's selected window.
224 It is not meaningful to set this to a specific frame or window with Custom.
225 Only programs can do so."
228 :type
'(choice (const :tag
"Use selected window"
229 :match
(lambda (widget value
)
230 (not (functionp value
)))
232 (function-item :tag
"Display in new frame" switch-to-buffer-other-frame
)
233 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
234 (function :tag
"Other function")))
236 (defcustom server-temp-file-regexp
"^/tmp/Re\\|/draft$"
237 "Regexp matching names of temporary files.
238 These are deleted and reused after each edit by the programs that
239 invoke the Emacs server."
243 (defcustom server-kill-new-buffers t
244 "Whether to kill buffers when done with them.
245 If non-nil, kill a buffer unless it already existed before editing
246 it with the Emacs server. If nil, kill only buffers as specified by
247 `server-temp-file-regexp'.
248 Please note that only buffers that still have a client are killed,
249 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
255 (defvar server-existing-buffer nil
256 "Non-nil means the buffer existed before the server was asked to visit it.
257 This means that the server should not kill the buffer when you say you
258 are done with it in the server.")
259 (make-variable-buffer-local 'server-existing-buffer
)
261 (defvar server--external-socket-initialized nil
262 "When an external socket is passed into Emacs, we need to call
263 `server-start' in order to initialize the connection. This flag
264 prevents multiple initializations when an external socket has
267 (defcustom server-name
268 (if internal--daemon-sockname
269 (file-name-nondirectory internal--daemon-sockname
)
271 "The name of the Emacs server, if this Emacs process creates one.
272 The command `server-start' makes use of this. It should not be
273 changed while a server is running."
278 ;; We do not use `temporary-file-directory' here, because emacsclient
279 ;; does not read the init file.
280 (defvar server-socket-dir
281 (if internal--daemon-sockname
282 (file-name-directory internal--daemon-sockname
)
283 (and (featurep 'make-network-process
'(:family local
))
284 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid))))
285 "The directory in which to place the server socket.
286 If local sockets are not supported, this is nil.")
288 (defun server-clients-with (property value
)
289 "Return a list of clients with PROPERTY set to VALUE."
291 (dolist (proc server-clients
)
292 (when (equal value
(process-get proc property
))
296 (defun server-add-client (proc)
297 "Create a client for process PROC, if it doesn't already have one.
298 New clients have no properties."
299 (add-to-list 'server-clients proc
))
301 (defmacro server-with-environment
(env vars
&rest body
)
302 "Evaluate BODY with environment variables VARS set to those in ENV.
303 The environment variables are then restored to their previous values.
305 VARS should be a list of strings.
306 ENV should be in the same format as `process-environment'."
308 (let ((var (make-symbol "var"))
309 (value (make-symbol "value")))
310 `(let ((process-environment process-environment
))
312 (let ((,value
(getenv-internal ,var
,env
)))
313 (push (if (stringp ,value
)
314 (concat ,var
"=" ,value
)
316 process-environment
)))
319 (defun server-delete-client (proc &optional noframe
)
320 "Delete PROC, including its buffers, terminals and frames.
321 If NOFRAME is non-nil, let the frames live.
322 Updates `server-clients'."
323 (server-log (concat "server-delete-client" (if noframe
" noframe")) proc
)
324 ;; Force a new lookup of client (prevents infinite recursion).
325 (when (memq proc server-clients
)
326 (let ((buffers (process-get proc
'buffers
)))
328 ;; Kill the client's buffers.
329 (dolist (buf buffers
)
330 (when (buffer-live-p buf
)
331 (with-current-buffer buf
332 ;; Kill the buffer if necessary.
333 (when (and (equal server-buffer-clients
335 (or (and server-kill-new-buffers
336 (not server-existing-buffer
))
337 (server-temp-file-p))
338 (not (buffer-modified-p)))
341 (progn (setq server-buffer-clients nil
)
342 (kill-buffer (current-buffer))
345 ;; Restore clients if user pressed C-g in `kill-buffer'.
346 (setq server-buffer-clients
(list proc
)))))))))
348 ;; Delete the client's frames.
350 (dolist (frame (frame-list))
351 (when (and (frame-live-p frame
)
352 (equal proc
(frame-parameter frame
'client
)))
353 ;; Prevent `server-handle-delete-frame' from calling us
355 (set-frame-parameter frame
'client nil
)
356 (delete-frame frame
))))
358 (setq server-clients
(delq proc server-clients
))
360 ;; Delete the client's tty, except on Windows (both GUI and console),
361 ;; where there's only one terminal and does not make sense to delete it.
362 (unless (eq system-type
'windows-nt
)
363 (let ((terminal (process-get proc
'terminal
)))
364 ;; Only delete the terminal if it is non-nil.
365 (when (and terminal
(eq (terminal-live-p terminal
) t
))
366 (delete-terminal terminal
))))
368 ;; Delete the client's process.
369 (if (eq (process-status proc
) 'open
)
370 (delete-process proc
))
372 (server-log "Deleted" proc
))))
374 (defvar server-log-time-function
'current-time-string
375 "Function to generate timestamps for `server-buffer'.")
377 (defconst server-buffer
" *server*"
378 "Buffer used internally by Emacs's server.
379 One use is to log the I/O for debugging purposes (see option `server-log'),
380 the other is to provide a current buffer in which the process filter can
381 safely let-bind buffer-local variables like `default-directory'.")
383 (defvar server-log nil
384 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
386 (defun server-log (string &optional client
)
387 "If option `server-log' is non-nil, log STRING to `server-buffer'.
388 If CLIENT is non-nil, add a description of it to the logged message."
390 (with-current-buffer (get-buffer-create server-buffer
)
391 (goto-char (point-max))
392 (insert (funcall server-log-time-function
)
395 ((listp client
) (format " %s: " (car client
)))
396 (t (format " %s: " client
)))
398 (or (bolp) (newline)))))
400 (defun server-sentinel (proc msg
)
401 "The process sentinel for Emacs server connections."
402 ;; If this is a new client process, set the query-on-exit flag to nil
403 ;; for this process (it isn't inherited from the server process).
404 (when (and (eq (process-status proc
) 'open
)
405 (process-query-on-exit-flag proc
))
406 (set-process-query-on-exit-flag proc nil
))
407 ;; Delete the associated connection file, if applicable.
408 ;; Although there's no 100% guarantee that the file is owned by the
409 ;; running Emacs instance, server-start uses server-running-p to check
410 ;; for possible servers before doing anything, so it *should* be ours.
411 (and (process-contact proc
:server
)
412 (eq (process-status proc
) 'closed
)
414 (delete-file (process-get proc
:server-file
))))
415 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
416 (server-delete-client proc
))
418 (defun server--on-display-p (frame display
)
419 (and (equal (frame-parameter frame
'display
) display
)
420 ;; Note: TTY frames still get a `display' parameter set to the value of
421 ;; $DISPLAY. This is useful when running from that tty frame
422 ;; sub-processes that want to connect to the X server, but that means we
423 ;; have to be careful here not to be tricked into thinking those frames
425 (not (eq (framep frame
) t
))))
427 (defun server-select-display (display)
428 ;; If the current frame is on `display' we're all set.
429 ;; Similarly if we are unable to open frames on other displays, there's
430 ;; nothing more we can do.
431 (unless (or (not (fboundp 'make-frame-on-display
))
432 (server--on-display-p (selected-frame) display
))
433 ;; Otherwise, look for an existing frame there and select it.
434 (dolist (frame (frame-list))
435 (when (server--on-display-p frame display
)
436 (select-frame frame
)))
437 ;; If there's no frame on that display yet, create and select one.
438 (unless (server--on-display-p (selected-frame) display
)
439 (let* ((buffer (generate-new-buffer " *server-dummy*"))
440 (frame (make-frame-on-display
442 ;; Make it display (and remember) some dummy buffer, so
443 ;; we can detect later if the frame is in use or not.
444 `((server-dummy-buffer .
,buffer
)
445 ;; This frame may be deleted later (see
446 ;; server-unselect-display) so we want it to be as
447 ;; unobtrusive as possible.
448 (visibility . nil
)))))
450 (set-window-buffer (selected-window) buffer
)
453 (defun server-unselect-display (frame)
454 (when (frame-live-p frame
)
455 ;; If the temporary frame is in use (displays something real), make it
456 ;; visible. If not (which can happen if the user's customizations call
457 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
458 ;; the last real frame is deleted.
460 ;; Rewritten to avoid inadvertently killing the current buffer after
461 ;; `delete-frame' removed FRAME (Bug#10729).
462 (let ((buffer (frame-parameter frame
'server-dummy-buffer
)))
463 (if (and (one-window-p 'nomini frame
)
464 (eq (window-buffer (frame-first-window frame
)) buffer
))
465 ;; The temp frame still only shows one buffer, and that is the
466 ;; internal temp buffer.
468 (set-frame-parameter frame
'visibility t
)
469 (set-frame-parameter frame
'server-dummy-buffer nil
))
470 (when (buffer-live-p buffer
)
471 (kill-buffer buffer
)))))
473 (defun server-handle-delete-frame (frame)
474 "Delete the client connection when the emacsclient frame is deleted.
475 \(To be used from `delete-frame-functions'.)"
476 (let ((proc (frame-parameter frame
'client
)))
477 (when (and (frame-live-p frame
)
479 ;; See if this is the last frame for this client.
480 (>= 1 (let ((frame-num 0))
481 (dolist (f (frame-list))
482 (when (eq proc
(frame-parameter f
'client
))
483 (setq frame-num
(1+ frame-num
))))
485 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
486 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
488 (defun server-handle-suspend-tty (terminal)
489 "Notify the client process that its tty device is suspended."
490 (dolist (proc (server-clients-with 'terminal terminal
))
491 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
)
494 (server-send-string proc
"-suspend \n")
495 (file-error ;The pipe/socket was closed.
496 (ignore-errors (server-delete-client proc
))))))
498 (defun server-unquote-arg (arg)
499 "Remove &-quotation from ARG.
500 See `server-quote-arg' and `server-process-filter'."
501 (replace-regexp-in-string
510 (defun server-quote-arg (arg)
511 "In ARG, insert a & before each &, each space, each newline, and -.
512 Change spaces to underscores, too, so that the return value never
515 See `server-unquote-arg' and `server-process-filter'."
516 (replace-regexp-in-string
517 "[-&\n ]" (lambda (s)
525 (defun server-send-string (proc string
)
526 "A wrapper around `process-send-string' for logging."
527 (server-log (concat "Sent " string
) proc
)
528 (process-send-string proc string
))
530 (defun server-ensure-safe-dir (dir)
531 "Make sure DIR is a directory with no race-condition issues.
532 Creates the directory if necessary and makes sure:
533 - there's no symlink involved
535 - it's not readable/writable by anybody else."
536 (setq dir
(directory-file-name dir
))
537 (let ((attrs (file-attributes dir
'integer
)))
539 (cl-letf (((default-file-modes) ?
\700)) (make-directory dir t
))
540 (setq attrs
(file-attributes dir
'integer
)))
542 ;; Check that it's safe for use.
543 (let* ((uid (file-attribute-user-id attrs
))
544 (w32 (eq system-type
'windows-nt
))
546 ((not (eq t
(file-attribute-type attrs
)))
547 (if (null attrs
) "its attributes can't be checked"
549 (if (stringp (file-attribute-type attrs
))
551 ((and w32
(zerop uid
)) ; on FAT32?
555 Using `%s' to store Emacs-server authentication files.
556 Directories on FAT32 filesystems are NOT secure against tampering.
557 See variable `server-auth-dir' for details."
558 (file-name-as-directory dir
))
561 ((and (/= uid
(user-uid)) ; is the dir ours?
563 ;; Files created on Windows by Administrator
564 ;; (RID=500) have the Administrators (RID=544)
565 ;; group recorded as the owner.
566 (/= uid
544) (/= (user-uid) 500)))
567 (format "it is not owned by you (owner = %s (%d))"
568 (user-full-name uid
) uid
))
570 ((/= 0 (logand ?
\077 (file-modes dir
)))
571 (format "it is accessible by others (%03o)"
575 (error "`%s' is not a safe directory because %s"
576 (expand-file-name dir
) unsafe
)))))
578 (defun server-generate-key ()
579 "Generate and return a random authentication key.
580 The key is a 64-byte string of random chars in the range `!'..`~'.
581 If called interactively, also inserts it into current buffer."
585 collect
(+ 33 (random 94)) into auth
586 finally return
(concat auth
))))
587 (if (called-interactively-p 'interactive
)
591 (defun server-get-auth-key ()
592 "Return server's authentication key.
594 If `server-auth-key' is nil, just call `server-generate-key'.
595 Otherwise, if `server-auth-key' is a valid key, return it.
596 If the key is not valid, signal an error."
598 (if (string-match-p "^[!-~]\\{64\\}$" server-auth-key
)
600 (error "The key `%s' is invalid" server-auth-key
))
601 (server-generate-key)))
604 (defun server-start (&optional leave-dead inhibit-prompt
)
605 "Allow this Emacs process to be a server for client processes.
606 This starts a server communications subprocess through which client
607 \"editors\" can send your editing commands to this Emacs job.
608 To use the server, set up the program `emacsclient' in the Emacs
609 distribution as your standard \"editor\".
611 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
612 kill any existing server communications subprocess.
614 If a server is already running, restart it. If clients are
615 running, ask the user for confirmation first, unless optional
616 argument INHIBIT-PROMPT is non-nil.
618 To force-start a server, do \\[server-force-delete] and then
621 To check from a Lisp program whether a server is running, use
622 the `server-process' variable."
624 (when (or (not server-clients
)
625 ;; Ask the user before deleting existing clients---except
626 ;; when we can't get user input, which may happen when
627 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
630 (null (cdr (frame-list)))
631 (eq (selected-frame) terminal-frame
))
635 "The current server still has clients; delete them? "))))
636 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
637 (server-file (expand-file-name server-name server-dir
)))
640 (ignore-errors (delete-process server-process
)))
641 ;; Check to see if an uninitialized external socket has been
642 ;; passed in, if that is the case, skip checking
643 ;; `server-running-p' as this will return the wrong result.
644 (if (and internal--daemon-sockname
645 (not server--external-socket-initialized
))
646 (setq server--external-socket-initialized t
)
647 ;; Delete the socket files made by previous server invocations.
648 (if (not (eq t
(server-running-p server-name
)))
649 ;; Remove any leftover socket or authentication file.
651 (let (delete-by-moving-to-trash)
652 (delete-file server-file
)))
653 (setq server-mode nil
) ;; already set by the minor mode code
656 (concat "Unable to start the Emacs server.\n"
657 (format "There is an existing Emacs server, named %S.\n"
659 (substitute-command-keys
660 "To start the server in this Emacs process, stop the existing
661 server or call `\\[server-force-delete]' to forcibly disconnect it."))
663 (setq leave-dead t
)))
664 ;; If this Emacs already had a server, clear out associated status.
665 (while server-clients
666 (server-delete-client (car server-clients
)))
667 ;; Now any previous server is properly stopped.
670 (unless (eq t leave-dead
) (server-log (message "Server stopped")))
671 (setq server-process nil
))
672 ;; Make sure there is a safe directory in which to place the socket.
673 (server-ensure-safe-dir server-dir
)
675 (server-log (message "Restarting server")))
676 (cl-letf (((default-file-modes) ?
\700))
677 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
678 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
679 (add-hook 'kill-emacs-query-functions
680 'server-kill-emacs-query-function
)
681 ;; We put server's kill-emacs-hook after the others, so that
682 ;; frames are not deleted too early, because doing that
683 ;; would severely degrade our abilities to communicate with
684 ;; the user, while some hooks may wish to ask the user
685 ;; questions (e.g., desktop-kill).
686 (add-hook 'kill-emacs-hook
'server-force-stop t
) ;Cleanup upon exit.
688 (apply #'make-network-process
692 :sentinel
#'server-sentinel
693 :filter
#'server-process-filter
694 :use-external-socket t
695 ;; We must receive file names without being decoded.
696 ;; Those are decoded by server-process-filter according
697 ;; to file-name-coding-system. Also don't get
698 ;; confused by CRs since we don't quote them.
699 :coding
'raw-text-unix
700 ;; The other args depend on the kind of socket used.
702 (list :family
'ipv4
;; We're not ready for IPv6 yet
703 :service
(or server-port t
)
704 :host
(or server-host
'local
)
705 :plist
'(:authenticated nil
))
708 :plist
'(:authenticated t
)))))
709 (unless server-process
(error "Could not start server process"))
710 (process-put server-process
:server-file server-file
)
712 (let ((auth-key (server-get-auth-key)))
713 (process-put server-process
:auth-key auth-key
)
714 (with-temp-file server-file
715 (set-buffer-multibyte nil
)
716 (setq buffer-file-coding-system
'no-conversion
)
717 (insert (format-network-address
718 (process-contact server-process
:local
))
719 " " (number-to-string (emacs-pid)) ; Kept for compatibility
720 "\n" auth-key
)))))))))
722 (defun server-force-stop ()
723 "Kill all connections to the current server.
724 This function is meant to be called from `kill-emacs-hook'."
728 (defun server-force-delete (&optional name
)
729 "Unconditionally delete connection file for server NAME.
730 If server is running, it is first stopped.
731 NAME defaults to `server-name'. With argument, ask for NAME."
733 (list (if current-prefix-arg
734 (read-string "Server name: " nil nil server-name
))))
735 (when server-mode
(with-temp-message nil
(server-mode -
1)))
736 (let ((file (expand-file-name (or name server-name
)
739 server-socket-dir
))))
741 (let (delete-by-moving-to-trash)
743 (message "Connection file %S deleted" file
))
745 (message "No connection file %S" file
)))))
747 (defun server-running-p (&optional name
)
748 "Test whether server NAME is running.
751 nil the server is definitely not running.
752 t the server seems to be running.
753 something else we cannot determine whether it's running without using
754 commands which may have to wait for a long time.
756 This function can return non-nil if the server was started by some other
757 Emacs process. To check from a Lisp program whether a server was started
758 by the current Emacs process, use the `server-process' variable."
759 (unless name
(setq name server-name
))
763 (insert-file-contents-literally (expand-file-name name server-auth-dir
))
764 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
767 (string-to-number (match-string 1))))
771 (make-network-process
772 :name
"server-client-test" :family
'local
:server nil
:noquery t
773 :service
(expand-file-name name server-socket-dir
)))
778 (define-minor-mode server-mode
781 Server mode runs a process that accepts commands from the
782 `emacsclient' program. See Info node `Emacs server' and
783 `server-start' for details."
787 ;; Fixme: Should this check for an existing server socket and do
788 ;; nothing if there is one (for multiple Emacs sessions)?
789 (server-start (not server-mode
)))
791 (defun server-eval-and-print (expr proc
)
792 "Eval EXPR and send the result back to client PROC."
793 ;; While we're running asynchronously (from a process filter), it is likely
794 ;; that the emacsclient command was run in response to a user
795 ;; action, so the user probably knows that Emacs is processing this
796 ;; emacsclient request, so if we get a C-g it's likely that the user
797 ;; intended it to interrupt us rather than interrupt whatever Emacs
798 ;; was doing before it started handling the process filter.
799 ;; Hence `with-local-quit' (bug#6585).
800 (let ((v (with-local-quit (eval (car (read-from-string expr
))))))
803 (let ((standard-output (current-buffer)))
805 (let ((text (buffer-substring-no-properties
806 (point-min) (point-max))))
807 (server-reply-print (server-quote-arg text
) proc
)))))))
809 (defconst server-msg-size
1024
810 "Maximum size of a message sent to a client.")
812 (defun server-reply-print (qtext proc
)
813 "Send a `-print QTEXT' command to client PROC.
814 QTEXT must be already quoted.
815 This handles splitting the command if it would be bigger than
817 (let ((prefix "-print ")
819 (while (> (+ (length qtext
) (length prefix
) 1) server-msg-size
)
820 ;; We have to split the string
821 (setq part
(substring qtext
0 (- server-msg-size
(length prefix
) 1)))
822 ;; Don't split in the middle of a quote sequence
823 (if (string-match "\\(^\\|[^&]\\)&\\(&&\\)*$" part
)
824 ;; There is an uneven number of & at the end
825 (setq part
(substring part
0 -
1)))
826 (setq qtext
(substring qtext
(length part
)))
827 (server-send-string proc
(concat prefix part
"\n"))
828 (setq prefix
"-print-nonl "))
829 (server-send-string proc
(concat prefix qtext
"\n"))))
831 (defun server-create-tty-frame (tty type proc
)
833 (error "Invalid terminal device"))
835 (error "Invalid terminal type"))
836 (add-to-list 'frame-inherited-parameters
'client
)
838 (server-with-environment
839 (process-get proc
'env
)
840 '("LANG" "LC_CTYPE" "LC_ALL"
841 ;; For tgetent(3); list according to ncurses(3).
842 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
843 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
844 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
845 "TERMINFO_DIRS" "TERMPATH"
847 "COLORFGBG" "COLORTERM")
848 (make-frame `((window-system . nil
)
851 ;; Ignore nowait here; we always need to
852 ;; clean up opened ttys when the client dies.
854 ;; This is a leftover from an earlier
855 ;; attempt at making it possible for process
856 ;; run in the server process to use the
857 ;; environment of the client process.
858 ;; It has no effect now and to make it work
859 ;; we'd need to decide how to make
860 ;; process-environment interact with client
861 ;; envvars, and then to change the
862 ;; C functions `child_setup' and
863 ;; `getenv_internal' accordingly.
864 (environment .
,(process-get proc
'env
)))))))
866 ;; ttys don't use the `display' parameter, but callproc.c does to set
867 ;; the DISPLAY environment on subprocesses.
868 (set-frame-parameter frame
'display
869 (getenv-internal "DISPLAY" (process-get proc
'env
)))
871 (process-put proc
'frame frame
)
872 (process-put proc
'terminal
(frame-terminal frame
))
875 (defun server-create-window-system-frame (display nowait proc parent-id
876 &optional parameters
)
877 (let* ((display (or display
878 (frame-parameter nil
'display
)
879 (error "Please specify display.")))
880 (w (or (cdr (assq 'window-system parameters
))
881 (window-system-for-display display
))))
883 ;; Special case for ns. This is because DISPLAY may not be set at all
884 ;; which in the ns case isn't an error. The variable display then becomes
885 ;; the fully qualified hostname, which make-frame-on-display below
886 ;; does not understand and throws an error.
887 ;; It may also be a valid X display, but if Emacs is compiled for ns, it
888 ;; can not make X frames.
889 (if (featurep 'ns-win
)
890 (setq w
'ns display
"ns")
891 ;; FIXME! Not sure what this was for, and not sure how it should work
892 ;; in the cl-defmethod new world!
893 ;;(unless (assq w window-system-initialization-alist)
898 ;; Flag frame as client-created, but use a dummy client.
899 ;; This will prevent the frame from being deleted when
900 ;; emacsclient quits while also preventing
901 ;; `server-save-buffers-kill-terminal' from unexpectedly
902 ;; killing emacs on that frame.
903 (let* ((params `((client .
,(if nowait
'nowait proc
))
904 ;; This is a leftover, see above.
905 (environment .
,(process-get proc
'env
))
909 (push (cons 'parent-id
(string-to-number parent-id
)) params
))
910 (add-to-list 'frame-inherited-parameters
'client
)
911 (setq frame
(make-frame-on-display display params
))
912 (server-log (format "%s created" frame
) proc
)
914 (process-put proc
'frame frame
)
915 (process-put proc
'terminal
(frame-terminal frame
))
919 (server-log "Window system unsupported" proc
)
920 (server-send-string proc
"-window-system-unsupported \n")
923 (defun server-goto-toplevel (proc)
925 ;; If we're running isearch, we must abort it to allow Emacs to
926 ;; display the buffer and switch to it.
927 (dolist (buffer (buffer-list))
928 (with-current-buffer buffer
929 (when (bound-and-true-p isearch-mode
)
931 ;; Signaled by isearch-cancel.
932 (quit (message nil
)))
933 (when (> (recursion-depth) 0)
934 ;; We're inside a minibuffer already, so if the emacs-client is trying
935 ;; to open a frame on a new display, we might end up with an unusable
936 ;; frame because input from that display will be blocked (until exiting
937 ;; the minibuffer). Better exit this minibuffer right away.
938 ;; Similarly with recursive-edits such as the splash screen.
939 (run-with-timer 0 nil
(lambda () (server-execute-continuation proc
)))
942 ;; We use various special properties on process objects:
943 ;; - `env' stores the info about the environment of the emacsclient process.
944 ;; - `continuation' is a no-arg function that we need to execute. It contains
945 ;; commands we wanted to execute in some earlier invocation of the process
946 ;; filter but that we somehow were unable to process at that time
947 ;; (e.g. because we first need to throw to the toplevel).
949 (defun server-execute-continuation (proc)
950 (let ((continuation (process-get proc
'continuation
)))
951 (process-put proc
'continuation nil
)
952 (if continuation
(ignore-errors (funcall continuation
)))))
954 (cl-defun server-process-filter (proc string
)
955 "Process a request from the server to edit some files.
956 PROC is the server process. STRING consists of a sequence of
957 commands prefixed by a dash. Some commands have arguments;
958 these are &-quoted and need to be decoded by `server-unquote-arg'.
959 The filter parses and executes these commands.
961 To illustrate the protocol, here is an example command that
962 emacsclient sends to create a new X frame (note that the whole
963 sequence is sent on a single line):
965 -env HOME=/home/lorentey
967 ... lots of other -env commands
971 The following commands are accepted by the server:
974 Authenticate the client using the secret authentication string
978 An environment variable on the client side.
981 The current working directory of the client process.
984 Forbid the creation of new frames.
986 `-frame-parameters ALIST'
987 Set the parameters of the created frame.
990 Request that the next frame created should not be
991 associated with this client.
994 Set the display name to open X frames on.
996 `-position LINE[:COLUMN]'
997 Go to the given line and column number
998 in the next file opened.
1001 Load the given file in the current frame.
1004 Evaluate EXPR as a Lisp expression and return the
1005 result in -print commands.
1010 `-tty DEVICENAME TYPE'
1011 Open a new tty frame at the client.
1014 Suspend this tty frame. The client sends this string in
1015 response to SIGTSTP and SIGTTOU. The server must cease all I/O
1016 on this tty until it gets a -resume command.
1019 Resume this tty frame. The client sends this string when it
1020 gets the SIGCONT signal and it is the foreground process on its
1024 Do nothing, but put the comment in the server log.
1025 Useful for debugging.
1028 The following commands are accepted by the client:
1031 Describes the process id of the Emacs process;
1032 used to forward window change signals to it.
1034 `-window-system-unsupported'
1035 Signals that the server does not support creating X frames;
1036 the client must try again with a tty frame.
1039 Print STRING on stdout. Used to send values
1042 `-print-nonl STRING'
1043 Print STRING on stdout. Used to continue a
1044 preceding -print command that would be too big to send
1045 in a single message.
1047 `-error DESCRIPTION'
1048 Signal an error and delete process PROC.
1051 Suspend this terminal, i.e., stop the client process.
1052 Sent when the user presses C-z."
1053 (server-log (concat "Received " string
) proc
)
1054 ;; First things first: let's check the authentication
1055 (unless (process-get proc
:authenticated
)
1056 (if (and (string-match "-auth \\([!-~]+\\)\n?" string
)
1057 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
1059 (setq string
(substring string
(match-end 0)))
1060 (process-put proc
:authenticated t
)
1061 (server-log "Authentication successful" proc
))
1062 (server-log "Authentication failed" proc
)
1064 proc
(concat "-error " (server-quote-arg "Authentication failed")))
1065 ;; Before calling `delete-process', give emacsclient time to
1066 ;; receive the error string and shut down on its own.
1068 (delete-process proc
)
1069 ;; We return immediately.
1070 (cl-return-from server-process-filter
)))
1071 (let ((prev (process-get proc
'previous-string
)))
1073 (setq string
(concat prev string
))
1074 (process-put proc
'previous-string nil
)))
1077 (server-add-client proc
)
1079 (server-send-string proc
(concat "-emacs-pid "
1080 (number-to-string (emacs-pid)) "\n"))
1081 (if (not (string-match "\n" string
))
1082 ;; Save for later any partial line that remains.
1083 (when (> (length string
) 0)
1084 (process-put proc
'previous-string string
))
1086 ;; In earlier versions of server.el (where we used an `emacsserver'
1087 ;; process), there could be multiple lines. Nowadays this is not
1088 ;; supported any more.
1089 (cl-assert (eq (match-end 0) (length string
)))
1090 (let ((request (substring string
0 (match-beginning 0)))
1091 (coding-system (or file-name-coding-system
1092 default-file-name-coding-system
))
1093 nowait
; t if emacsclient does not want to wait for us.
1094 frame
; Frame opened for the client (if any).
1095 display
; Open frame on this display.
1096 parent-id
; Window ID for XEmbed
1097 dontkill
; t if client should not be killed.
1101 frame-parameters
;parameters for newly created frame
1102 tty-name
; nil, `window-system', or the tty name.
1108 ;; Remove this line from STRING.
1109 (setq string
(substring string
(match-end 0)))
1111 (mapcar 'server-unquote-arg
(split-string request
" " t
)))
1113 (pcase (pop args-left
)
1114 ;; -version CLIENT-VERSION: obsolete at birth.
1115 (`"-version" (pop args-left
))
1117 ;; -nowait: Emacsclient won't wait for a result.
1118 (`"-nowait" (setq nowait t
))
1120 ;; -current-frame: Don't create frames.
1121 (`"-current-frame" (setq use-current-frame t
))
1123 ;; -frame-parameters: Set frame parameters
1124 (`"-frame-parameters"
1125 (let ((alist (pop args-left
)))
1127 (setq alist
(decode-coding-string alist coding-system
)))
1128 (setq frame-parameters
(car (read-from-string alist
)))))
1130 ;; -display DISPLAY:
1131 ;; Open X frames on the given display instead of the default.
1133 (setq display
(pop args-left
))
1134 (if (zerop (length display
)) (setq display nil
)))
1137 ;; Open X frame within window ID, via XEmbed.
1139 (setq parent-id
(pop args-left
))
1140 (if (zerop (length parent-id
)) (setq parent-id nil
)))
1142 ;; -window-system: Open a new X frame.
1144 (if (fboundp 'x-create-frame
)
1146 tty-name
'window-system
)))
1148 ;; -resume: Resume a suspended tty frame.
1150 (let ((terminal (process-get proc
'terminal
)))
1153 (when (eq (terminal-live-p terminal
) t
)
1154 (resume-tty terminal
)))
1157 ;; -suspend: Suspend the client's frame. (In case we
1158 ;; get out of sync, and a C-z sends a SIGTSTP to
1161 (let ((terminal (process-get proc
'terminal
)))
1164 (when (eq (terminal-live-p terminal
) t
)
1165 (suspend-tty terminal
)))
1168 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1169 ;; (The given comment appears in the server log.)
1174 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1175 ;; (But if we see -window-system later, use that.)
1177 (setq tty-name
(pop args-left
)
1178 tty-type
(pop args-left
)
1179 dontkill
(or dontkill
1180 (not use-current-frame
)))
1181 ;; On Windows, emacsclient always asks for a tty
1182 ;; frame. If running a GUI server, force the frame
1183 ;; type to GUI. (Cygwin is perfectly happy with
1184 ;; multi-tty support, so don't override the user's
1185 ;; choice there.) In daemon mode on Windows, we can't
1186 ;; make tty frames, so force the frame type to GUI
1188 (when (and (eq system-type
'windows-nt
)
1190 (eq window-system
'w32
)))
1191 (push "-window-system" args-left
)))
1193 ;; -position LINE[:COLUMN]: Set point to the given
1194 ;; position in the next file.
1196 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1198 (error "Invalid -position command in client args"))
1199 (let ((arg (pop args-left
)))
1201 (cons (string-to-number (match-string 1 arg
))
1202 (string-to-number (or (match-string 2 arg
)
1205 ;; -file FILENAME: Load the given file.
1207 (let ((file (pop args-left
)))
1209 (setq file
(decode-coding-string file coding-system
)))
1210 ;; Allow Cygwin's emacsclient to be used as a file
1211 ;; handler on MS-Windows, in which case FILENAME
1212 ;; might start with a drive letter.
1213 (when (and (fboundp 'cygwin-convert-file-name-from-windows
)
1214 (string-match "\\`[A-Za-z]:" file
))
1215 (setq file
(cygwin-convert-file-name-from-windows file
)))
1216 (setq file
(expand-file-name file dir
))
1217 (push (cons file filepos
) files
)
1218 (server-log (format "New file: %s %s"
1219 file
(or filepos
""))
1223 ;; -eval EXPR: Evaluate a Lisp expression.
1225 (if use-current-frame
1226 (setq use-current-frame
'always
))
1227 (let ((expr (pop args-left
)))
1229 (setq expr
(decode-coding-string expr coding-system
)))
1230 (push (lambda () (server-eval-and-print expr proc
))
1232 (setq filepos nil
)))
1234 ;; -env NAME=VALUE: An environment variable.
1236 (let ((var (pop args-left
)))
1237 ;; XXX Variables should be encoded as in getenv/setenv.
1238 (process-put proc
'env
1239 (cons var
(process-get proc
'env
)))))
1241 ;; -dir DIRNAME: The cwd of the emacsclient process.
1243 (setq dir
(pop args-left
))
1245 (setq dir
(decode-coding-string dir coding-system
)))
1246 (setq dir
(command-line-normalize-file-name dir
))
1247 (process-put proc
'server-client-directory dir
))
1250 (arg (error "Unknown command: %s" arg
))))
1252 ;; If both -no-wait and -tty are given with file or sexp
1253 ;; arguments, use an existing frame.
1255 (not (eq tty-name
'window-system
))
1257 (setq use-current-frame t
))
1259 (setq create-frame-func
1262 ((and use-current-frame
1263 (or (eq use-current-frame
'always
)
1264 ;; We can't use the Emacs daemon's
1267 (null (cdr (frame-list)))
1268 (eq (selected-frame)
1270 (setq tty-name nil tty-type nil
)
1271 (if display
(server-select-display display
)))
1272 ((or (and (eq system-type
'windows-nt
)
1274 (setq display
"w32"))
1275 (eq tty-name
'window-system
))
1276 (server-create-window-system-frame display nowait proc
1279 ;; When resuming on a tty, tty-name is nil.
1281 (server-create-tty-frame tty-name tty-type proc
)))))
1286 (with-current-buffer (get-buffer-create server-buffer
)
1287 ;; Use the same cwd as the emacsclient, if possible, so
1288 ;; relative file names work correctly, even in `eval'.
1289 (let ((default-directory
1290 (if (and dir
(file-directory-p dir
))
1291 dir default-directory
)))
1292 (server-execute proc files nowait commands
1293 dontkill create-frame-func tty-name
)))))
1295 (when (or frame files
)
1296 (server-goto-toplevel proc
))
1298 (server-execute-continuation proc
))))
1300 (t (server-return-error proc err
))))
1302 (defun server-execute (proc files nowait commands dontkill create-frame-func tty-name
)
1303 ;; This is run from timers and process-filters, i.e. "asynchronously".
1304 ;; But w.r.t the user, this is not really asynchronous since the timer
1305 ;; is run after 0s and the process-filter is run in response to the
1306 ;; user running `emacsclient'. So it is OK to override the
1307 ;; inhibit-quit flag, which is good since `commands' (as well as
1308 ;; find-file-noselect via the major-mode) can run arbitrary code,
1309 ;; including code that needs to wait.
1312 (let* ((buffers (server-visit-files files proc nowait
))
1313 ;; If we were told only to open a new client, obey
1314 ;; `initial-buffer-choice' if it specifies a file
1316 (initial-buffer (unless (or files commands
)
1318 (cond ((stringp initial-buffer-choice
)
1319 (find-file-noselect initial-buffer-choice
))
1320 ((functionp initial-buffer-choice
)
1321 (funcall initial-buffer-choice
)))))
1322 (if (buffer-live-p buf
) buf
(get-buffer-create "*scratch*")))))
1323 ;; Set current buffer so that newly created tty frames
1324 ;; show the correct buffer initially.
1325 (frame (with-current-buffer (or (car buffers
)
1329 (funcall create-frame-func
)
1330 ;; Switch to initial buffer in case the frame was reused.
1331 (when initial-buffer
1332 (switch-to-buffer initial-buffer
'norecord
))))))
1334 (mapc 'funcall
(nreverse commands
))
1336 ;; Delete the client if necessary.
1339 ;; Client requested nowait; return immediately.
1340 (server-log "Close nowait client" proc
)
1341 (server-delete-client proc
))
1342 ((and (not dontkill
) (null buffers
))
1343 ;; This client is empty; get rid of it immediately.
1344 (server-log "Close empty client" proc
)
1345 (server-delete-client proc
)))
1347 ((or isearch-mode
(minibufferp))
1349 ((and frame
(null buffers
))
1350 (run-hooks 'server-after-make-frame-hook
)
1351 (message "%s" (substitute-command-keys
1352 "When done with this frame, type \\[delete-frame]")))
1353 ((not (null buffers
))
1354 (run-hooks 'server-after-make-frame-hook
)
1355 (server-switch-buffer (car buffers
) nil
(cdr (car files
)))
1356 (run-hooks 'server-switch-hook
)
1358 (message "%s" (substitute-command-keys
1359 "When done with a buffer, type \\[server-edit]")))))
1360 (when (and frame
(null tty-name
))
1361 (server-unselect-display frame
)))
1363 (when (eq (car err
) 'quit
)
1364 (message "Quit emacsclient request"))
1365 (server-return-error proc err
)))))
1367 (defun server-return-error (proc err
)
1370 proc
(concat "-error " (server-quote-arg
1371 (error-message-string err
))))
1372 (server-log (error-message-string err
) proc
)
1373 ;; Before calling `delete-process', give emacsclient time to
1374 ;; receive the error string and shut down on its own.
1376 (delete-process proc
)))
1378 (defun server-goto-line-column (line-col)
1379 "Move point to the position indicated in LINE-COL.
1380 LINE-COL should be a pair (LINE . COL)."
1382 (goto-char (point-min))
1383 (forward-line (1- (car line-col
)))
1384 (let ((column-number (cdr line-col
)))
1385 (when (> column-number
0)
1386 (move-to-column (1- column-number
))))))
1388 (defun server-visit-files (files proc
&optional nowait
)
1389 "Find FILES and return a list of buffers created.
1390 FILES is an alist whose elements are (FILENAME . FILEPOS)
1391 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1392 PROC is the client that requested this operation.
1393 NOWAIT non-nil means this client is not waiting for the results,
1394 so don't mark these buffers specially, just visit them normally."
1395 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1396 (let ((last-nonmenu-event t
) client-record
)
1397 ;; Restore the current buffer afterward, but not using save-excursion,
1398 ;; because we don't want to save point in this buffer
1399 ;; if it happens to be one of those specified by the server.
1400 (save-current-buffer
1401 (dolist (file files
)
1402 ;; If there is an existing buffer modified or the file is
1403 ;; modified, revert it. If there is an existing buffer with
1404 ;; deleted file, offer to write it.
1405 (let* ((minibuffer-auto-raise (or server-raise-frame
1406 minibuffer-auto-raise
))
1408 (obuf (get-file-buffer filen
)))
1409 (add-to-history 'file-name-history filen
)
1412 (run-hooks 'pre-command-hook
)
1413 (set-buffer (find-file-noselect filen
)))
1415 ;; separately for each file, in sync with post-command hooks,
1416 ;; with the new buffer current:
1417 (run-hooks 'pre-command-hook
)
1418 (cond ((file-exists-p filen
)
1419 (when (not (verify-visited-file-modtime obuf
))
1420 (revert-buffer t nil
)))
1423 (concat "File no longer exists: " filen
1424 ", write buffer to file? "))
1425 (write-file filen
))))
1426 (unless server-buffer-clients
1427 (setq server-existing-buffer t
)))
1428 (server-goto-line-column (cdr file
))
1429 (run-hooks 'server-visit-hook
)
1430 ;; hooks may be specific to current buffer:
1431 (run-hooks 'post-command-hook
))
1433 ;; When the buffer is killed, inform the clients.
1434 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1435 (push proc server-buffer-clients
))
1436 (push (current-buffer) client-record
)))
1438 (process-put proc
'buffers
1439 (nconc (process-get proc
'buffers
) client-record
)))
1442 (defvar server-kill-buffer-running nil
1443 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1445 (defun server-buffer-done (buffer &optional for-killing
)
1446 "Mark BUFFER as \"done\" for its client(s).
1447 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1448 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1449 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1451 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1452 (let ((next-buffer nil
)
1454 (dolist (proc server-clients
)
1455 (let ((buffers (process-get proc
'buffers
)))
1457 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1458 (when buffers
; Ignore bufferless clients.
1459 (setq buffers
(delq buffer buffers
))
1460 ;; Delete all dead buffers from PROC.
1463 (not (buffer-live-p b
))
1464 (setq buffers
(delq b buffers
))))
1465 (process-put proc
'buffers buffers
)
1466 ;; If client now has no pending buffers,
1467 ;; tell it that it is done, and forget it entirely.
1469 (server-log "Close" proc
)
1471 ;; `server-delete-client' might delete the client's
1472 ;; frames, which might change the current buffer. We
1473 ;; don't want that (bug#640).
1474 (save-current-buffer
1475 (server-delete-client proc
))
1476 (server-delete-client proc
))))))
1477 (when (and (bufferp buffer
) (buffer-name buffer
))
1478 ;; We may or may not kill this buffer;
1479 ;; if we do, do not call server-buffer-done recursively
1480 ;; from kill-buffer-hook.
1481 (let ((server-kill-buffer-running t
))
1482 (with-current-buffer buffer
1483 (setq server-buffer-clients nil
)
1484 (run-hooks 'server-done-hook
))
1485 ;; Notice whether server-done-hook killed the buffer.
1486 (if (null (buffer-name buffer
))
1488 ;; Don't bother killing or burying the buffer
1489 ;; when we are called from kill-buffer.
1491 (when (and (not killed
)
1492 server-kill-new-buffers
1493 (with-current-buffer buffer
1494 (not server-existing-buffer
)))
1496 (bury-buffer buffer
)
1497 ;; Prevent kill-buffer from prompting (Bug#3696).
1498 (with-current-buffer buffer
1499 (set-buffer-modified-p nil
))
1500 (kill-buffer buffer
))
1502 (if (server-temp-file-p buffer
)
1504 (with-current-buffer buffer
1505 (set-buffer-modified-p nil
))
1506 (kill-buffer buffer
)
1508 (bury-buffer buffer
)))))))
1509 (list next-buffer killed
)))
1511 (defun server-temp-file-p (&optional buffer
)
1512 "Return non-nil if BUFFER contains a file considered temporary.
1513 These are files whose names suggest they are repeatedly
1514 reused to pass information to another program.
1516 The variable `server-temp-file-regexp' controls which filenames
1517 are considered temporary."
1518 (and (buffer-file-name buffer
)
1519 (string-match-p server-temp-file-regexp
(buffer-file-name buffer
))))
1521 (defun server-done ()
1522 "Offer to save current buffer, mark it as \"done\" for clients.
1523 This kills or buries the buffer, then returns a list
1524 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1525 as a suggestion for what to select next, or nil.
1526 KILLED is t if we killed BUFFER, which happens if it was created
1527 specifically for the clients and did not exist before their request for it."
1528 (when server-buffer-clients
1529 (if (server-temp-file-p)
1530 ;; For a temp file, save, and do make a non-numeric backup
1531 ;; (unless make-backup-files is nil).
1532 (let ((version-control nil
)
1533 (buffer-backed-up nil
))
1535 (when (and (buffer-modified-p)
1537 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1539 (server-buffer-done (current-buffer))))
1541 (defun server-kill-emacs-query-function ()
1542 "Ask before exiting Emacs if it has live clients."
1543 (or (not (let (live-client)
1544 (dolist (proc server-clients
)
1545 (when (memq t
(mapcar 'buffer-live-p
(process-get
1547 (setq live-client t
)))
1549 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1551 (defun server-kill-buffer ()
1552 "Remove the current buffer from its clients' buffer list.
1553 Designed to be added to `kill-buffer-hook'."
1554 ;; Prevent infinite recursion if user has made server-done-hook
1555 ;; call kill-buffer.
1556 (or server-kill-buffer-running
1557 (and server-buffer-clients
1558 (let ((server-kill-buffer-running t
))
1559 (when server-process
1560 (server-buffer-done (current-buffer) t
))))))
1562 (defun server-edit (&optional arg
)
1563 "Switch to next server editing buffer; say \"Done\" for current buffer.
1564 If a server buffer is current, it is marked \"done\" and optionally saved.
1565 The buffer is also killed if it did not exist before the clients asked for it.
1566 When all of a client's buffers are marked as \"done\", the client is notified.
1568 Temporary files such as MH <draft> files are always saved and backed up,
1569 no questions asked. (The variable `make-backup-files', if nil, still
1570 inhibits a backup; you can set it locally in a particular buffer to
1571 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1572 which filenames are considered temporary.
1574 If invoked with a prefix argument, or if there is no server process running,
1575 starts server process and that is all. Invoked by \\[server-edit]."
1579 (not server-process
)
1580 (memq (process-status server-process
) '(signal exit
)))
1582 (server-clients (apply 'server-switch-buffer
(server-done)))
1583 (t (message "No server editing buffers exist"))))
1585 (defun server-switch-buffer (&optional next-buffer killed-one filepos
)
1586 "Switch to another buffer, preferably one that has a client.
1587 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1589 KILLED-ONE is t in a recursive call if we have already killed one
1590 temp-file server buffer. This means we should avoid the final
1591 \"switch to some other buffer\" since we've already effectively
1594 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1595 visit NEXT-BUFFER in an existing window. If non-nil, it should
1596 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1597 (if (null next-buffer
)
1599 (let ((rest server-clients
))
1600 (while (and rest
(not next-buffer
))
1601 (let ((proc (car rest
)))
1602 ;; Only look at frameless clients, or those in the selected
1604 (when (or (not (process-get proc
'frame
))
1605 (eq (process-get proc
'frame
) (selected-frame)))
1606 (setq next-buffer
(car (process-get proc
'buffers
))))
1607 (setq rest
(cdr rest
)))))
1608 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1609 (unless (or next-buffer killed-one
(window-dedicated-p))
1610 ;; (switch-to-buffer (other-buffer))
1611 (message "No server buffers remain to edit")))
1612 (if (not (buffer-live-p next-buffer
))
1613 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1614 ;; and try the next surviving server buffer.
1615 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1616 ;; OK, we know next-buffer is live, let's display and select it.
1617 (if (functionp server-window
)
1618 (funcall server-window next-buffer
)
1619 (let ((win (get-buffer-window next-buffer
0)))
1620 (if (and win
(not server-window
))
1621 ;; The buffer is already displayed: just reuse the
1622 ;; window. If FILEPOS is non-nil, use it to replace the
1623 ;; window's own value of point.
1626 (set-buffer next-buffer
)
1628 (server-goto-line-column filepos
)))
1629 ;; Otherwise, let's find an appropriate window.
1630 (cond ((window-live-p server-window
)
1631 (select-window server-window
))
1632 ((framep server-window
)
1633 (unless (frame-live-p server-window
)
1634 (setq server-window
(make-frame)))
1635 (select-window (frame-selected-window server-window
))))
1636 (when (window-minibuffer-p)
1637 (select-window (next-window nil
'nomini
0)))
1638 ;; Move to a non-dedicated window, if we have one.
1639 (when (window-dedicated-p)
1641 (get-window-with-predicate
1643 (and (not (window-dedicated-p w
))
1644 (equal (frame-terminal (window-frame w
))
1646 'nomini
'visible
(selected-window))))
1648 (switch-to-buffer next-buffer
)
1649 ;; After all the above, we might still have ended up with
1650 ;; a minibuffer/dedicated-window (if there's no other).
1651 (error (pop-to-buffer next-buffer
)))))))
1652 (when server-raise-frame
1653 (select-frame-set-input-focus (window-frame)))))
1656 (defun server-save-buffers-kill-terminal (arg)
1657 ;; Called from save-buffers-kill-terminal in files.el.
1658 "Offer to save each buffer, then kill the current client.
1659 With ARG non-nil, silently save all file-visiting buffers, then kill.
1661 If emacsclient was started with a list of filenames to edit, then
1662 only these files will be asked to be saved."
1663 (let ((proc (frame-parameter nil
'client
)))
1664 (cond ((eq proc
'nowait
)
1665 ;; Nowait frames have no client buffer list.
1666 (if (cdr (frame-list))
1667 (progn (save-some-buffers arg
)
1669 ;; If we're the last frame standing, kill Emacs.
1670 (save-buffers-kill-emacs arg
)))
1672 (let ((buffers (process-get proc
'buffers
)))
1675 ;; Only files from emacsclient file list.
1676 (lambda () (memq (current-buffer) buffers
))
1677 ;; No emacsclient file list: don't override
1678 ;; `save-some-buffers-default-predicate' (unless
1679 ;; ARG is non-nil), since we're not killing
1680 ;; Emacs (unlike `save-buffers-kill-emacs').
1682 (server-delete-client proc
)))
1683 (t (error "Invalid client frame")))))
1685 (define-key ctl-x-map
"#" 'server-edit
)
1687 (defun server-unload-function ()
1688 "Unload the Server library."
1690 (substitute-key-definition 'server-edit nil ctl-x-map
)
1691 (save-current-buffer
1692 (dolist (buffer (buffer-list))
1694 (remove-hook 'kill-buffer-hook
'server-kill-buffer t
)))
1695 ;; continue standard unloading
1698 (defun server-eval-at (server form
)
1699 "Contact the Emacs server named SERVER and evaluate FORM there.
1700 Returns the result of the evaluation, or signals an error if it
1701 cannot contact the specified server. For example:
1702 (server-eval-at \"server\" \\='(emacs-pid))
1703 returns the process ID of the Emacs instance running \"server\"."
1704 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
1705 (server-file (expand-file-name server server-dir
))
1706 (coding-system-for-read 'binary
)
1707 (coding-system-for-write 'binary
)
1708 address port secret process
)
1709 (unless (file-exists-p server-file
)
1710 (error "No such server: %s" server
))
1712 (when server-use-tcp
1713 (let ((coding-system-for-read 'no-conversion
))
1714 (insert-file-contents server-file
)
1715 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1716 (error "Invalid auth file"))
1717 (setq address
(match-string 1)
1718 port
(string-to-number (match-string 2)))
1720 (setq secret
(buffer-substring (point) (line-end-position)))
1722 (unless (setq process
(make-network-process
1724 :buffer
(current-buffer)
1726 :service
(if server-use-tcp port server-file
)
1727 :family
(if server-use-tcp
'ipv4
'local
)
1729 (error "Unable to contact the server"))
1731 (process-send-string process
(concat "-auth " secret
"\n")))
1732 (process-send-string process
1734 (server-quote-arg (format "%S" form
))
1736 (while (memq (process-status process
) '(open run
))
1737 (accept-process-output process
0 10))
1738 (goto-char (point-min))
1739 ;; If the result is nil, there's nothing in the buffer. If the
1740 ;; result is non-nil, it's after "-print ".
1742 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t
)
1745 (buffer-substring (point)
1746 (progn (skip-chars-forward "^\n")
1748 (if (not (equal answer
""))
1749 (read (decode-coding-string (server-unquote-arg answer
)
1750 'emacs-internal
)))))))
1755 ;;; server.el ends here