1 ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
3 ;; Copyright (C) 1986-1987, 1992, 1994-2012 Free Software Foundation, Inc.
5 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
9 ;; Changes by peck@sun.com and by rms.
10 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; This Lisp code is run in Emacs when it is to operate as
30 ;; a server for other processes.
32 ;; Load this library and do M-x server-edit to enable Emacs as a server.
33 ;; Emacs opens up a socket for communication with clients. If there are no
34 ;; client buffers to edit, server-edit acts like (switch-to-buffer
37 ;; When some other program runs "the editor" to edit a file,
38 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
39 ;; This program transmits the file names to Emacs through
40 ;; the server subprocess, and Emacs visits them and lets you edit them.
42 ;; Note that any number of clients may dispatch files to Emacs to be edited.
44 ;; When you finish editing a Server buffer, again call server-edit
45 ;; to mark that buffer as done for the client and switch to the next
46 ;; Server buffer. When all the buffers for a client have been edited
47 ;; and exited with server-edit, the client "editor" will return
48 ;; to the program that invoked it.
50 ;; Your editing commands and Emacs's display output go to and from
51 ;; the terminal in the usual way. Thus, server operation is possible
52 ;; only when Emacs can talk to the terminal at the time you invoke
53 ;; the client. This is possible in four cases:
55 ;; 1. On a window system, where Emacs runs in one window and the
56 ;; program that wants to use "the editor" runs in another.
58 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
59 ;; program that wants to use "the editor" runs on another.
61 ;; 3. When the program that wants to use "the editor" is running
62 ;; as a subprocess of Emacs.
64 ;; 4. On a system with job control, when Emacs is suspended, the program
65 ;; that wants to use "the editor" will stop and display
66 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
67 ;; brought into the foreground for editing. When done editing, Emacs is
68 ;; suspended again, and the client program is brought into the foreground.
70 ;; The buffer local variable "server-buffer-clients" lists
71 ;; the clients who are waiting for this buffer to be edited.
72 ;; The global variable "server-clients" lists all the waiting clients,
73 ;; and which files are yet to be edited for each.
77 ;; - handle command-line-args-left.
78 ;; - move most of the args processing and decision making from emacsclient.c
80 ;; - fix up handling of the client's environment (place it in the terminal?).
84 (eval-when-compile (require 'cl-lib
))
87 "Emacs running as a server process."
90 (defcustom server-use-tcp nil
91 "If non-nil, use TCP sockets instead of local sockets."
92 :set
#'(lambda (sym val
)
93 (unless (featurep 'make-network-process
'(:family local
))
95 (unless load-in-progress
96 (message "Local sockets unsupported, using TCP sockets")))
97 (set-default sym val
))
102 (defcustom server-host nil
103 "The name or IP address to use as host address of the server process.
104 If set, the server accepts remote connections; otherwise it is local."
107 (string :tag
"Name or IP address")
108 (const :tag
"Local" nil
))
111 (put 'server-host
'risky-local-variable t
)
113 (defcustom server-port nil
114 "The port number that the server process should listen on.
115 This variable only takes effect when the Emacs server is using
116 TCP instead of local sockets. A nil value means to use a random
120 (string :tag
"Port number")
121 (const :tag
"Random" nil
))
124 (put 'server-port
'risky-local-variable t
)
126 (defcustom server-auth-dir
(locate-user-emacs-file "server/")
127 "Directory for server authentication files.
128 We only use this if `server-use-tcp' is non-nil.
129 Otherwise we use `server-socket-dir'.
131 NOTE: On FAT32 filesystems, directories are not secure;
132 files can be read and modified by any user or process.
133 It is strongly suggested to set `server-auth-dir' to a
134 directory residing in a NTFS partition instead."
139 (put 'server-auth-dir
'risky-local-variable t
)
141 (defcustom server-auth-key nil
142 "Server authentication key.
144 Normally, the authentication key is randomly generated when the
145 server starts, which guarantees some level of security. It is
146 recommended to leave it that way. Using a long-lived shared key
147 will decrease security (especially since the key is transmitted as
150 In some situations however, it can be difficult to share randomly
151 generated passwords with remote hosts (eg. no shared directory),
152 so you can set the key with this variable and then copy the
153 server file to the remote host (with possible changes to IP
154 address and/or port if that applies).
156 The key must consist of 64 ASCII printable characters except for
157 space (this means characters from ! to ~; or from code 33 to 126).
159 You can use \\[server-generate-key] to get a random authentication
163 (const :tag
"Random" nil
)
164 (string :tag
"Password"))
167 (defcustom server-raise-frame t
168 "If non-nil, raise frame when switching to a buffer."
173 (defcustom server-visit-hook nil
174 "Hook run when visiting a file for the Emacs server."
178 (defcustom server-switch-hook nil
179 "Hook run when switching to a buffer for the Emacs server."
183 (defcustom server-done-hook nil
184 "Hook run when done editing a buffer for the Emacs server."
188 (defvar server-process nil
189 "The current server process.")
191 (defvar server-clients nil
192 "List of current server clients.
193 Each element is a process.")
195 (defvar server-buffer-clients nil
196 "List of client processes requesting editing of current buffer.")
197 (make-variable-buffer-local 'server-buffer-clients
)
198 ;; Changing major modes should not erase this local.
199 (put 'server-buffer-clients
'permanent-local t
)
201 (defcustom server-window nil
202 "Specification of the window to use for selecting Emacs server buffers.
203 If nil, use the selected window.
204 If it is a function, it should take one argument (a buffer) and
205 display and select it. A common value is `pop-to-buffer'.
206 If it is a window, use that.
207 If it is a frame, use the frame's selected window.
209 It is not meaningful to set this to a specific frame or window with Custom.
210 Only programs can do so."
213 :type
'(choice (const :tag
"Use selected window"
214 :match
(lambda (widget value
)
215 (not (functionp value
)))
217 (function-item :tag
"Display in new frame" switch-to-buffer-other-frame
)
218 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
219 (function :tag
"Other function")))
221 (defcustom server-temp-file-regexp
"^/tmp/Re\\|/draft$"
222 "Regexp matching names of temporary files.
223 These are deleted and reused after each edit by the programs that
224 invoke the Emacs server."
228 (defcustom server-kill-new-buffers t
229 "Whether to kill buffers when done with them.
230 If non-nil, kill a buffer unless it already existed before editing
231 it with the Emacs server. If nil, kill only buffers as specified by
232 `server-temp-file-regexp'.
233 Please note that only buffers that still have a client are killed,
234 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
240 (or (assq 'server-buffer-clients minor-mode-alist
)
241 (push '(server-buffer-clients " Server") minor-mode-alist
))
243 (defvar server-existing-buffer nil
244 "Non-nil means the buffer existed before the server was asked to visit it.
245 This means that the server should not kill the buffer when you say you
246 are done with it in the server.")
247 (make-variable-buffer-local 'server-existing-buffer
)
249 (defcustom server-name
"server"
250 "The name of the Emacs server, if this Emacs process creates one.
251 The command `server-start' makes use of this. It should not be
252 changed while a server is running."
257 ;; We do not use `temporary-file-directory' here, because emacsclient
258 ;; does not read the init file.
259 (defvar server-socket-dir
260 (and (featurep 'make-network-process
'(:family local
))
261 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
262 "The directory in which to place the server socket.
263 If local sockets are not supported, this is nil.")
265 (defun server-clients-with (property value
)
266 "Return a list of clients with PROPERTY set to VALUE."
268 (dolist (proc server-clients
)
269 (when (equal value
(process-get proc property
))
273 (defun server-add-client (proc)
274 "Create a client for process PROC, if it doesn't already have one.
275 New clients have no properties."
276 (add-to-list 'server-clients proc
))
278 (defmacro server-with-environment
(env vars
&rest body
)
279 "Evaluate BODY with environment variables VARS set to those in ENV.
280 The environment variables are then restored to their previous values.
282 VARS should be a list of strings.
283 ENV should be in the same format as `process-environment'."
285 (let ((var (make-symbol "var"))
286 (value (make-symbol "value")))
287 `(let ((process-environment process-environment
))
289 (let ((,value
(getenv-internal ,var
,env
)))
290 (push (if (stringp ,value
)
291 (concat ,var
"=" ,value
)
293 process-environment
)))
296 (defun server-delete-client (proc &optional noframe
)
297 "Delete PROC, including its buffers, terminals and frames.
298 If NOFRAME is non-nil, let the frames live.
299 Updates `server-clients'."
300 (server-log (concat "server-delete-client" (if noframe
" noframe")) proc
)
301 ;; Force a new lookup of client (prevents infinite recursion).
302 (when (memq proc server-clients
)
303 (let ((buffers (process-get proc
'buffers
)))
305 ;; Kill the client's buffers.
306 (dolist (buf buffers
)
307 (when (buffer-live-p buf
)
308 (with-current-buffer buf
309 ;; Kill the buffer if necessary.
310 (when (and (equal server-buffer-clients
312 (or (and server-kill-new-buffers
313 (not server-existing-buffer
))
314 (server-temp-file-p))
315 (not (buffer-modified-p)))
318 (progn (setq server-buffer-clients nil
)
319 (kill-buffer (current-buffer))
322 ;; Restore clients if user pressed C-g in `kill-buffer'.
323 (setq server-buffer-clients
(list proc
)))))))))
325 ;; Delete the client's frames.
327 (dolist (frame (frame-list))
328 (when (and (frame-live-p frame
)
329 (equal proc
(frame-parameter frame
'client
)))
330 ;; Prevent `server-handle-delete-frame' from calling us
332 (set-frame-parameter frame
'client nil
)
333 (delete-frame frame
))))
335 (setq server-clients
(delq proc server-clients
))
337 ;; Delete the client's tty, except on Windows (both GUI and console),
338 ;; where there's only one terminal and does not make sense to delete it.
339 (unless (eq system-type
'windows-nt
)
340 (let ((terminal (process-get proc
'terminal
)))
341 ;; Only delete the terminal if it is non-nil.
342 (when (and terminal
(eq (terminal-live-p terminal
) t
))
343 (delete-terminal terminal
))))
345 ;; Delete the client's process.
346 (if (eq (process-status proc
) 'open
)
347 (delete-process proc
))
349 (server-log "Deleted" proc
))))
351 (defvar server-log-time-function
'current-time-string
352 "Function to generate timestamps for `server-buffer'.")
354 (defconst server-buffer
" *server*"
355 "Buffer used internally by Emacs's server.
356 One use is to log the I/O for debugging purposes (see `server-log'),
357 the other is to provide a current buffer in which the process filter can
358 safely let-bind buffer-local variables like `default-directory'.")
360 (defvar server-log nil
361 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
363 (defun server-log (string &optional client
)
364 "If `server-log' is non-nil, log STRING to `server-buffer'.
365 If CLIENT is non-nil, add a description of it to the logged message."
367 (with-current-buffer (get-buffer-create server-buffer
)
368 (goto-char (point-max))
369 (insert (funcall server-log-time-function
)
372 ((listp client
) (format " %s: " (car client
)))
373 (t (format " %s: " client
)))
375 (or (bolp) (newline)))))
377 (defun server-sentinel (proc msg
)
378 "The process sentinel for Emacs server connections."
379 ;; If this is a new client process, set the query-on-exit flag to nil
380 ;; for this process (it isn't inherited from the server process).
381 (when (and (eq (process-status proc
) 'open
)
382 (process-query-on-exit-flag proc
))
383 (set-process-query-on-exit-flag proc nil
))
384 ;; Delete the associated connection file, if applicable.
385 ;; Although there's no 100% guarantee that the file is owned by the
386 ;; running Emacs instance, server-start uses server-running-p to check
387 ;; for possible servers before doing anything, so it *should* be ours.
388 (and (process-contact proc
:server
)
389 (eq (process-status proc
) 'closed
)
391 (delete-file (process-get proc
:server-file
))))
392 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
393 (server-delete-client proc
))
395 (defun server--on-display-p (frame display
)
396 (and (equal (frame-parameter frame
'display
) display
)
397 ;; Note: TTY frames still get a `display' parameter set to the value of
398 ;; $DISPLAY. This is useful when running from that tty frame
399 ;; sub-processes that want to connect to the X server, but that means we
400 ;; have to be careful here not to be tricked into thinking those frames
402 (not (eq (framep frame
) t
))))
404 (defun server-select-display (display)
405 ;; If the current frame is on `display' we're all set.
406 ;; Similarly if we are unable to open frames on other displays, there's
407 ;; nothing more we can do.
408 (unless (or (not (fboundp 'make-frame-on-display
))
409 (server--on-display-p (selected-frame) display
))
410 ;; Otherwise, look for an existing frame there and select it.
411 (dolist (frame (frame-list))
412 (when (server--on-display-p frame display
)
413 (select-frame frame
)))
414 ;; If there's no frame on that display yet, create and select one.
415 (unless (server--on-display-p (selected-frame) display
)
416 (let* ((buffer (generate-new-buffer " *server-dummy*"))
417 (frame (make-frame-on-display
419 ;; Make it display (and remember) some dummy buffer, so
420 ;; we can detect later if the frame is in use or not.
421 `((server-dummy-buffer .
,buffer
)
422 ;; This frame may be deleted later (see
423 ;; server-unselect-display) so we want it to be as
424 ;; unobtrusive as possible.
425 (visibility . nil
)))))
427 (set-window-buffer (selected-window) buffer
)
430 (defun server-unselect-display (frame)
431 (when (frame-live-p frame
)
432 ;; If the temporary frame is in use (displays something real), make it
433 ;; visible. If not (which can happen if the user's customizations call
434 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
435 ;; the last real frame is deleted.
437 ;; Rewritten to avoid inadvertently killing the current buffer after
438 ;; `delete-frame' removed FRAME (Bug#10729).
439 (let ((buffer (frame-parameter frame
'server-dummy-buffer
)))
440 (if (and (one-window-p 'nomini frame
)
441 (eq (window-buffer (frame-first-window frame
)) buffer
))
442 ;; The temp frame still only shows one buffer, and that is the
443 ;; internal temp buffer.
445 (set-frame-parameter frame
'visibility t
)
446 (set-frame-parameter frame
'server-dummy-buffer nil
))
447 (when (buffer-live-p buffer
)
448 (kill-buffer buffer
)))))
450 (defun server-handle-delete-frame (frame)
451 "Delete the client connection when the emacsclient frame is deleted.
452 \(To be used from `delete-frame-functions'.)"
453 (let ((proc (frame-parameter frame
'client
)))
454 (when (and (frame-live-p frame
)
456 ;; See if this is the last frame for this client.
457 (>= 1 (let ((frame-num 0))
458 (dolist (f (frame-list))
459 (when (eq proc
(frame-parameter f
'client
))
460 (setq frame-num
(1+ frame-num
))))
462 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
463 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
465 (defun server-handle-suspend-tty (terminal)
466 "Notify the client process that its tty device is suspended."
467 (dolist (proc (server-clients-with 'terminal terminal
))
468 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
)
471 (server-send-string proc
"-suspend \n")
472 (file-error ;The pipe/socket was closed.
473 (ignore-errors (server-delete-client proc
))))))
475 (defun server-unquote-arg (arg)
476 "Remove &-quotation from ARG.
477 See `server-quote-arg' and `server-process-filter'."
478 (replace-regexp-in-string
487 (defun server-quote-arg (arg)
488 "In ARG, insert a & before each &, each space, each newline, and -.
489 Change spaces to underscores, too, so that the return value never
492 See `server-unquote-arg' and `server-process-filter'."
493 (replace-regexp-in-string
494 "[-&\n ]" (lambda (s)
502 (defun server-send-string (proc string
)
503 "A wrapper around `process-send-string' for logging."
504 (server-log (concat "Sent " string
) proc
)
505 (process-send-string proc string
))
507 (defun server-ensure-safe-dir (dir)
508 "Make sure DIR is a directory with no race-condition issues.
509 Creates the directory if necessary and makes sure:
510 - there's no symlink involved
512 - it's not readable/writable by anybody else."
513 (setq dir
(directory-file-name dir
))
514 (let ((attrs (file-attributes dir
'integer
)))
516 (cl-letf (((default-file-modes) ?
\700)) (make-directory dir t
))
517 (setq attrs
(file-attributes dir
'integer
)))
519 ;; Check that it's safe for use.
520 (let* ((uid (nth 2 attrs
))
521 (w32 (eq system-type
'windows-nt
))
523 ((not (eq t
(car attrs
))) nil
) ; is a dir?
524 ((and w32
(zerop uid
)) ; on FAT32?
527 (format "Using `%s' to store Emacs-server authentication files.
528 Directories on FAT32 filesystems are NOT secure against tampering.
529 See variable `server-auth-dir' for details."
530 (file-name-as-directory dir
))
533 ((and (/= uid
(user-uid)) ; is the dir ours?
535 ;; Files created on Windows by Administrator
536 ;; (RID=500) have the Administrators (RID=544)
537 ;; group recorded as the owner.
538 (/= uid
544) (/= (user-uid) 500)))
541 (t ; else, check permissions
542 (zerop (logand ?
\077 (file-modes dir
)))))))
544 (error "The directory `%s' is unsafe" dir
)))))
546 (defun server-generate-key ()
547 "Generate and return a random authentication key.
548 The key is a 64-byte string of random chars in the range `!'..`~'.
549 If called interactively, also inserts it into current buffer."
553 collect
(+ 33 (random 94)) into auth
554 finally return
(concat auth
))))
555 (if (called-interactively-p 'interactive
)
559 (defun server-get-auth-key ()
560 "Return server's authentication key.
562 If `server-auth-key' is nil, just call `server-generate-key'.
563 Otherwise, if `server-auth-key' is a valid key, return it.
564 If the key is not valid, signal an error."
566 (if (string-match-p "^[!-~]\\{64\\}$" server-auth-key
)
568 (error "The key '%s' is invalid" server-auth-key
))
569 (server-generate-key)))
572 (defun server-start (&optional leave-dead inhibit-prompt
)
573 "Allow this Emacs process to be a server for client processes.
574 This starts a server communications subprocess through which client
575 \"editors\" can send your editing commands to this Emacs job.
576 To use the server, set up the program `emacsclient' in the Emacs
577 distribution as your standard \"editor\".
579 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
580 kill any existing server communications subprocess.
582 If a server is already running, restart it. If clients are
583 running, ask the user for confirmation first, unless optional
584 argument INHIBIT-PROMPT is non-nil.
586 To force-start a server, do \\[server-force-delete] and then
589 (when (or (not server-clients
)
590 ;; Ask the user before deleting existing clients---except
591 ;; when we can't get user input, which may happen when
592 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
595 (null (cdr (frame-list)))
596 (eq (selected-frame) terminal-frame
))
600 "The current server still has clients; delete them? "))))
601 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
602 (server-file (expand-file-name server-name server-dir
)))
605 (ignore-errors (delete-process server-process
)))
606 ;; Delete the socket files made by previous server invocations.
607 (if (not (eq t
(server-running-p server-name
)))
608 ;; Remove any leftover socket or authentication file
610 (let (delete-by-moving-to-trash)
611 (delete-file server-file
)))
612 (setq server-mode nil
) ;; already set by the minor mode code
615 (concat "Unable to start the Emacs server.\n"
616 (format "There is an existing Emacs server, named %S.\n"
618 "To start the server in this Emacs process, stop the existing
619 server or call `M-x server-force-delete' to forcibly disconnect it.")
622 ;; If this Emacs already had a server, clear out associated status.
623 (while server-clients
624 (server-delete-client (car server-clients
)))
625 ;; Now any previous server is properly stopped.
628 (unless (eq t leave-dead
) (server-log (message "Server stopped")))
629 (setq server-process nil
))
630 ;; Make sure there is a safe directory in which to place the socket.
631 (server-ensure-safe-dir server-dir
)
633 (server-log (message "Restarting server")))
634 (cl-letf (((default-file-modes) ?
\700))
635 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
636 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
637 (add-hook 'kill-buffer-query-functions
638 'server-kill-buffer-query-function
)
639 (add-hook 'kill-emacs-query-functions
640 'server-kill-emacs-query-function
)
641 (add-hook 'kill-emacs-hook
'server-force-stop
) ;Cleanup upon exit.
643 (apply #'make-network-process
647 :sentinel
'server-sentinel
648 :filter
'server-process-filter
649 ;; We must receive file names without being decoded.
650 ;; Those are decoded by server-process-filter according
651 ;; to file-name-coding-system. Also don't get
652 ;; confused by CRs since we don't quote them.
653 :coding
'raw-text-unix
654 ;; The other args depend on the kind of socket used.
656 (list :family
'ipv4
;; We're not ready for IPv6 yet
657 :service
(or server-port t
)
658 :host
(or server-host
'local
)
659 :plist
'(:authenticated nil
))
662 :plist
'(:authenticated t
)))))
663 (unless server-process
(error "Could not start server process"))
664 (process-put server-process
:server-file server-file
)
666 (let ((auth-key (server-get-auth-key)))
667 (process-put server-process
:auth-key auth-key
)
668 (with-temp-file server-file
669 (set-buffer-multibyte nil
)
670 (setq buffer-file-coding-system
'no-conversion
)
671 (insert (format-network-address
672 (process-contact server-process
:local
))
673 " " (number-to-string (emacs-pid)) ; Kept for compatibility
674 "\n" auth-key
)))))))))
676 (defun server-force-stop ()
677 "Kill all connections to the current server.
678 This function is meant to be called from `kill-emacs-hook'."
682 (defun server-force-delete (&optional name
)
683 "Unconditionally delete connection file for server NAME.
684 If server is running, it is first stopped.
685 NAME defaults to `server-name'. With argument, ask for NAME."
687 (list (if current-prefix-arg
688 (read-string "Server name: " nil nil server-name
))))
689 (when server-mode
(with-temp-message nil
(server-mode -
1)))
690 (let ((file (expand-file-name (or name server-name
)
693 server-socket-dir
))))
695 (let (delete-by-moving-to-trash)
697 (message "Connection file %S deleted" file
))
699 (message "No connection file %S" file
)))))
701 (defun server-running-p (&optional name
)
702 "Test whether server NAME is running.
705 nil the server is definitely not running.
706 t the server seems to be running.
707 something else we cannot determine whether it's running without using
708 commands which may have to wait for a long time."
709 (unless name
(setq name server-name
))
713 (insert-file-contents-literally (expand-file-name name server-auth-dir
))
714 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
717 (string-to-number (match-string 1))))
721 (make-network-process
722 :name
"server-client-test" :family
'local
:server nil
:noquery t
723 :service
(expand-file-name name server-socket-dir
)))
728 (define-minor-mode server-mode
730 With a prefix argument ARG, enable Server mode if ARG is
731 positive, and disable it otherwise. If called from Lisp, enable
732 Server mode if ARG is omitted or nil.
734 Server mode runs a process that accepts commands from the
735 `emacsclient' program. See Info node `Emacs server' and
736 `server-start' for details."
740 ;; Fixme: Should this check for an existing server socket and do
741 ;; nothing if there is one (for multiple Emacs sessions)?
742 (server-start (not server-mode
)))
744 (defun server-eval-and-print (expr proc
)
745 "Eval EXPR and send the result back to client PROC."
746 ;; While we're running asynchronously (from a process filter), it is likely
747 ;; that the emacsclient command was run in response to a user
748 ;; action, so the user probably knows that Emacs is processing this
749 ;; emacsclient request, so if we get a C-g it's likely that the user
750 ;; intended it to interrupt us rather than interrupt whatever Emacs
751 ;; was doing before it started handling the process filter.
752 ;; Hence `with-local-quit' (bug#6585).
753 (let ((v (with-local-quit (eval (car (read-from-string expr
))))))
756 (let ((standard-output (current-buffer)))
758 (let ((text (buffer-substring-no-properties
759 (point-min) (point-max))))
760 (server-reply-print (server-quote-arg text
) proc
)))))))
762 (defconst server-msg-size
1024
763 "Maximum size of a message sent to a client.")
765 (defun server-reply-print (qtext proc
)
766 "Send a `-print QTEXT' command to client PROC.
767 QTEXT must be already quoted.
768 This handles splitting the command if it would be bigger than
770 (let ((prefix "-print ")
772 (while (> (+ (length qtext
) (length prefix
) 1) server-msg-size
)
773 ;; We have to split the string
774 (setq part
(substring qtext
0 (- server-msg-size
(length prefix
) 1)))
775 ;; Don't split in the middle of a quote sequence
776 (if (string-match "\\(^\\|[^&]\\)\\(&&\\)+$" part
)
777 ;; There is an uneven number of & at the end
778 (setq part
(substring part
0 -
1)))
779 (setq qtext
(substring qtext
(length part
)))
780 (server-send-string proc
(concat prefix part
"\n"))
781 (setq prefix
"-print-nonl "))
782 (server-send-string proc
(concat prefix qtext
"\n"))))
784 (defun server-create-tty-frame (tty type proc
)
786 (error "Invalid terminal device"))
788 (error "Invalid terminal type"))
789 (add-to-list 'frame-inherited-parameters
'client
)
791 (server-with-environment (process-get proc
'env
)
792 '("LANG" "LC_CTYPE" "LC_ALL"
793 ;; For tgetent(3); list according to ncurses(3).
794 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
795 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
796 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
797 "TERMINFO_DIRS" "TERMPATH"
799 "COLORFGBG" "COLORTERM")
800 (make-frame `((window-system . nil
)
803 ;; Ignore nowait here; we always need to
804 ;; clean up opened ttys when the client dies.
806 ;; This is a leftover from an earlier
807 ;; attempt at making it possible for process
808 ;; run in the server process to use the
809 ;; environment of the client process.
810 ;; It has no effect now and to make it work
811 ;; we'd need to decide how to make
812 ;; process-environment interact with client
813 ;; envvars, and then to change the
814 ;; C functions `child_setup' and
815 ;; `getenv_internal' accordingly.
816 (environment .
,(process-get proc
'env
)))))))
818 ;; ttys don't use the `display' parameter, but callproc.c does to set
819 ;; the DISPLAY environment on subprocesses.
820 (set-frame-parameter frame
'display
821 (getenv-internal "DISPLAY" (process-get proc
'env
)))
823 (process-put proc
'frame frame
)
824 (process-put proc
'terminal
(frame-terminal frame
))
827 (defun server-create-window-system-frame (display nowait proc parent-id
828 &optional parameters
)
829 (add-to-list 'frame-inherited-parameters
'client
)
830 (if (not (fboundp 'make-frame-on-display
))
832 ;; This emacs does not support X.
833 (server-log "Window system unsupported" proc
)
834 (server-send-string proc
"-window-system-unsupported \n")
836 ;; Flag frame as client-created, but use a dummy client.
837 ;; This will prevent the frame from being deleted when
838 ;; emacsclient quits while also preventing
839 ;; `server-save-buffers-kill-terminal' from unexpectedly
840 ;; killing emacs on that frame.
841 (let* ((params `((client .
,(if nowait
'nowait proc
))
842 ;; This is a leftover, see above.
843 (environment .
,(process-get proc
'env
))
846 (frame-parameter nil
'display
)
848 (error "Please specify display")))
851 (push (cons 'parent-id
(string-to-number parent-id
)) params
))
852 (setq frame
(make-frame-on-display display params
))
853 (server-log (format "%s created" frame
) proc
)
855 (process-put proc
'frame frame
)
856 (process-put proc
'terminal
(frame-terminal frame
))
859 (defun server-goto-toplevel (proc)
861 ;; If we're running isearch, we must abort it to allow Emacs to
862 ;; display the buffer and switch to it.
863 (dolist (buffer (buffer-list))
864 (with-current-buffer buffer
865 (when (bound-and-true-p isearch-mode
)
867 ;; Signaled by isearch-cancel.
868 (quit (message nil
)))
869 (when (> (recursion-depth) 0)
870 ;; We're inside a minibuffer already, so if the emacs-client is trying
871 ;; to open a frame on a new display, we might end up with an unusable
872 ;; frame because input from that display will be blocked (until exiting
873 ;; the minibuffer). Better exit this minibuffer right away.
874 ;; Similarly with recursive-edits such as the splash screen.
875 (run-with-timer 0 nil
(lambda () (server-execute-continuation proc
)))
878 ;; We use various special properties on process objects:
879 ;; - `env' stores the info about the environment of the emacsclient process.
880 ;; - `continuation' is a no-arg function that we need to execute. It contains
881 ;; commands we wanted to execute in some earlier invocation of the process
882 ;; filter but that we somehow were unable to process at that time
883 ;; (e.g. because we first need to throw to the toplevel).
885 (defun server-execute-continuation (proc)
886 (let ((continuation (process-get proc
'continuation
)))
887 (process-put proc
'continuation nil
)
888 (if continuation
(ignore-errors (funcall continuation
)))))
890 (cl-defun server-process-filter (proc string
)
891 "Process a request from the server to edit some files.
892 PROC is the server process. STRING consists of a sequence of
893 commands prefixed by a dash. Some commands have arguments;
894 these are &-quoted and need to be decoded by `server-unquote-arg'.
895 The filter parses and executes these commands.
897 To illustrate the protocol, here is an example command that
898 emacsclient sends to create a new X frame (note that the whole
899 sequence is sent on a single line):
901 -env HOME=/home/lorentey
903 ... lots of other -env commands
907 The following commands are accepted by the server:
910 Authenticate the client using the secret authentication string
914 An environment variable on the client side.
917 The current working directory of the client process.
920 Forbid the creation of new frames.
922 `-frame-parameters ALIST'
923 Set the parameters of the created frame.
926 Request that the next frame created should not be
927 associated with this client.
930 Set the display name to open X frames on.
932 `-position LINE[:COLUMN]'
933 Go to the given line and column number
934 in the next file opened.
937 Load the given file in the current frame.
940 Evaluate EXPR as a Lisp expression and return the
941 result in -print commands.
946 `-tty DEVICENAME TYPE'
947 Open a new tty frame at the client.
950 Suspend this tty frame. The client sends this string in
951 response to SIGTSTP and SIGTTOU. The server must cease all I/O
952 on this tty until it gets a -resume command.
955 Resume this tty frame. The client sends this string when it
956 gets the SIGCONT signal and it is the foreground process on its
960 Do nothing, but put the comment in the server log.
961 Useful for debugging.
964 The following commands are accepted by the client:
967 Describes the process id of the Emacs process;
968 used to forward window change signals to it.
970 `-window-system-unsupported'
971 Signals that the server does not support creating X frames;
972 the client must try again with a tty frame.
975 Print STRING on stdout. Used to send values
979 Print STRING on stdout. Used to continue a
980 preceding -print command that would be too big to send
984 Signal an error and delete process PROC.
987 Suspend this terminal, i.e., stop the client process.
988 Sent when the user presses C-z."
989 (server-log (concat "Received " string
) proc
)
990 ;; First things first: let's check the authentication
991 (unless (process-get proc
:authenticated
)
992 (if (and (string-match "-auth \\([!-~]+\\)\n?" string
)
993 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
995 (setq string
(substring string
(match-end 0)))
996 (process-put proc
:authenticated t
)
997 (server-log "Authentication successful" proc
))
998 (server-log "Authentication failed" proc
)
1000 proc
(concat "-error " (server-quote-arg "Authentication failed")))
1001 ;; Before calling `delete-process', give emacsclient time to
1002 ;; receive the error string and shut down on its own.
1004 (delete-process proc
)
1005 ;; We return immediately.
1006 (cl-return-from server-process-filter
)))
1007 (let ((prev (process-get proc
'previous-string
)))
1009 (setq string
(concat prev string
))
1010 (process-put proc
'previous-string nil
)))
1013 (server-add-client proc
)
1015 (server-send-string proc
(concat "-emacs-pid "
1016 (number-to-string (emacs-pid)) "\n"))
1017 (if (not (string-match "\n" string
))
1018 ;; Save for later any partial line that remains.
1019 (when (> (length string
) 0)
1020 (process-put proc
'previous-string string
))
1022 ;; In earlier versions of server.el (where we used an `emacsserver'
1023 ;; process), there could be multiple lines. Nowadays this is not
1024 ;; supported any more.
1025 (cl-assert (eq (match-end 0) (length string
)))
1026 (let ((request (substring string
0 (match-beginning 0)))
1027 (coding-system (and (default-value 'enable-multibyte-characters
)
1028 (or file-name-coding-system
1029 default-file-name-coding-system
)))
1030 nowait
; t if emacsclient does not want to wait for us.
1031 frame
; Frame opened for the client (if any).
1032 display
; Open frame on this display.
1033 parent-id
; Window ID for XEmbed
1034 dontkill
; t if client should not be killed.
1038 frame-parameters
;parameters for newly created frame
1039 tty-name
; nil, `window-system', or the tty name.
1044 ;; Remove this line from STRING.
1045 (setq string
(substring string
(match-end 0)))
1047 (mapcar 'server-unquote-arg
(split-string request
" " t
)))
1049 (pcase (pop args-left
)
1050 ;; -version CLIENT-VERSION: obsolete at birth.
1051 (`"-version" (pop args-left
))
1053 ;; -nowait: Emacsclient won't wait for a result.
1054 (`"-nowait" (setq nowait t
))
1056 ;; -current-frame: Don't create frames.
1057 (`"-current-frame" (setq use-current-frame t
))
1059 ;; -frame-parameters: Set frame parameters
1060 (`"-frame-parameters"
1061 (let ((alist (pop args-left
)))
1063 (setq alist
(decode-coding-string alist coding-system
)))
1064 (setq frame-parameters
(car (read-from-string alist
)))))
1066 ;; -display DISPLAY:
1067 ;; Open X frames on the given display instead of the default.
1069 (setq display
(pop args-left
))
1070 (if (zerop (length display
)) (setq display nil
)))
1073 ;; Open X frame within window ID, via XEmbed.
1075 (setq parent-id
(pop args-left
))
1076 (if (zerop (length parent-id
)) (setq parent-id nil
)))
1078 ;; -window-system: Open a new X frame.
1080 (if (fboundp 'x-create-frame
)
1082 tty-name
'window-system
)))
1084 ;; -resume: Resume a suspended tty frame.
1086 (let ((terminal (process-get proc
'terminal
)))
1089 (when (eq (terminal-live-p terminal
) t
)
1090 (resume-tty terminal
)))
1093 ;; -suspend: Suspend the client's frame. (In case we
1094 ;; get out of sync, and a C-z sends a SIGTSTP to
1097 (let ((terminal (process-get proc
'terminal
)))
1100 (when (eq (terminal-live-p terminal
) t
)
1101 (suspend-tty terminal
)))
1104 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1105 ;; (The given comment appears in the server log.)
1110 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1111 ;; (But if we see -window-system later, use that.)
1113 (setq tty-name
(pop args-left
)
1114 tty-type
(pop args-left
)
1115 dontkill
(or dontkill
1116 (not use-current-frame
)))
1117 ;; On Windows, emacsclient always asks for a tty frame.
1118 ;; If running a GUI server, force the frame type to GUI.
1119 (when (eq window-system
'w32
)
1120 (push "-window-system" args-left
)))
1122 ;; -position LINE[:COLUMN]: Set point to the given
1123 ;; position in the next file.
1125 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1127 (error "Invalid -position command in client args"))
1128 (let ((arg (pop args-left
)))
1130 (cons (string-to-number (match-string 1 arg
))
1131 (string-to-number (or (match-string 2 arg
)
1134 ;; -file FILENAME: Load the given file.
1136 (let ((file (pop args-left
)))
1138 (setq file
(decode-coding-string file coding-system
)))
1139 (setq file
(expand-file-name file dir
))
1140 (push (cons file filepos
) files
)
1141 (server-log (format "New file: %s %s"
1142 file
(or filepos
"")) proc
))
1145 ;; -eval EXPR: Evaluate a Lisp expression.
1147 (if use-current-frame
1148 (setq use-current-frame
'always
))
1149 (let ((expr (pop args-left
)))
1151 (setq expr
(decode-coding-string expr coding-system
)))
1152 (push (lambda () (server-eval-and-print expr proc
))
1154 (setq filepos nil
)))
1156 ;; -env NAME=VALUE: An environment variable.
1158 (let ((var (pop args-left
)))
1159 ;; XXX Variables should be encoded as in getenv/setenv.
1160 (process-put proc
'env
1161 (cons var
(process-get proc
'env
)))))
1163 ;; -dir DIRNAME: The cwd of the emacsclient process.
1165 (setq dir
(pop args-left
))
1167 (setq dir
(decode-coding-string dir coding-system
)))
1168 (setq dir
(command-line-normalize-file-name dir
))
1169 (process-put proc
'server-client-directory dir
))
1172 (arg (error "Unknown command: %s" arg
))))
1174 ;; If both -no-wait and -tty are given with file or sexp
1175 ;; arguments, use an existing frame.
1177 (not (eq tty-name
'window-system
))
1179 (setq use-current-frame t
))
1183 ((and use-current-frame
1184 (or (eq use-current-frame
'always
)
1185 ;; We can't use the Emacs daemon's
1188 (null (cdr (frame-list)))
1189 (eq (selected-frame)
1191 (setq tty-name nil tty-type nil
)
1192 (if display
(server-select-display display
)))
1193 ((eq tty-name
'window-system
)
1194 (server-create-window-system-frame display nowait proc
1197 ;; When resuming on a tty, tty-name is nil.
1199 (server-create-tty-frame tty-name tty-type proc
))))
1204 (with-current-buffer (get-buffer-create server-buffer
)
1205 ;; Use the same cwd as the emacsclient, if possible, so
1206 ;; relative file names work correctly, even in `eval'.
1207 (let ((default-directory
1208 (if (and dir
(file-directory-p dir
))
1209 dir default-directory
)))
1210 (server-execute proc files nowait commands
1211 dontkill frame tty-name
)))))
1213 (when (or frame files
)
1214 (server-goto-toplevel proc
))
1216 (server-execute-continuation proc
))))
1218 (error (server-return-error proc err
))))
1220 (defun server-execute (proc files nowait commands dontkill frame tty-name
)
1221 ;; This is run from timers and process-filters, i.e. "asynchronously".
1222 ;; But w.r.t the user, this is not really asynchronous since the timer
1223 ;; is run after 0s and the process-filter is run in response to the
1224 ;; user running `emacsclient'. So it is OK to override the
1225 ;; inhibit-quit flag, which is good since `commands' (as well as
1226 ;; find-file-noselect via the major-mode) can run arbitrary code,
1227 ;; including code that needs to wait.
1230 (let ((buffers (server-visit-files files proc nowait
)))
1231 (mapc 'funcall
(nreverse commands
))
1233 ;; If we were told only to open a new client, obey
1234 ;; `initial-buffer-choice' if it specifies a file.
1235 (unless (or files commands
)
1236 (if (stringp initial-buffer-choice
)
1237 (find-file initial-buffer-choice
)
1238 (switch-to-buffer (get-buffer-create "*scratch*")
1241 ;; Delete the client if necessary.
1244 ;; Client requested nowait; return immediately.
1245 (server-log "Close nowait client" proc
)
1246 (server-delete-client proc
))
1247 ((and (not dontkill
) (null buffers
))
1248 ;; This client is empty; get rid of it immediately.
1249 (server-log "Close empty client" proc
)
1250 (server-delete-client proc
)))
1252 ((or isearch-mode
(minibufferp))
1254 ((and frame
(null buffers
))
1255 (message "%s" (substitute-command-keys
1256 "When done with this frame, type \\[delete-frame]")))
1257 ((not (null buffers
))
1258 (server-switch-buffer (car buffers
) nil
(cdr (car files
)))
1259 (run-hooks 'server-switch-hook
)
1261 (message "%s" (substitute-command-keys
1262 "When done with a buffer, type \\[server-edit]")))))
1263 (when (and frame
(null tty-name
))
1264 (server-unselect-display frame
)))
1266 (when (eq (car err
) 'quit
)
1267 (message "Quit emacsclient request"))
1268 (server-return-error proc err
)))))
1270 (defun server-return-error (proc err
)
1273 proc
(concat "-error " (server-quote-arg
1274 (error-message-string err
))))
1275 (server-log (error-message-string err
) proc
)
1276 ;; Before calling `delete-process', give emacsclient time to
1277 ;; receive the error string and shut down on its own.
1279 (delete-process proc
)))
1281 (defun server-goto-line-column (line-col)
1282 "Move point to the position indicated in LINE-COL.
1283 LINE-COL should be a pair (LINE . COL)."
1285 (goto-char (point-min))
1286 (forward-line (1- (car line-col
)))
1287 (let ((column-number (cdr line-col
)))
1288 (when (> column-number
0)
1289 (move-to-column (1- column-number
))))))
1291 (defun server-visit-files (files proc
&optional nowait
)
1292 "Find FILES and return a list of buffers created.
1293 FILES is an alist whose elements are (FILENAME . FILEPOS)
1294 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1295 PROC is the client that requested this operation.
1296 NOWAIT non-nil means this client is not waiting for the results,
1297 so don't mark these buffers specially, just visit them normally."
1298 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1299 (let ((last-nonmenu-event t
) client-record
)
1300 ;; Restore the current buffer afterward, but not using save-excursion,
1301 ;; because we don't want to save point in this buffer
1302 ;; if it happens to be one of those specified by the server.
1303 (save-current-buffer
1304 (dolist (file files
)
1305 ;; If there is an existing buffer modified or the file is
1306 ;; modified, revert it. If there is an existing buffer with
1307 ;; deleted file, offer to write it.
1308 (let* ((minibuffer-auto-raise (or server-raise-frame
1309 minibuffer-auto-raise
))
1311 (obuf (get-file-buffer filen
)))
1312 (add-to-history 'file-name-history filen
)
1315 (run-hooks 'pre-command-hook
)
1316 (set-buffer (find-file-noselect filen
)))
1318 ;; separately for each file, in sync with post-command hooks,
1319 ;; with the new buffer current:
1320 (run-hooks 'pre-command-hook
)
1321 (cond ((file-exists-p filen
)
1322 (when (not (verify-visited-file-modtime obuf
))
1323 (revert-buffer t nil
)))
1326 (concat "File no longer exists: " filen
1327 ", write buffer to file? "))
1328 (write-file filen
))))
1329 (unless server-buffer-clients
1330 (setq server-existing-buffer t
)))
1331 (server-goto-line-column (cdr file
))
1332 (run-hooks 'server-visit-hook
)
1333 ;; hooks may be specific to current buffer:
1334 (run-hooks 'post-command-hook
))
1336 ;; When the buffer is killed, inform the clients.
1337 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1338 (push proc server-buffer-clients
))
1339 (push (current-buffer) client-record
)))
1341 (process-put proc
'buffers
1342 (nconc (process-get proc
'buffers
) client-record
)))
1345 (defvar server-kill-buffer-running nil
1346 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1348 (defun server-buffer-done (buffer &optional for-killing
)
1349 "Mark BUFFER as \"done\" for its client(s).
1350 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1351 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1352 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1354 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1355 (let ((next-buffer nil
)
1357 (dolist (proc server-clients
)
1358 (let ((buffers (process-get proc
'buffers
)))
1360 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1361 (when buffers
; Ignore bufferless clients.
1362 (setq buffers
(delq buffer buffers
))
1363 ;; Delete all dead buffers from PROC.
1366 (not (buffer-live-p b
))
1367 (setq buffers
(delq b buffers
))))
1368 (process-put proc
'buffers buffers
)
1369 ;; If client now has no pending buffers,
1370 ;; tell it that it is done, and forget it entirely.
1372 (server-log "Close" proc
)
1374 ;; `server-delete-client' might delete the client's
1375 ;; frames, which might change the current buffer. We
1376 ;; don't want that (bug#640).
1377 (save-current-buffer
1378 (server-delete-client proc
))
1379 (server-delete-client proc
))))))
1380 (when (and (bufferp buffer
) (buffer-name buffer
))
1381 ;; We may or may not kill this buffer;
1382 ;; if we do, do not call server-buffer-done recursively
1383 ;; from kill-buffer-hook.
1384 (let ((server-kill-buffer-running t
))
1385 (with-current-buffer buffer
1386 (setq server-buffer-clients nil
)
1387 (run-hooks 'server-done-hook
))
1388 ;; Notice whether server-done-hook killed the buffer.
1389 (if (null (buffer-name buffer
))
1391 ;; Don't bother killing or burying the buffer
1392 ;; when we are called from kill-buffer.
1394 (when (and (not killed
)
1395 server-kill-new-buffers
1396 (with-current-buffer buffer
1397 (not server-existing-buffer
)))
1399 (bury-buffer buffer
)
1400 ;; Prevent kill-buffer from prompting (Bug#3696).
1401 (with-current-buffer buffer
1402 (set-buffer-modified-p nil
))
1403 (kill-buffer buffer
))
1405 (if (server-temp-file-p buffer
)
1407 (with-current-buffer buffer
1408 (set-buffer-modified-p nil
))
1409 (kill-buffer buffer
)
1411 (bury-buffer buffer
)))))))
1412 (list next-buffer killed
)))
1414 (defun server-temp-file-p (&optional buffer
)
1415 "Return non-nil if BUFFER contains a file considered temporary.
1416 These are files whose names suggest they are repeatedly
1417 reused to pass information to another program.
1419 The variable `server-temp-file-regexp' controls which filenames
1420 are considered temporary."
1421 (and (buffer-file-name buffer
)
1422 (string-match-p server-temp-file-regexp
(buffer-file-name buffer
))))
1424 (defun server-done ()
1425 "Offer to save current buffer, mark it as \"done\" for clients.
1426 This kills or buries the buffer, then returns a list
1427 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1428 as a suggestion for what to select next, or nil.
1429 KILLED is t if we killed BUFFER, which happens if it was created
1430 specifically for the clients and did not exist before their request for it."
1431 (when server-buffer-clients
1432 (if (server-temp-file-p)
1433 ;; For a temp file, save, and do make a non-numeric backup
1434 ;; (unless make-backup-files is nil).
1435 (let ((version-control nil
)
1436 (buffer-backed-up nil
))
1438 (when (and (buffer-modified-p)
1440 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1442 (server-buffer-done (current-buffer))))
1444 ;; Ask before killing a server buffer.
1445 ;; It was suggested to release its client instead,
1446 ;; but I think that is dangerous--the client would proceed
1447 ;; using whatever is on disk in that file. -- rms.
1448 (defun server-kill-buffer-query-function ()
1449 "Ask before killing a server buffer."
1450 (or (not server-buffer-clients
)
1452 (dolist (proc server-buffer-clients
)
1453 (when (and (memq proc server-clients
)
1454 (eq (process-status proc
) 'open
))
1457 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1458 (buffer-name (current-buffer))))))
1460 (defun server-kill-emacs-query-function ()
1461 "Ask before exiting Emacs if it has live clients."
1462 (or (not server-clients
)
1464 (dolist (proc server-clients
)
1465 (when (memq t
(mapcar 'buffer-live-p
(process-get
1467 (setq live-client t
)))
1469 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1471 (defun server-kill-buffer ()
1472 "Remove the current buffer from its clients' buffer list.
1473 Designed to be added to `kill-buffer-hook'."
1474 ;; Prevent infinite recursion if user has made server-done-hook
1475 ;; call kill-buffer.
1476 (or server-kill-buffer-running
1477 (and server-buffer-clients
1478 (let ((server-kill-buffer-running t
))
1479 (when server-process
1480 (server-buffer-done (current-buffer) t
))))))
1482 (defun server-edit (&optional arg
)
1483 "Switch to next server editing buffer; say \"Done\" for current buffer.
1484 If a server buffer is current, it is marked \"done\" and optionally saved.
1485 The buffer is also killed if it did not exist before the clients asked for it.
1486 When all of a client's buffers are marked as \"done\", the client is notified.
1488 Temporary files such as MH <draft> files are always saved and backed up,
1489 no questions asked. (The variable `make-backup-files', if nil, still
1490 inhibits a backup; you can set it locally in a particular buffer to
1491 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1492 which filenames are considered temporary.
1494 If invoked with a prefix argument, or if there is no server process running,
1495 starts server process and that is all. Invoked by \\[server-edit]."
1499 (not server-process
)
1500 (memq (process-status server-process
) '(signal exit
)))
1502 (server-clients (apply 'server-switch-buffer
(server-done)))
1503 (t (message "No server editing buffers exist"))))
1505 (defun server-switch-buffer (&optional next-buffer killed-one filepos
)
1506 "Switch to another buffer, preferably one that has a client.
1507 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1509 KILLED-ONE is t in a recursive call if we have already killed one
1510 temp-file server buffer. This means we should avoid the final
1511 \"switch to some other buffer\" since we've already effectively
1514 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1515 visit NEXT-BUFFER in an existing window. If non-nil, it should
1516 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1517 (if (null next-buffer
)
1519 (let ((rest server-clients
))
1520 (while (and rest
(not next-buffer
))
1521 (let ((proc (car rest
)))
1522 ;; Only look at frameless clients, or those in the selected
1524 (when (or (not (process-get proc
'frame
))
1525 (eq (process-get proc
'frame
) (selected-frame)))
1526 (setq next-buffer
(car (process-get proc
'buffers
))))
1527 (setq rest
(cdr rest
)))))
1528 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1529 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1530 ;; (switch-to-buffer (other-buffer))
1531 (message "No server buffers remain to edit")))
1532 (if (not (buffer-live-p next-buffer
))
1533 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1534 ;; and try the next surviving server buffer.
1535 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1536 ;; OK, we know next-buffer is live, let's display and select it.
1537 (if (functionp server-window
)
1538 (funcall server-window next-buffer
)
1539 (let ((win (get-buffer-window next-buffer
0)))
1540 (if (and win
(not server-window
))
1541 ;; The buffer is already displayed: just reuse the
1542 ;; window. If FILEPOS is non-nil, use it to replace the
1543 ;; window's own value of point.
1546 (set-buffer next-buffer
)
1548 (server-goto-line-column filepos
)))
1549 ;; Otherwise, let's find an appropriate window.
1550 (cond ((window-live-p server-window
)
1551 (select-window server-window
))
1552 ((framep server-window
)
1553 (unless (frame-live-p server-window
)
1554 (setq server-window
(make-frame)))
1555 (select-window (frame-selected-window server-window
))))
1556 (when (window-minibuffer-p (selected-window))
1557 (select-window (next-window nil
'nomini
0)))
1558 ;; Move to a non-dedicated window, if we have one.
1559 (when (window-dedicated-p (selected-window))
1561 (get-window-with-predicate
1563 (and (not (window-dedicated-p w
))
1564 (equal (frame-terminal (window-frame w
))
1565 (frame-terminal (selected-frame)))))
1566 'nomini
'visible
(selected-window))))
1568 (switch-to-buffer next-buffer
)
1569 ;; After all the above, we might still have ended up with
1570 ;; a minibuffer/dedicated-window (if there's no other).
1571 (error (pop-to-buffer next-buffer
)))))))
1572 (when server-raise-frame
1573 (select-frame-set-input-focus (window-frame (selected-window))))))
1576 (defun server-save-buffers-kill-terminal (arg)
1577 ;; Called from save-buffers-kill-terminal in files.el.
1578 "Offer to save each buffer, then kill the current client.
1579 With ARG non-nil, silently save all file-visiting buffers, then kill.
1581 If emacsclient was started with a list of filenames to edit, then
1582 only these files will be asked to be saved."
1583 (let ((proc (frame-parameter (selected-frame) 'client
)))
1584 (cond ((eq proc
'nowait
)
1585 ;; Nowait frames have no client buffer list.
1586 (if (cdr (frame-list))
1587 (progn (save-some-buffers arg
)
1589 ;; If we're the last frame standing, kill Emacs.
1590 (save-buffers-kill-emacs arg
)))
1592 (let ((buffers (process-get proc
'buffers
)))
1593 ;; If client is bufferless, emulate a normal Emacs exit
1594 ;; and offer to save all buffers. Otherwise, offer to
1595 ;; save only the buffers belonging to the client.
1598 (lambda () (memq (current-buffer) buffers
))
1600 (server-delete-client proc
)))
1601 (t (error "Invalid client frame")))))
1603 (define-key ctl-x-map
"#" 'server-edit
)
1605 (defun server-unload-function ()
1606 "Unload the server library."
1608 (substitute-key-definition 'server-edit nil ctl-x-map
)
1609 (save-current-buffer
1610 (dolist (buffer (buffer-list))
1612 (remove-hook 'kill-buffer-hook
'server-kill-buffer t
)))
1613 ;; continue standard unloading
1616 (defun server-eval-at (server form
)
1617 "Contact the Emacs server named SERVER and evaluate FORM there.
1618 Returns the result of the evaluation, or signals an error if it
1619 cannot contact the specified server. For example:
1620 \(server-eval-at \"server\" '(emacs-pid))
1621 returns the process ID of the Emacs instance running \"server\"."
1622 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
1623 (server-file (expand-file-name server server-dir
))
1624 (coding-system-for-read 'binary
)
1625 (coding-system-for-write 'binary
)
1626 address port secret process
)
1627 (unless (file-exists-p server-file
)
1628 (error "No such server: %s" server
))
1630 (when server-use-tcp
1631 (let ((coding-system-for-read 'no-conversion
))
1632 (insert-file-contents server-file
)
1633 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1634 (error "Invalid auth file"))
1635 (setq address
(match-string 1)
1636 port
(string-to-number (match-string 2)))
1638 (setq secret
(buffer-substring (point) (line-end-position)))
1640 (unless (setq process
(make-network-process
1642 :buffer
(current-buffer)
1644 :service
(if server-use-tcp port server-file
)
1645 :family
(if server-use-tcp
'ipv4
'local
)
1647 (error "Unable to contact the server"))
1649 (process-send-string process
(concat "-auth " secret
"\n")))
1650 (process-send-string process
1652 (server-quote-arg (format "%S" form
))
1654 (while (memq (process-status process
) '(open run
))
1655 (accept-process-output process
0 10))
1656 (goto-char (point-min))
1657 ;; If the result is nil, there's nothing in the buffer. If the
1658 ;; result is non-nil, it's after "-print ".
1660 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t
)
1663 (buffer-substring (point)
1664 (progn (skip-chars-forward "^\n")
1666 (if (not (equal answer
""))
1667 (read (decode-coding-string (server-unquote-arg answer
)
1668 'emacs-internal
)))))))
1673 ;;; server.el ends here