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 (let* ((display (or display
830 (frame-parameter nil
'display
)
831 (error "Please specify display.")))
832 (w (or (cdr (assq 'window-system parameters
))
833 (window-system-for-display display
))))
835 (unless (assq w window-system-initialization-alist
)
839 ;; Flag frame as client-created, but use a dummy client.
840 ;; This will prevent the frame from being deleted when
841 ;; emacsclient quits while also preventing
842 ;; `server-save-buffers-kill-terminal' from unexpectedly
843 ;; killing emacs on that frame.
844 (let* ((params `((client .
,(if nowait
'nowait proc
))
845 ;; This is a leftover, see above.
846 (environment .
,(process-get proc
'env
))
850 (push (cons 'parent-id
(string-to-number parent-id
)) params
))
851 (add-to-list 'frame-inherited-parameters
'client
)
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
))
860 (server-log "Window system unsupported" proc
)
861 (server-send-string proc
"-window-system-unsupported \n")
864 (defun server-goto-toplevel (proc)
866 ;; If we're running isearch, we must abort it to allow Emacs to
867 ;; display the buffer and switch to it.
868 (dolist (buffer (buffer-list))
869 (with-current-buffer buffer
870 (when (bound-and-true-p isearch-mode
)
872 ;; Signaled by isearch-cancel.
873 (quit (message nil
)))
874 (when (> (recursion-depth) 0)
875 ;; We're inside a minibuffer already, so if the emacs-client is trying
876 ;; to open a frame on a new display, we might end up with an unusable
877 ;; frame because input from that display will be blocked (until exiting
878 ;; the minibuffer). Better exit this minibuffer right away.
879 ;; Similarly with recursive-edits such as the splash screen.
880 (run-with-timer 0 nil
(lambda () (server-execute-continuation proc
)))
883 ;; We use various special properties on process objects:
884 ;; - `env' stores the info about the environment of the emacsclient process.
885 ;; - `continuation' is a no-arg function that we need to execute. It contains
886 ;; commands we wanted to execute in some earlier invocation of the process
887 ;; filter but that we somehow were unable to process at that time
888 ;; (e.g. because we first need to throw to the toplevel).
890 (defun server-execute-continuation (proc)
891 (let ((continuation (process-get proc
'continuation
)))
892 (process-put proc
'continuation nil
)
893 (if continuation
(ignore-errors (funcall continuation
)))))
895 (cl-defun server-process-filter (proc string
)
896 "Process a request from the server to edit some files.
897 PROC is the server process. STRING consists of a sequence of
898 commands prefixed by a dash. Some commands have arguments;
899 these are &-quoted and need to be decoded by `server-unquote-arg'.
900 The filter parses and executes these commands.
902 To illustrate the protocol, here is an example command that
903 emacsclient sends to create a new X frame (note that the whole
904 sequence is sent on a single line):
906 -env HOME=/home/lorentey
908 ... lots of other -env commands
912 The following commands are accepted by the server:
915 Authenticate the client using the secret authentication string
919 An environment variable on the client side.
922 The current working directory of the client process.
925 Forbid the creation of new frames.
927 `-frame-parameters ALIST'
928 Set the parameters of the created frame.
931 Request that the next frame created should not be
932 associated with this client.
935 Set the display name to open X frames on.
937 `-position LINE[:COLUMN]'
938 Go to the given line and column number
939 in the next file opened.
942 Load the given file in the current frame.
945 Evaluate EXPR as a Lisp expression and return the
946 result in -print commands.
951 `-tty DEVICENAME TYPE'
952 Open a new tty frame at the client.
955 Suspend this tty frame. The client sends this string in
956 response to SIGTSTP and SIGTTOU. The server must cease all I/O
957 on this tty until it gets a -resume command.
960 Resume this tty frame. The client sends this string when it
961 gets the SIGCONT signal and it is the foreground process on its
965 Do nothing, but put the comment in the server log.
966 Useful for debugging.
969 The following commands are accepted by the client:
972 Describes the process id of the Emacs process;
973 used to forward window change signals to it.
975 `-window-system-unsupported'
976 Signals that the server does not support creating X frames;
977 the client must try again with a tty frame.
980 Print STRING on stdout. Used to send values
984 Print STRING on stdout. Used to continue a
985 preceding -print command that would be too big to send
989 Signal an error and delete process PROC.
992 Suspend this terminal, i.e., stop the client process.
993 Sent when the user presses C-z."
994 (server-log (concat "Received " string
) proc
)
995 ;; First things first: let's check the authentication
996 (unless (process-get proc
:authenticated
)
997 (if (and (string-match "-auth \\([!-~]+\\)\n?" string
)
998 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
1000 (setq string
(substring string
(match-end 0)))
1001 (process-put proc
:authenticated t
)
1002 (server-log "Authentication successful" proc
))
1003 (server-log "Authentication failed" proc
)
1005 proc
(concat "-error " (server-quote-arg "Authentication failed")))
1006 ;; Before calling `delete-process', give emacsclient time to
1007 ;; receive the error string and shut down on its own.
1009 (delete-process proc
)
1010 ;; We return immediately.
1011 (cl-return-from server-process-filter
)))
1012 (let ((prev (process-get proc
'previous-string
)))
1014 (setq string
(concat prev string
))
1015 (process-put proc
'previous-string nil
)))
1018 (server-add-client proc
)
1020 (server-send-string proc
(concat "-emacs-pid "
1021 (number-to-string (emacs-pid)) "\n"))
1022 (if (not (string-match "\n" string
))
1023 ;; Save for later any partial line that remains.
1024 (when (> (length string
) 0)
1025 (process-put proc
'previous-string string
))
1027 ;; In earlier versions of server.el (where we used an `emacsserver'
1028 ;; process), there could be multiple lines. Nowadays this is not
1029 ;; supported any more.
1030 (cl-assert (eq (match-end 0) (length string
)))
1031 (let ((request (substring string
0 (match-beginning 0)))
1032 (coding-system (and (default-value 'enable-multibyte-characters
)
1033 (or file-name-coding-system
1034 default-file-name-coding-system
)))
1035 nowait
; t if emacsclient does not want to wait for us.
1036 frame
; Frame opened for the client (if any).
1037 display
; Open frame on this display.
1038 parent-id
; Window ID for XEmbed
1039 dontkill
; t if client should not be killed.
1043 frame-parameters
;parameters for newly created frame
1044 tty-name
; nil, `window-system', or the tty name.
1049 ;; Remove this line from STRING.
1050 (setq string
(substring string
(match-end 0)))
1052 (mapcar 'server-unquote-arg
(split-string request
" " t
)))
1054 (pcase (pop args-left
)
1055 ;; -version CLIENT-VERSION: obsolete at birth.
1056 (`"-version" (pop args-left
))
1058 ;; -nowait: Emacsclient won't wait for a result.
1059 (`"-nowait" (setq nowait t
))
1061 ;; -current-frame: Don't create frames.
1062 (`"-current-frame" (setq use-current-frame t
))
1064 ;; -frame-parameters: Set frame parameters
1065 (`"-frame-parameters"
1066 (let ((alist (pop args-left
)))
1068 (setq alist
(decode-coding-string alist coding-system
)))
1069 (setq frame-parameters
(car (read-from-string alist
)))))
1071 ;; -display DISPLAY:
1072 ;; Open X frames on the given display instead of the default.
1074 (setq display
(pop args-left
))
1075 (if (zerop (length display
)) (setq display nil
)))
1078 ;; Open X frame within window ID, via XEmbed.
1080 (setq parent-id
(pop args-left
))
1081 (if (zerop (length parent-id
)) (setq parent-id nil
)))
1083 ;; -window-system: Open a new X frame.
1085 (if (fboundp 'x-create-frame
)
1087 tty-name
'window-system
)))
1089 ;; -resume: Resume a suspended tty frame.
1091 (let ((terminal (process-get proc
'terminal
)))
1094 (when (eq (terminal-live-p terminal
) t
)
1095 (resume-tty terminal
)))
1098 ;; -suspend: Suspend the client's frame. (In case we
1099 ;; get out of sync, and a C-z sends a SIGTSTP to
1102 (let ((terminal (process-get proc
'terminal
)))
1105 (when (eq (terminal-live-p terminal
) t
)
1106 (suspend-tty terminal
)))
1109 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1110 ;; (The given comment appears in the server log.)
1115 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1116 ;; (But if we see -window-system later, use that.)
1118 (setq tty-name
(pop args-left
)
1119 tty-type
(pop args-left
)
1120 dontkill
(or dontkill
1121 (not use-current-frame
)))
1122 ;; On Windows, emacsclient always asks for a tty
1123 ;; frame. If running a GUI server, force the frame
1124 ;; type to GUI. (Cygwin is perfectly happy with
1125 ;; multi-tty support, so don't override the user's
1127 (when (and (eq system-type
'windows-nt
)
1128 (eq window-system
'w32
))
1129 (push "-window-system" args-left
)))
1131 ;; -position LINE[:COLUMN]: Set point to the given
1132 ;; position in the next file.
1134 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1136 (error "Invalid -position command in client args"))
1137 (let ((arg (pop args-left
)))
1139 (cons (string-to-number (match-string 1 arg
))
1140 (string-to-number (or (match-string 2 arg
)
1143 ;; -file FILENAME: Load the given file.
1145 (let ((file (pop args-left
)))
1147 (setq file
(decode-coding-string file coding-system
)))
1148 (setq file
(expand-file-name file dir
))
1149 (push (cons file filepos
) files
)
1150 (server-log (format "New file: %s %s"
1151 file
(or filepos
"")) proc
))
1154 ;; -eval EXPR: Evaluate a Lisp expression.
1156 (if use-current-frame
1157 (setq use-current-frame
'always
))
1158 (let ((expr (pop args-left
)))
1160 (setq expr
(decode-coding-string expr coding-system
)))
1161 (push (lambda () (server-eval-and-print expr proc
))
1163 (setq filepos nil
)))
1165 ;; -env NAME=VALUE: An environment variable.
1167 (let ((var (pop args-left
)))
1168 ;; XXX Variables should be encoded as in getenv/setenv.
1169 (process-put proc
'env
1170 (cons var
(process-get proc
'env
)))))
1172 ;; -dir DIRNAME: The cwd of the emacsclient process.
1174 (setq dir
(pop args-left
))
1176 (setq dir
(decode-coding-string dir coding-system
)))
1177 (setq dir
(command-line-normalize-file-name dir
))
1178 (process-put proc
'server-client-directory dir
))
1181 (arg (error "Unknown command: %s" arg
))))
1183 ;; If both -no-wait and -tty are given with file or sexp
1184 ;; arguments, use an existing frame.
1186 (not (eq tty-name
'window-system
))
1188 (setq use-current-frame t
))
1192 ((and use-current-frame
1193 (or (eq use-current-frame
'always
)
1194 ;; We can't use the Emacs daemon's
1197 (null (cdr (frame-list)))
1198 (eq (selected-frame)
1200 (setq tty-name nil tty-type nil
)
1201 (if display
(server-select-display display
)))
1202 ((eq tty-name
'window-system
)
1203 (server-create-window-system-frame display nowait proc
1206 ;; When resuming on a tty, tty-name is nil.
1208 (server-create-tty-frame tty-name tty-type proc
))))
1213 (with-current-buffer (get-buffer-create server-buffer
)
1214 ;; Use the same cwd as the emacsclient, if possible, so
1215 ;; relative file names work correctly, even in `eval'.
1216 (let ((default-directory
1217 (if (and dir
(file-directory-p dir
))
1218 dir default-directory
)))
1219 (server-execute proc files nowait commands
1220 dontkill frame tty-name
)))))
1222 (when (or frame files
)
1223 (server-goto-toplevel proc
))
1225 (server-execute-continuation proc
))))
1227 (error (server-return-error proc err
))))
1229 (defun server-execute (proc files nowait commands dontkill frame tty-name
)
1230 ;; This is run from timers and process-filters, i.e. "asynchronously".
1231 ;; But w.r.t the user, this is not really asynchronous since the timer
1232 ;; is run after 0s and the process-filter is run in response to the
1233 ;; user running `emacsclient'. So it is OK to override the
1234 ;; inhibit-quit flag, which is good since `commands' (as well as
1235 ;; find-file-noselect via the major-mode) can run arbitrary code,
1236 ;; including code that needs to wait.
1239 (let ((buffers (server-visit-files files proc nowait
)))
1240 (mapc 'funcall
(nreverse commands
))
1242 ;; If we were told only to open a new client, obey
1243 ;; `initial-buffer-choice' if it specifies a file.
1244 (unless (or files commands
)
1245 (if (stringp initial-buffer-choice
)
1246 (find-file initial-buffer-choice
)
1247 (switch-to-buffer (get-buffer-create "*scratch*")
1250 ;; Delete the client if necessary.
1253 ;; Client requested nowait; return immediately.
1254 (server-log "Close nowait client" proc
)
1255 (server-delete-client proc
))
1256 ((and (not dontkill
) (null buffers
))
1257 ;; This client is empty; get rid of it immediately.
1258 (server-log "Close empty client" proc
)
1259 (server-delete-client proc
)))
1261 ((or isearch-mode
(minibufferp))
1263 ((and frame
(null buffers
))
1264 (message "%s" (substitute-command-keys
1265 "When done with this frame, type \\[delete-frame]")))
1266 ((not (null buffers
))
1267 (server-switch-buffer (car buffers
) nil
(cdr (car files
)))
1268 (run-hooks 'server-switch-hook
)
1270 (message "%s" (substitute-command-keys
1271 "When done with a buffer, type \\[server-edit]")))))
1272 (when (and frame
(null tty-name
))
1273 (server-unselect-display frame
)))
1275 (when (eq (car err
) 'quit
)
1276 (message "Quit emacsclient request"))
1277 (server-return-error proc err
)))))
1279 (defun server-return-error (proc err
)
1282 proc
(concat "-error " (server-quote-arg
1283 (error-message-string err
))))
1284 (server-log (error-message-string err
) proc
)
1285 ;; Before calling `delete-process', give emacsclient time to
1286 ;; receive the error string and shut down on its own.
1288 (delete-process proc
)))
1290 (defun server-goto-line-column (line-col)
1291 "Move point to the position indicated in LINE-COL.
1292 LINE-COL should be a pair (LINE . COL)."
1294 (goto-char (point-min))
1295 (forward-line (1- (car line-col
)))
1296 (let ((column-number (cdr line-col
)))
1297 (when (> column-number
0)
1298 (move-to-column (1- column-number
))))))
1300 (defun server-visit-files (files proc
&optional nowait
)
1301 "Find FILES and return a list of buffers created.
1302 FILES is an alist whose elements are (FILENAME . FILEPOS)
1303 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1304 PROC is the client that requested this operation.
1305 NOWAIT non-nil means this client is not waiting for the results,
1306 so don't mark these buffers specially, just visit them normally."
1307 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1308 (let ((last-nonmenu-event t
) client-record
)
1309 ;; Restore the current buffer afterward, but not using save-excursion,
1310 ;; because we don't want to save point in this buffer
1311 ;; if it happens to be one of those specified by the server.
1312 (save-current-buffer
1313 (dolist (file files
)
1314 ;; If there is an existing buffer modified or the file is
1315 ;; modified, revert it. If there is an existing buffer with
1316 ;; deleted file, offer to write it.
1317 (let* ((minibuffer-auto-raise (or server-raise-frame
1318 minibuffer-auto-raise
))
1320 (obuf (get-file-buffer filen
)))
1321 (add-to-history 'file-name-history filen
)
1324 (run-hooks 'pre-command-hook
)
1325 (set-buffer (find-file-noselect filen
)))
1327 ;; separately for each file, in sync with post-command hooks,
1328 ;; with the new buffer current:
1329 (run-hooks 'pre-command-hook
)
1330 (cond ((file-exists-p filen
)
1331 (when (not (verify-visited-file-modtime obuf
))
1332 (revert-buffer t nil
)))
1335 (concat "File no longer exists: " filen
1336 ", write buffer to file? "))
1337 (write-file filen
))))
1338 (unless server-buffer-clients
1339 (setq server-existing-buffer t
)))
1340 (server-goto-line-column (cdr file
))
1341 (run-hooks 'server-visit-hook
)
1342 ;; hooks may be specific to current buffer:
1343 (run-hooks 'post-command-hook
))
1345 ;; When the buffer is killed, inform the clients.
1346 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1347 (push proc server-buffer-clients
))
1348 (push (current-buffer) client-record
)))
1350 (process-put proc
'buffers
1351 (nconc (process-get proc
'buffers
) client-record
)))
1354 (defvar server-kill-buffer-running nil
1355 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1357 (defun server-buffer-done (buffer &optional for-killing
)
1358 "Mark BUFFER as \"done\" for its client(s).
1359 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1360 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1361 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1363 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1364 (let ((next-buffer nil
)
1366 (dolist (proc server-clients
)
1367 (let ((buffers (process-get proc
'buffers
)))
1369 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1370 (when buffers
; Ignore bufferless clients.
1371 (setq buffers
(delq buffer buffers
))
1372 ;; Delete all dead buffers from PROC.
1375 (not (buffer-live-p b
))
1376 (setq buffers
(delq b buffers
))))
1377 (process-put proc
'buffers buffers
)
1378 ;; If client now has no pending buffers,
1379 ;; tell it that it is done, and forget it entirely.
1381 (server-log "Close" proc
)
1383 ;; `server-delete-client' might delete the client's
1384 ;; frames, which might change the current buffer. We
1385 ;; don't want that (bug#640).
1386 (save-current-buffer
1387 (server-delete-client proc
))
1388 (server-delete-client proc
))))))
1389 (when (and (bufferp buffer
) (buffer-name buffer
))
1390 ;; We may or may not kill this buffer;
1391 ;; if we do, do not call server-buffer-done recursively
1392 ;; from kill-buffer-hook.
1393 (let ((server-kill-buffer-running t
))
1394 (with-current-buffer buffer
1395 (setq server-buffer-clients nil
)
1396 (run-hooks 'server-done-hook
))
1397 ;; Notice whether server-done-hook killed the buffer.
1398 (if (null (buffer-name buffer
))
1400 ;; Don't bother killing or burying the buffer
1401 ;; when we are called from kill-buffer.
1403 (when (and (not killed
)
1404 server-kill-new-buffers
1405 (with-current-buffer buffer
1406 (not server-existing-buffer
)))
1408 (bury-buffer buffer
)
1409 ;; Prevent kill-buffer from prompting (Bug#3696).
1410 (with-current-buffer buffer
1411 (set-buffer-modified-p nil
))
1412 (kill-buffer buffer
))
1414 (if (server-temp-file-p buffer
)
1416 (with-current-buffer buffer
1417 (set-buffer-modified-p nil
))
1418 (kill-buffer buffer
)
1420 (bury-buffer buffer
)))))))
1421 (list next-buffer killed
)))
1423 (defun server-temp-file-p (&optional buffer
)
1424 "Return non-nil if BUFFER contains a file considered temporary.
1425 These are files whose names suggest they are repeatedly
1426 reused to pass information to another program.
1428 The variable `server-temp-file-regexp' controls which filenames
1429 are considered temporary."
1430 (and (buffer-file-name buffer
)
1431 (string-match-p server-temp-file-regexp
(buffer-file-name buffer
))))
1433 (defun server-done ()
1434 "Offer to save current buffer, mark it as \"done\" for clients.
1435 This kills or buries the buffer, then returns a list
1436 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1437 as a suggestion for what to select next, or nil.
1438 KILLED is t if we killed BUFFER, which happens if it was created
1439 specifically for the clients and did not exist before their request for it."
1440 (when server-buffer-clients
1441 (if (server-temp-file-p)
1442 ;; For a temp file, save, and do make a non-numeric backup
1443 ;; (unless make-backup-files is nil).
1444 (let ((version-control nil
)
1445 (buffer-backed-up nil
))
1447 (when (and (buffer-modified-p)
1449 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1451 (server-buffer-done (current-buffer))))
1453 ;; Ask before killing a server buffer.
1454 ;; It was suggested to release its client instead,
1455 ;; but I think that is dangerous--the client would proceed
1456 ;; using whatever is on disk in that file. -- rms.
1457 (defun server-kill-buffer-query-function ()
1458 "Ask before killing a server buffer."
1459 (or (not server-buffer-clients
)
1461 (dolist (proc server-buffer-clients
)
1462 (when (and (memq proc server-clients
)
1463 (eq (process-status proc
) 'open
))
1466 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1467 (buffer-name (current-buffer))))))
1469 (defun server-kill-emacs-query-function ()
1470 "Ask before exiting Emacs if it has live clients."
1471 (or (not server-clients
)
1473 (dolist (proc server-clients
)
1474 (when (memq t
(mapcar 'buffer-live-p
(process-get
1476 (setq live-client t
)))
1478 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1480 (defun server-kill-buffer ()
1481 "Remove the current buffer from its clients' buffer list.
1482 Designed to be added to `kill-buffer-hook'."
1483 ;; Prevent infinite recursion if user has made server-done-hook
1484 ;; call kill-buffer.
1485 (or server-kill-buffer-running
1486 (and server-buffer-clients
1487 (let ((server-kill-buffer-running t
))
1488 (when server-process
1489 (server-buffer-done (current-buffer) t
))))))
1491 (defun server-edit (&optional arg
)
1492 "Switch to next server editing buffer; say \"Done\" for current buffer.
1493 If a server buffer is current, it is marked \"done\" and optionally saved.
1494 The buffer is also killed if it did not exist before the clients asked for it.
1495 When all of a client's buffers are marked as \"done\", the client is notified.
1497 Temporary files such as MH <draft> files are always saved and backed up,
1498 no questions asked. (The variable `make-backup-files', if nil, still
1499 inhibits a backup; you can set it locally in a particular buffer to
1500 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1501 which filenames are considered temporary.
1503 If invoked with a prefix argument, or if there is no server process running,
1504 starts server process and that is all. Invoked by \\[server-edit]."
1508 (not server-process
)
1509 (memq (process-status server-process
) '(signal exit
)))
1511 (server-clients (apply 'server-switch-buffer
(server-done)))
1512 (t (message "No server editing buffers exist"))))
1514 (defun server-switch-buffer (&optional next-buffer killed-one filepos
)
1515 "Switch to another buffer, preferably one that has a client.
1516 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1518 KILLED-ONE is t in a recursive call if we have already killed one
1519 temp-file server buffer. This means we should avoid the final
1520 \"switch to some other buffer\" since we've already effectively
1523 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1524 visit NEXT-BUFFER in an existing window. If non-nil, it should
1525 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1526 (if (null next-buffer
)
1528 (let ((rest server-clients
))
1529 (while (and rest
(not next-buffer
))
1530 (let ((proc (car rest
)))
1531 ;; Only look at frameless clients, or those in the selected
1533 (when (or (not (process-get proc
'frame
))
1534 (eq (process-get proc
'frame
) (selected-frame)))
1535 (setq next-buffer
(car (process-get proc
'buffers
))))
1536 (setq rest
(cdr rest
)))))
1537 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1538 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1539 ;; (switch-to-buffer (other-buffer))
1540 (message "No server buffers remain to edit")))
1541 (if (not (buffer-live-p next-buffer
))
1542 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1543 ;; and try the next surviving server buffer.
1544 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1545 ;; OK, we know next-buffer is live, let's display and select it.
1546 (if (functionp server-window
)
1547 (funcall server-window next-buffer
)
1548 (let ((win (get-buffer-window next-buffer
0)))
1549 (if (and win
(not server-window
))
1550 ;; The buffer is already displayed: just reuse the
1551 ;; window. If FILEPOS is non-nil, use it to replace the
1552 ;; window's own value of point.
1555 (set-buffer next-buffer
)
1557 (server-goto-line-column filepos
)))
1558 ;; Otherwise, let's find an appropriate window.
1559 (cond ((window-live-p server-window
)
1560 (select-window server-window
))
1561 ((framep server-window
)
1562 (unless (frame-live-p server-window
)
1563 (setq server-window
(make-frame)))
1564 (select-window (frame-selected-window server-window
))))
1565 (when (window-minibuffer-p (selected-window))
1566 (select-window (next-window nil
'nomini
0)))
1567 ;; Move to a non-dedicated window, if we have one.
1568 (when (window-dedicated-p (selected-window))
1570 (get-window-with-predicate
1572 (and (not (window-dedicated-p w
))
1573 (equal (frame-terminal (window-frame w
))
1574 (frame-terminal (selected-frame)))))
1575 'nomini
'visible
(selected-window))))
1577 (switch-to-buffer next-buffer
)
1578 ;; After all the above, we might still have ended up with
1579 ;; a minibuffer/dedicated-window (if there's no other).
1580 (error (pop-to-buffer next-buffer
)))))))
1581 (when server-raise-frame
1582 (select-frame-set-input-focus (window-frame (selected-window))))))
1585 (defun server-save-buffers-kill-terminal (arg)
1586 ;; Called from save-buffers-kill-terminal in files.el.
1587 "Offer to save each buffer, then kill the current client.
1588 With ARG non-nil, silently save all file-visiting buffers, then kill.
1590 If emacsclient was started with a list of filenames to edit, then
1591 only these files will be asked to be saved."
1592 (let ((proc (frame-parameter (selected-frame) 'client
)))
1593 (cond ((eq proc
'nowait
)
1594 ;; Nowait frames have no client buffer list.
1595 (if (cdr (frame-list))
1596 (progn (save-some-buffers arg
)
1598 ;; If we're the last frame standing, kill Emacs.
1599 (save-buffers-kill-emacs arg
)))
1601 (let ((buffers (process-get proc
'buffers
)))
1602 ;; If client is bufferless, emulate a normal Emacs exit
1603 ;; and offer to save all buffers. Otherwise, offer to
1604 ;; save only the buffers belonging to the client.
1607 (lambda () (memq (current-buffer) buffers
))
1609 (server-delete-client proc
)))
1610 (t (error "Invalid client frame")))))
1612 (define-key ctl-x-map
"#" 'server-edit
)
1614 (defun server-unload-function ()
1615 "Unload the server library."
1617 (substitute-key-definition 'server-edit nil ctl-x-map
)
1618 (save-current-buffer
1619 (dolist (buffer (buffer-list))
1621 (remove-hook 'kill-buffer-hook
'server-kill-buffer t
)))
1622 ;; continue standard unloading
1625 (defun server-eval-at (server form
)
1626 "Contact the Emacs server named SERVER and evaluate FORM there.
1627 Returns the result of the evaluation, or signals an error if it
1628 cannot contact the specified server. For example:
1629 \(server-eval-at \"server\" '(emacs-pid))
1630 returns the process ID of the Emacs instance running \"server\"."
1631 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
1632 (server-file (expand-file-name server server-dir
))
1633 (coding-system-for-read 'binary
)
1634 (coding-system-for-write 'binary
)
1635 address port secret process
)
1636 (unless (file-exists-p server-file
)
1637 (error "No such server: %s" server
))
1639 (when server-use-tcp
1640 (let ((coding-system-for-read 'no-conversion
))
1641 (insert-file-contents server-file
)
1642 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1643 (error "Invalid auth file"))
1644 (setq address
(match-string 1)
1645 port
(string-to-number (match-string 2)))
1647 (setq secret
(buffer-substring (point) (line-end-position)))
1649 (unless (setq process
(make-network-process
1651 :buffer
(current-buffer)
1653 :service
(if server-use-tcp port server-file
)
1654 :family
(if server-use-tcp
'ipv4
'local
)
1656 (error "Unable to contact the server"))
1658 (process-send-string process
(concat "-auth " secret
"\n")))
1659 (process-send-string process
1661 (server-quote-arg (format "%S" form
))
1663 (while (memq (process-status process
) '(open run
))
1664 (accept-process-output process
0 10))
1665 (goto-char (point-min))
1666 ;; If the result is nil, there's nothing in the buffer. If the
1667 ;; result is non-nil, it's after "-print ".
1669 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t
)
1672 (buffer-substring (point)
1673 (progn (skip-chars-forward "^\n")
1675 (if (not (equal answer
""))
1676 (read (decode-coding-string (server-unquote-arg answer
)
1677 'emacs-internal
)))))))
1682 ;;; server.el ends here