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
))
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")))
98 (set-default sym val
))
103 (defcustom server-host nil
104 "The name or IP address to use as host address of the server process.
105 If set, the server accepts remote connections; otherwise it is local."
108 (string :tag
"Name or IP address")
109 (const :tag
"Local" nil
))
112 (put 'server-host
'risky-local-variable t
)
114 (defcustom server-port nil
115 "The port number that the server process should listen on.
116 This variable only takes effect when the Emacs server is using
117 TCP instead of local sockets. A nil value means to use a random
121 (string :tag
"Port number")
122 (const :tag
"Random" nil
))
125 (put 'server-port
'risky-local-variable t
)
127 (defcustom server-auth-dir
(locate-user-emacs-file "server/")
128 "Directory for server authentication files.
129 We only use this if `server-use-tcp' is non-nil.
130 Otherwise we use `server-socket-dir'.
132 NOTE: On FAT32 filesystems, directories are not secure;
133 files can be read and modified by any user or process.
134 It is strongly suggested to set `server-auth-dir' to a
135 directory residing in a NTFS partition instead."
140 (put 'server-auth-dir
'risky-local-variable t
)
142 (defcustom server-auth-key nil
143 "Server authentication key.
145 Normally, authentication key is generated on random when server
146 starts, which guarantees some level of security. It is
147 recommended to leave it that way. Using a long-lived shared key
148 may decrease security (especially since the key is transmitted as
151 In some situations however, it can be difficult to share randomly
152 generated password with remote hosts (eg. no shared directory),
153 so you can set the key with this variable and then copy server
154 file to remote host (with possible changes to IP address and/or
155 port if that applies).
157 The key must consist of 64 US-ASCII printable characters except
158 for space (this means characters from ! to ~; or from code 33
161 You can use \\[server-generate-key] to get a random authentication
165 (const :tag
"Random" nil
)
166 (string :tag
"Password"))
169 (defcustom server-raise-frame t
170 "If non-nil, raise frame when switching to a buffer."
175 (defcustom server-visit-hook nil
176 "Hook run when visiting a file for the Emacs server."
180 (defcustom server-switch-hook nil
181 "Hook run when switching to a buffer for the Emacs server."
185 (defcustom server-done-hook nil
186 "Hook run when done editing a buffer for the Emacs server."
190 (defvar server-process nil
191 "The current server process.")
193 (defvar server-clients nil
194 "List of current server clients.
195 Each element is a process.")
197 (defvar server-buffer-clients nil
198 "List of client processes requesting editing of current buffer.")
199 (make-variable-buffer-local 'server-buffer-clients
)
200 ;; Changing major modes should not erase this local.
201 (put 'server-buffer-clients
'permanent-local t
)
203 (defcustom server-window nil
204 "Specification of the window to use for selecting Emacs server buffers.
205 If nil, use the selected window.
206 If it is a function, it should take one argument (a buffer) and
207 display and select it. A common value is `pop-to-buffer'.
208 If it is a window, use that.
209 If it is a frame, use the frame's selected window.
211 It is not meaningful to set this to a specific frame or window with Custom.
212 Only programs can do so."
215 :type
'(choice (const :tag
"Use selected window"
216 :match
(lambda (widget value
)
217 (not (functionp value
)))
219 (function-item :tag
"Display in new frame" switch-to-buffer-other-frame
)
220 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
221 (function :tag
"Other function")))
223 (defcustom server-temp-file-regexp
"^/tmp/Re\\|/draft$"
224 "Regexp matching names of temporary files.
225 These are deleted and reused after each edit by the programs that
226 invoke the Emacs server."
230 (defcustom server-kill-new-buffers t
231 "Whether to kill buffers when done with them.
232 If non-nil, kill a buffer unless it already existed before editing
233 it with the Emacs server. If nil, kill only buffers as specified by
234 `server-temp-file-regexp'.
235 Please note that only buffers that still have a client are killed,
236 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
242 (or (assq 'server-buffer-clients minor-mode-alist
)
243 (push '(server-buffer-clients " Server") minor-mode-alist
))
245 (defvar server-existing-buffer nil
246 "Non-nil means the buffer existed before the server was asked to visit it.
247 This means that the server should not kill the buffer when you say you
248 are done with it in the server.")
249 (make-variable-buffer-local 'server-existing-buffer
)
251 (defcustom server-name
"server"
252 "The name of the Emacs server, if this Emacs process creates one.
253 The command `server-start' makes use of this. It should not be
254 changed while a server is running."
259 ;; We do not use `temporary-file-directory' here, because emacsclient
260 ;; does not read the init file.
261 (defvar server-socket-dir
262 (and (featurep 'make-network-process
'(:family local
))
263 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
264 "The directory in which to place the server socket.
265 If local sockets are not supported, this is nil.")
267 (defun server-clients-with (property value
)
268 "Return a list of clients with PROPERTY set to VALUE."
270 (dolist (proc server-clients
)
271 (when (equal value
(process-get proc property
))
275 (defun server-add-client (proc)
276 "Create a client for process PROC, if it doesn't already have one.
277 New clients have no properties."
278 (add-to-list 'server-clients proc
))
280 (defmacro server-with-environment
(env vars
&rest body
)
281 "Evaluate BODY with environment variables VARS set to those in ENV.
282 The environment variables are then restored to their previous values.
284 VARS should be a list of strings.
285 ENV should be in the same format as `process-environment'."
287 (let ((var (make-symbol "var"))
288 (value (make-symbol "value")))
289 `(let ((process-environment process-environment
))
291 (let ((,value
(getenv-internal ,var
,env
)))
292 (push (if (stringp ,value
)
293 (concat ,var
"=" ,value
)
295 process-environment
)))
298 (defun server-delete-client (proc &optional noframe
)
299 "Delete PROC, including its buffers, terminals and frames.
300 If NOFRAME is non-nil, let the frames live.
301 Updates `server-clients'."
302 (server-log (concat "server-delete-client" (if noframe
" noframe")) proc
)
303 ;; Force a new lookup of client (prevents infinite recursion).
304 (when (memq proc server-clients
)
305 (let ((buffers (process-get proc
'buffers
)))
307 ;; Kill the client's buffers.
308 (dolist (buf buffers
)
309 (when (buffer-live-p buf
)
310 (with-current-buffer buf
311 ;; Kill the buffer if necessary.
312 (when (and (equal server-buffer-clients
314 (or (and server-kill-new-buffers
315 (not server-existing-buffer
))
316 (server-temp-file-p))
317 (not (buffer-modified-p)))
320 (progn (setq server-buffer-clients nil
)
321 (kill-buffer (current-buffer))
324 ;; Restore clients if user pressed C-g in `kill-buffer'.
325 (setq server-buffer-clients
(list proc
)))))))))
327 ;; Delete the client's frames.
329 (dolist (frame (frame-list))
330 (when (and (frame-live-p frame
)
331 (equal proc
(frame-parameter frame
'client
)))
332 ;; Prevent `server-handle-delete-frame' from calling us
334 (set-frame-parameter frame
'client nil
)
335 (delete-frame frame
))))
337 (setq server-clients
(delq proc server-clients
))
339 ;; Delete the client's tty, except on Windows (both GUI and console),
340 ;; where there's only one terminal and does not make sense to delete it.
341 (unless (eq system-type
'windows-nt
)
342 (let ((terminal (process-get proc
'terminal
)))
343 ;; Only delete the terminal if it is non-nil.
344 (when (and terminal
(eq (terminal-live-p terminal
) t
))
345 (delete-terminal terminal
))))
347 ;; Delete the client's process.
348 (if (eq (process-status proc
) 'open
)
349 (delete-process proc
))
351 (server-log "Deleted" proc
))))
353 (defvar server-log-time-function
'current-time-string
354 "Function to generate timestamps for `server-buffer'.")
356 (defconst server-buffer
" *server*"
357 "Buffer used internally by Emacs's server.
358 One use is to log the I/O for debugging purposes (see `server-log'),
359 the other is to provide a current buffer in which the process filter can
360 safely let-bind buffer-local variables like `default-directory'.")
362 (defvar server-log nil
363 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
365 (defun server-log (string &optional client
)
366 "If `server-log' is non-nil, log STRING to `server-buffer'.
367 If CLIENT is non-nil, add a description of it to the logged message."
369 (with-current-buffer (get-buffer-create server-buffer
)
370 (goto-char (point-max))
371 (insert (funcall server-log-time-function
)
374 ((listp client
) (format " %s: " (car client
)))
375 (t (format " %s: " client
)))
377 (or (bolp) (newline)))))
379 (defun server-sentinel (proc msg
)
380 "The process sentinel for Emacs server connections."
381 ;; If this is a new client process, set the query-on-exit flag to nil
382 ;; for this process (it isn't inherited from the server process).
383 (when (and (eq (process-status proc
) 'open
)
384 (process-query-on-exit-flag proc
))
385 (set-process-query-on-exit-flag proc nil
))
386 ;; Delete the associated connection file, if applicable.
387 ;; Although there's no 100% guarantee that the file is owned by the
388 ;; running Emacs instance, server-start uses server-running-p to check
389 ;; for possible servers before doing anything, so it *should* be ours.
390 (and (process-contact proc
:server
)
391 (eq (process-status proc
) 'closed
)
393 (delete-file (process-get proc
:server-file
))))
394 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
395 (server-delete-client proc
))
397 (defun server--on-display-p (frame display
)
398 (and (equal (frame-parameter frame
'display
) display
)
399 ;; Note: TTY frames still get a `display' parameter set to the value of
400 ;; $DISPLAY. This is useful when running from that tty frame
401 ;; sub-processes that want to connect to the X server, but that means we
402 ;; have to be careful here not to be tricked into thinking those frames
404 (not (eq (framep frame
) t
))))
406 (defun server-select-display (display)
407 ;; If the current frame is on `display' we're all set.
408 ;; Similarly if we are unable to open frames on other displays, there's
409 ;; nothing more we can do.
410 (unless (or (not (fboundp 'make-frame-on-display
))
411 (server--on-display-p (selected-frame) display
))
412 ;; Otherwise, look for an existing frame there and select it.
413 (dolist (frame (frame-list))
414 (when (server--on-display-p frame display
)
415 (select-frame frame
)))
416 ;; If there's no frame on that display yet, create and select one.
417 (unless (server--on-display-p (selected-frame) display
)
418 (let* ((buffer (generate-new-buffer " *server-dummy*"))
419 (frame (make-frame-on-display
421 ;; Make it display (and remember) some dummy buffer, so
422 ;; we can detect later if the frame is in use or not.
423 `((server-dummy-buffer .
,buffer
)
424 ;; This frame may be deleted later (see
425 ;; server-unselect-display) so we want it to be as
426 ;; unobtrusive as possible.
427 (visibility . nil
)))))
429 (set-window-buffer (selected-window) buffer
)
432 (defun server-unselect-display (frame)
433 (when (frame-live-p frame
)
434 ;; If the temporary frame is in use (displays something real), make it
435 ;; visible. If not (which can happen if the user's customizations call
436 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
437 ;; the last real frame is deleted.
439 ;; Rewritten to avoid inadvertently killing the current buffer after
440 ;; `delete-frame' removed FRAME (Bug#10729).
441 (let ((buffer (frame-parameter frame
'server-dummy-buffer
)))
442 (if (and (one-window-p 'nomini frame
)
443 (eq (window-buffer (frame-first-window frame
)) buffer
))
444 ;; The temp frame still only shows one buffer, and that is the
445 ;; internal temp buffer.
447 (set-frame-parameter frame
'visibility t
)
448 (set-frame-parameter frame
'server-dummy-buffer nil
))
449 (when (buffer-live-p buffer
)
450 (kill-buffer buffer
)))))
452 (defun server-handle-delete-frame (frame)
453 "Delete the client connection when the emacsclient frame is deleted.
454 \(To be used from `delete-frame-functions'.)"
455 (let ((proc (frame-parameter frame
'client
)))
456 (when (and (frame-live-p frame
)
458 ;; See if this is the last frame for this client.
459 (>= 1 (let ((frame-num 0))
460 (dolist (f (frame-list))
461 (when (eq proc
(frame-parameter f
'client
))
462 (setq frame-num
(1+ frame-num
))))
464 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
465 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
467 (defun server-handle-suspend-tty (terminal)
468 "Notify the client process that its tty device is suspended."
469 (dolist (proc (server-clients-with 'terminal terminal
))
470 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
)
473 (server-send-string proc
"-suspend \n")
474 (file-error ;The pipe/socket was closed.
475 (ignore-errors (server-delete-client proc
))))))
477 (defun server-unquote-arg (arg)
478 "Remove &-quotation from ARG.
479 See `server-quote-arg' and `server-process-filter'."
480 (replace-regexp-in-string
489 (defun server-quote-arg (arg)
490 "In ARG, insert a & before each &, each space, each newline, and -.
491 Change spaces to underscores, too, so that the return value never
494 See `server-unquote-arg' and `server-process-filter'."
495 (replace-regexp-in-string
496 "[-&\n ]" (lambda (s)
504 (defun server-send-string (proc string
)
505 "A wrapper around `process-send-string' for logging."
506 (server-log (concat "Sent " string
) proc
)
507 (process-send-string proc string
))
509 (defun server-ensure-safe-dir (dir)
510 "Make sure DIR is a directory with no race-condition issues.
511 Creates the directory if necessary and makes sure:
512 - there's no symlink involved
514 - it's not readable/writable by anybody else."
515 (setq dir
(directory-file-name dir
))
516 (let ((attrs (file-attributes dir
'integer
)))
518 (letf (((default-file-modes) ?
\700)) (make-directory dir t
))
519 (setq attrs
(file-attributes dir
'integer
)))
521 ;; Check that it's safe for use.
522 (let* ((uid (nth 2 attrs
))
523 (w32 (eq system-type
'windows-nt
))
525 (unless (eq t
(car attrs
)) ; is a dir?
527 (when (and w32
(zerop uid
)) ; on FAT32?
530 (format "Using `%s' to store Emacs-server authentication files.
531 Directories on FAT32 filesystems are NOT secure against tampering.
532 See variable `server-auth-dir' for details."
533 (file-name-as-directory dir
))
536 (unless (or (= uid
(user-uid)) ; is the dir ours?
538 ;; Files created on Windows by
539 ;; Administrator (RID=500) have
540 ;; the Administrators (RID=544)
541 ;; group recorded as the owner.
542 (= uid
544) (= (user-uid) 500)))
546 (unless (zerop (logand ?
\077 (file-modes dir
)))
550 (error "The directory `%s' is unsafe" dir
)))))
552 (defun server-generate-key ()
553 "Generates and returns a random 64-byte strings of random chars
554 in the range `!'..`~'. If called interactively, also inserts it
555 into current buffer."
559 collect
(+ 33 (random 94)) into auth
560 finally return
(concat auth
))))
561 (if (called-interactively-p)
565 (defun server-get-auth-key ()
566 "Returns server's authentication key.
568 If `server-auth-key' is nil this function will just call
569 `server-generate-key'. Otherwise, if `server-auth-key' is
570 a valid authentication it will return it. Otherwise, it will
573 (if (string-match "^[!-~]\\{64\\}$" server-auth-key
)
575 (error "The key '%s' is invalid" server-auth-key
))
576 (server-generate-key)))
579 (defun server-start (&optional leave-dead inhibit-prompt
)
580 "Allow this Emacs process to be a server for client processes.
581 This starts a server communications subprocess through which
582 client \"editors\" can send your editing commands to this Emacs
583 job. To use the server, set up the program `emacsclient' in the
584 Emacs distribution as your standard \"editor\".
586 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
587 kill any existing server communications subprocess.
589 If a server is already running, restart it. If clients are
590 running, ask the user for confirmation first, unless optional
591 argument INHIBIT-PROMPT is non-nil.
593 To force-start a server, do \\[server-force-delete] and then
596 (when (or (not server-clients
)
597 ;; Ask the user before deleting existing clients---except
598 ;; when we can't get user input, which may happen when
599 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
602 (null (cdr (frame-list)))
603 (eq (selected-frame) terminal-frame
))
607 "The current server still has clients; delete them? "))))
608 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
609 (server-file (expand-file-name server-name server-dir
)))
612 (ignore-errors (delete-process server-process
)))
613 ;; Delete the socket files made by previous server invocations.
614 (if (not (eq t
(server-running-p server-name
)))
615 ;; Remove any leftover socket or authentication file
617 (let (delete-by-moving-to-trash)
618 (delete-file server-file
)))
619 (setq server-mode nil
) ;; already set by the minor mode code
622 (concat "Unable to start the Emacs server.\n"
623 (format "There is an existing Emacs server, named %S.\n"
625 "To start the server in this Emacs process, stop the existing
626 server or call `M-x server-force-delete' to forcibly disconnect it.")
629 ;; If this Emacs already had a server, clear out associated status.
630 (while server-clients
631 (server-delete-client (car server-clients
)))
632 ;; Now any previous server is properly stopped.
635 (unless (eq t leave-dead
) (server-log (message "Server stopped")))
636 (setq server-process nil
))
637 ;; Make sure there is a safe directory in which to place the socket.
638 (server-ensure-safe-dir server-dir
)
640 (server-log (message "Restarting server")))
641 (letf (((default-file-modes) ?
\700))
642 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
643 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
644 (add-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
645 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
646 (add-hook 'kill-emacs-hook
'server-force-stop
) ;Cleanup upon exit.
648 (apply #'make-network-process
652 :sentinel
'server-sentinel
653 :filter
'server-process-filter
654 ;; We must receive file names without being decoded.
655 ;; Those are decoded by server-process-filter according
656 ;; to file-name-coding-system. Also don't get
657 ;; confused by CRs since we don't quote them.
658 :coding
'raw-text-unix
659 ;; The other args depend on the kind of socket used.
661 (list :family
'ipv4
;; We're not ready for IPv6 yet
662 :service
(or server-port t
)
663 :host
(or server-host
'local
)
664 :plist
'(:authenticated nil
))
667 :plist
'(:authenticated t
)))))
668 (unless server-process
(error "Could not start server process"))
669 (process-put server-process
:server-file server-file
)
671 (let ((auth-key (server-get-auth-key)))
672 (process-put server-process
:auth-key auth-key
)
673 (with-temp-file server-file
674 (set-buffer-multibyte nil
)
675 (setq buffer-file-coding-system
'no-conversion
)
676 (insert (format-network-address
677 (process-contact server-process
:local
))
678 " " (number-to-string (emacs-pid)) ; Kept for compatibility
679 "\n" auth-key
)))))))))
681 (defun server-force-stop ()
682 "Kill all connections to the current server.
683 This function is meant to be called from `kill-emacs-hook'."
687 (defun server-force-delete (&optional name
)
688 "Unconditionally delete connection file for server NAME.
689 If server is running, it is first stopped.
690 NAME defaults to `server-name'. With argument, ask for NAME."
692 (list (if current-prefix-arg
693 (read-string "Server name: " nil nil server-name
))))
694 (when server-mode
(with-temp-message nil
(server-mode -
1)))
695 (let ((file (expand-file-name (or name server-name
)
698 server-socket-dir
))))
700 (let (delete-by-moving-to-trash)
702 (message "Connection file %S deleted" file
))
704 (message "No connection file %S" file
)))))
706 (defun server-running-p (&optional name
)
707 "Test whether server NAME is running.
710 nil the server is definitely not running.
711 t the server seems to be running.
712 something else we cannot determine whether it's running without using
713 commands which may have to wait for a long time."
714 (unless name
(setq name server-name
))
718 (insert-file-contents-literally (expand-file-name name server-auth-dir
))
719 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
722 (string-to-number (match-string 1))))
726 (make-network-process
727 :name
"server-client-test" :family
'local
:server nil
:noquery t
728 :service
(expand-file-name name server-socket-dir
)))
733 (define-minor-mode server-mode
735 With a prefix argument ARG, enable Server mode if ARG is
736 positive, and disable it otherwise. If called from Lisp, enable
737 Server mode if ARG is omitted or nil.
739 Server mode runs a process that accepts commands from the
740 `emacsclient' program. See Info node `Emacs server' and
741 `server-start' for details."
745 ;; Fixme: Should this check for an existing server socket and do
746 ;; nothing if there is one (for multiple Emacs sessions)?
747 (server-start (not server-mode
)))
749 (defun server-eval-and-print (expr proc
)
750 "Eval EXPR and send the result back to client PROC."
751 ;; While we're running asynchronously (from a process filter), it is likely
752 ;; that the emacsclient command was run in response to a user
753 ;; action, so the user probably knows that Emacs is processing this
754 ;; emacsclient request, so if we get a C-g it's likely that the user
755 ;; intended it to interrupt us rather than interrupt whatever Emacs
756 ;; was doing before it started handling the process filter.
757 ;; Hence `with-local-quit' (bug#6585).
758 (let ((v (with-local-quit (eval (car (read-from-string expr
))))))
761 (let ((standard-output (current-buffer)))
763 (let ((text (buffer-substring-no-properties
764 (point-min) (point-max))))
765 (server-reply-print (server-quote-arg text
) proc
)))))))
767 (defconst server-msg-size
1024
768 "Maximum size of a message sent to a client.")
770 (defun server-reply-print (qtext proc
)
771 "Send a `-print QTEXT' command to client PROC.
772 QTEXT must be already quoted.
773 This handles splitting the command if it would be bigger than
775 (let ((prefix "-print ")
777 (while (> (+ (length qtext
) (length prefix
) 1) server-msg-size
)
778 ;; We have to split the string
779 (setq part
(substring qtext
0 (- server-msg-size
(length prefix
) 1)))
780 ;; Don't split in the middle of a quote sequence
781 (if (string-match "\\(^\\|[^&]\\)\\(&&\\)+$" part
)
782 ;; There is an uneven number of & at the end
783 (setq part
(substring part
0 -
1)))
784 (setq qtext
(substring qtext
(length part
)))
785 (server-send-string proc
(concat prefix part
"\n"))
786 (setq prefix
"-print-nonl "))
787 (server-send-string proc
(concat prefix qtext
"\n"))))
789 (defun server-create-tty-frame (tty type proc
)
791 (error "Invalid terminal device"))
793 (error "Invalid terminal type"))
794 (add-to-list 'frame-inherited-parameters
'client
)
796 (server-with-environment (process-get proc
'env
)
797 '("LANG" "LC_CTYPE" "LC_ALL"
798 ;; For tgetent(3); list according to ncurses(3).
799 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
800 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
801 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
802 "TERMINFO_DIRS" "TERMPATH"
804 "COLORFGBG" "COLORTERM")
805 (make-frame `((window-system . nil
)
808 ;; Ignore nowait here; we always need to
809 ;; clean up opened ttys when the client dies.
811 ;; This is a leftover from an earlier
812 ;; attempt at making it possible for process
813 ;; run in the server process to use the
814 ;; environment of the client process.
815 ;; It has no effect now and to make it work
816 ;; we'd need to decide how to make
817 ;; process-environment interact with client
818 ;; envvars, and then to change the
819 ;; C functions `child_setup' and
820 ;; `getenv_internal' accordingly.
821 (environment .
,(process-get proc
'env
)))))))
823 ;; ttys don't use the `display' parameter, but callproc.c does to set
824 ;; the DISPLAY environment on subprocesses.
825 (set-frame-parameter frame
'display
826 (getenv-internal "DISPLAY" (process-get proc
'env
)))
828 (process-put proc
'frame frame
)
829 (process-put proc
'terminal
(frame-terminal frame
))
831 ;; Display *scratch* by default.
832 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
836 (defun server-create-window-system-frame (display nowait proc parent-id
837 &optional parameters
)
838 (add-to-list 'frame-inherited-parameters
'client
)
839 (if (not (fboundp 'make-frame-on-display
))
841 ;; This emacs does not support X.
842 (server-log "Window system unsupported" proc
)
843 (server-send-string proc
"-window-system-unsupported \n")
845 ;; Flag frame as client-created, but use a dummy client.
846 ;; This will prevent the frame from being deleted when
847 ;; emacsclient quits while also preventing
848 ;; `server-save-buffers-kill-terminal' from unexpectedly
849 ;; killing emacs on that frame.
850 (let* ((params `((client .
,(if nowait
'nowait proc
))
851 ;; This is a leftover, see above.
852 (environment .
,(process-get proc
'env
))
855 (frame-parameter nil
'display
)
857 (error "Please specify display")))
860 (push (cons 'parent-id
(string-to-number parent-id
)) params
))
861 (setq frame
(make-frame-on-display display params
))
862 (server-log (format "%s created" frame
) proc
)
864 (process-put proc
'frame frame
)
865 (process-put proc
'terminal
(frame-terminal frame
))
867 ;; Display *scratch* by default.
868 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
871 (defun server-goto-toplevel (proc)
873 ;; If we're running isearch, we must abort it to allow Emacs to
874 ;; display the buffer and switch to it.
875 (dolist (buffer (buffer-list))
876 (with-current-buffer buffer
877 (when (bound-and-true-p isearch-mode
)
879 ;; Signaled by isearch-cancel.
880 (quit (message nil
)))
881 (when (> (recursion-depth) 0)
882 ;; We're inside a minibuffer already, so if the emacs-client is trying
883 ;; to open a frame on a new display, we might end up with an unusable
884 ;; frame because input from that display will be blocked (until exiting
885 ;; the minibuffer). Better exit this minibuffer right away.
886 ;; Similarly with recursive-edits such as the splash screen.
887 (run-with-timer 0 nil
(lambda () (server-execute-continuation proc
)))
890 ;; We use various special properties on process objects:
891 ;; - `env' stores the info about the environment of the emacsclient process.
892 ;; - `continuation' is a no-arg function that we need to execute. It contains
893 ;; commands we wanted to execute in some earlier invocation of the process
894 ;; filter but that we somehow were unable to process at that time
895 ;; (e.g. because we first need to throw to the toplevel).
897 (defun server-execute-continuation (proc)
898 (let ((continuation (process-get proc
'continuation
)))
899 (process-put proc
'continuation nil
)
900 (if continuation
(ignore-errors (funcall continuation
)))))
902 (defun* server-process-filter
(proc string
)
903 "Process a request from the server to edit some files.
904 PROC is the server process. STRING consists of a sequence of
905 commands prefixed by a dash. Some commands have arguments;
906 these are &-quoted and need to be decoded by `server-unquote-arg'.
907 The filter parses and executes these commands.
909 To illustrate the protocol, here is an example command that
910 emacsclient sends to create a new X frame (note that the whole
911 sequence is sent on a single line):
913 -env HOME=/home/lorentey
915 ... lots of other -env commands
919 The following commands are accepted by the server:
922 Authenticate the client using the secret authentication string
926 An environment variable on the client side.
929 The current working directory of the client process.
932 Forbid the creation of new frames.
934 `-frame-parameters ALIST'
935 Set the parameters of the created frame.
938 Request that the next frame created should not be
939 associated with this client.
942 Set the display name to open X frames on.
944 `-position LINE[:COLUMN]'
945 Go to the given line and column number
946 in the next file opened.
949 Load the given file in the current frame.
952 Evaluate EXPR as a Lisp expression and return the
953 result in -print commands.
958 `-tty DEVICENAME TYPE'
959 Open a new tty frame at the client.
962 Suspend this tty frame. The client sends this string in
963 response to SIGTSTP and SIGTTOU. The server must cease all I/O
964 on this tty until it gets a -resume command.
967 Resume this tty frame. The client sends this string when it
968 gets the SIGCONT signal and it is the foreground process on its
972 Do nothing, but put the comment in the server log.
973 Useful for debugging.
976 The following commands are accepted by the client:
979 Describes the process id of the Emacs process;
980 used to forward window change signals to it.
982 `-window-system-unsupported'
983 Signals that the server does not support creating X frames;
984 the client must try again with a tty frame.
987 Print STRING on stdout. Used to send values
991 Print STRING on stdout. Used to continue a
992 preceding -print command that would be too big to send
996 Signal an error and delete process PROC.
999 Suspend this terminal, i.e., stop the client process.
1000 Sent when the user presses C-z."
1001 (server-log (concat "Received " string
) proc
)
1002 ;; First things first: let's check the authentication
1003 (unless (process-get proc
:authenticated
)
1004 (if (and (string-match "-auth \\([!-~]+\\)\n?" string
)
1005 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
1007 (setq string
(substring string
(match-end 0)))
1008 (process-put proc
:authenticated t
)
1009 (server-log "Authentication successful" proc
))
1010 (server-log "Authentication failed" proc
)
1012 proc
(concat "-error " (server-quote-arg "Authentication failed")))
1013 ;; Before calling `delete-process', give emacsclient time to
1014 ;; receive the error string and shut down on its own.
1016 (delete-process proc
)
1017 ;; We return immediately
1018 (return-from server-process-filter
)))
1019 (let ((prev (process-get proc
'previous-string
)))
1021 (setq string
(concat prev string
))
1022 (process-put proc
'previous-string nil
)))
1025 (server-add-client proc
)
1027 (server-send-string proc
(concat "-emacs-pid "
1028 (number-to-string (emacs-pid)) "\n"))
1029 (if (not (string-match "\n" string
))
1030 ;; Save for later any partial line that remains.
1031 (when (> (length string
) 0)
1032 (process-put proc
'previous-string string
))
1034 ;; In earlier versions of server.el (where we used an `emacsserver'
1035 ;; process), there could be multiple lines. Nowadays this is not
1036 ;; supported any more.
1037 (assert (eq (match-end 0) (length string
)))
1038 (let ((request (substring string
0 (match-beginning 0)))
1039 (coding-system (and (default-value 'enable-multibyte-characters
)
1040 (or file-name-coding-system
1041 default-file-name-coding-system
)))
1042 nowait
; t if emacsclient does not want to wait for us.
1043 frame
; Frame opened for the client (if any).
1044 display
; Open frame on this display.
1045 parent-id
; Window ID for XEmbed
1046 dontkill
; t if client should not be killed.
1050 frame-parameters
;parameters for newly created frame
1051 tty-name
; nil, `window-system', or the tty name.
1056 ;; Remove this line from STRING.
1057 (setq string
(substring string
(match-end 0)))
1059 (mapcar 'server-unquote-arg
(split-string request
" " t
)))
1061 (pcase (pop args-left
)
1062 ;; -version CLIENT-VERSION: obsolete at birth.
1063 (`"-version" (pop args-left
))
1065 ;; -nowait: Emacsclient won't wait for a result.
1066 (`"-nowait" (setq nowait t
))
1068 ;; -current-frame: Don't create frames.
1069 (`"-current-frame" (setq use-current-frame t
))
1071 ;; -frame-parameters: Set frame parameters
1072 (`"-frame-parameters"
1073 (let ((alist (pop args-left
)))
1075 (setq alist
(decode-coding-string alist coding-system
)))
1076 (setq frame-parameters
(car (read-from-string alist
)))))
1078 ;; -display DISPLAY:
1079 ;; Open X frames on the given display instead of the default.
1081 (setq display
(pop args-left
))
1082 (if (zerop (length display
)) (setq display nil
)))
1085 ;; Open X frame within window ID, via XEmbed.
1087 (setq parent-id
(pop args-left
))
1088 (if (zerop (length parent-id
)) (setq parent-id nil
)))
1090 ;; -window-system: Open a new X frame.
1093 (setq tty-name
'window-system
))
1095 ;; -resume: Resume a suspended tty frame.
1097 (let ((terminal (process-get proc
'terminal
)))
1100 (when (eq (terminal-live-p terminal
) t
)
1101 (resume-tty terminal
)))
1104 ;; -suspend: Suspend the client's frame. (In case we
1105 ;; get out of sync, and a C-z sends a SIGTSTP to
1108 (let ((terminal (process-get proc
'terminal
)))
1111 (when (eq (terminal-live-p terminal
) t
)
1112 (suspend-tty terminal
)))
1115 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1116 ;; (The given comment appears in the server log.)
1121 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1123 (setq tty-name
(pop args-left
)
1124 tty-type
(pop args-left
)
1125 dontkill
(or dontkill
1126 (not use-current-frame
)))
1127 ;; On Windows, emacsclient always asks for a tty frame.
1128 ;; If running a GUI server, force the frame type to GUI.
1129 (when (eq window-system
'w32
)
1130 (push "-window-system" args-left
)))
1132 ;; -position LINE[:COLUMN]: Set point to the given
1133 ;; position in the next file.
1135 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1137 (error "Invalid -position command in client args"))
1138 (let ((arg (pop args-left
)))
1140 (cons (string-to-number (match-string 1 arg
))
1141 (string-to-number (or (match-string 2 arg
)
1144 ;; -file FILENAME: Load the given file.
1146 (let ((file (pop args-left
)))
1148 (setq file
(decode-coding-string file coding-system
)))
1149 (setq file
(expand-file-name file dir
))
1150 (push (cons file filepos
) files
)
1151 (server-log (format "New file: %s %s"
1152 file
(or filepos
"")) proc
))
1155 ;; -eval EXPR: Evaluate a Lisp expression.
1157 (if use-current-frame
1158 (setq use-current-frame
'always
))
1159 (let ((expr (pop args-left
)))
1161 (setq expr
(decode-coding-string expr coding-system
)))
1162 (push (lambda () (server-eval-and-print expr proc
))
1164 (setq filepos nil
)))
1166 ;; -env NAME=VALUE: An environment variable.
1168 (let ((var (pop args-left
)))
1169 ;; XXX Variables should be encoded as in getenv/setenv.
1170 (process-put proc
'env
1171 (cons var
(process-get proc
'env
)))))
1173 ;; -dir DIRNAME: The cwd of the emacsclient process.
1175 (setq dir
(pop args-left
))
1177 (setq dir
(decode-coding-string dir coding-system
)))
1178 (setq dir
(command-line-normalize-file-name dir
)))
1181 (arg (error "Unknown command: %s" arg
))))
1185 ((and use-current-frame
1186 (or (eq use-current-frame
'always
)
1187 ;; We can't use the Emacs daemon's
1190 (null (cdr (frame-list)))
1191 (eq (selected-frame)
1193 (setq tty-name nil tty-type nil
)
1194 (if display
(server-select-display display
)))
1195 ((eq tty-name
'window-system
)
1196 (server-create-window-system-frame display nowait proc
1199 ;; When resuming on a tty, tty-name is nil.
1201 (server-create-tty-frame tty-name tty-type proc
))))
1206 (with-current-buffer (get-buffer-create server-buffer
)
1207 ;; Use the same cwd as the emacsclient, if possible, so
1208 ;; relative file names work correctly, even in `eval'.
1209 (let ((default-directory
1210 (if (and dir
(file-directory-p dir
))
1211 dir default-directory
)))
1212 (server-execute proc files nowait commands
1213 dontkill frame tty-name
)))))
1215 (when (or frame files
)
1216 (server-goto-toplevel proc
))
1218 (server-execute-continuation proc
))))
1220 (error (server-return-error proc err
))))
1222 (defun server-execute (proc files nowait commands dontkill frame tty-name
)
1223 ;; This is run from timers and process-filters, i.e. "asynchronously".
1224 ;; But w.r.t the user, this is not really asynchronous since the timer
1225 ;; is run after 0s and the process-filter is run in response to the
1226 ;; user running `emacsclient'. So it is OK to override the
1227 ;; inhibit-quit flag, which is good since `commands' (as well as
1228 ;; find-file-noselect via the major-mode) can run arbitrary code,
1229 ;; including code that needs to wait.
1234 (server-visit-files files proc nowait
))))
1236 (mapc 'funcall
(nreverse commands
))
1238 ;; Delete the client if necessary.
1241 ;; Client requested nowait; return immediately.
1242 (server-log "Close nowait client" proc
)
1243 (server-delete-client proc
))
1244 ((and (not dontkill
) (null buffers
))
1245 ;; This client is empty; get rid of it immediately.
1246 (server-log "Close empty client" proc
)
1247 (server-delete-client proc
)))
1249 ((or isearch-mode
(minibufferp))
1251 ((and frame
(null buffers
))
1252 (message "%s" (substitute-command-keys
1253 "When done with this frame, type \\[delete-frame]")))
1254 ((not (null buffers
))
1255 (server-switch-buffer (car buffers
) nil
(cdr (car files
)))
1256 (run-hooks 'server-switch-hook
)
1258 (message "%s" (substitute-command-keys
1259 "When done with a buffer, type \\[server-edit]")))))
1260 (when (and frame
(null tty-name
))
1261 (server-unselect-display frame
)))
1263 (when (eq (car err
) 'quit
)
1264 (message "Quit emacsclient request"))
1265 (server-return-error proc err
)))))
1267 (defun server-return-error (proc err
)
1270 proc
(concat "-error " (server-quote-arg
1271 (error-message-string err
))))
1272 (server-log (error-message-string err
) proc
)
1273 ;; Before calling `delete-process', give emacsclient time to
1274 ;; receive the error string and shut down on its own.
1276 (delete-process proc
)))
1278 (defun server-goto-line-column (line-col)
1279 "Move point to the position indicated in LINE-COL.
1280 LINE-COL should be a pair (LINE . COL)."
1282 (goto-char (point-min))
1283 (forward-line (1- (car line-col
)))
1284 (let ((column-number (cdr line-col
)))
1285 (when (> column-number
0)
1286 (move-to-column (1- column-number
))))))
1288 (defun server-visit-files (files proc
&optional nowait
)
1289 "Find FILES and return a list of buffers created.
1290 FILES is an alist whose elements are (FILENAME . FILEPOS)
1291 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1292 PROC is the client that requested this operation.
1293 NOWAIT non-nil means this client is not waiting for the results,
1294 so don't mark these buffers specially, just visit them normally."
1295 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1296 (let ((last-nonmenu-event t
) client-record
)
1297 ;; Restore the current buffer afterward, but not using save-excursion,
1298 ;; because we don't want to save point in this buffer
1299 ;; if it happens to be one of those specified by the server.
1300 (save-current-buffer
1301 (dolist (file files
)
1302 ;; If there is an existing buffer modified or the file is
1303 ;; modified, revert it. If there is an existing buffer with
1304 ;; deleted file, offer to write it.
1305 (let* ((minibuffer-auto-raise (or server-raise-frame
1306 minibuffer-auto-raise
))
1308 (obuf (get-file-buffer filen
)))
1309 (add-to-history 'file-name-history filen
)
1312 (run-hooks 'pre-command-hook
)
1313 (set-buffer (find-file-noselect filen
)))
1315 ;; separately for each file, in sync with post-command hooks,
1316 ;; with the new buffer current:
1317 (run-hooks 'pre-command-hook
)
1318 (cond ((file-exists-p filen
)
1319 (when (not (verify-visited-file-modtime obuf
))
1320 (revert-buffer t nil
)))
1323 (concat "File no longer exists: " filen
1324 ", write buffer to file? "))
1325 (write-file filen
))))
1326 (unless server-buffer-clients
1327 (setq server-existing-buffer t
)))
1328 (server-goto-line-column (cdr file
))
1329 (run-hooks 'server-visit-hook
)
1330 ;; hooks may be specific to current buffer:
1331 (run-hooks 'post-command-hook
))
1333 ;; When the buffer is killed, inform the clients.
1334 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1335 (push proc server-buffer-clients
))
1336 (push (current-buffer) client-record
)))
1338 (process-put proc
'buffers
1339 (nconc (process-get proc
'buffers
) client-record
)))
1342 (defvar server-kill-buffer-running nil
1343 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1345 (defun server-buffer-done (buffer &optional for-killing
)
1346 "Mark BUFFER as \"done\" for its client(s).
1347 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1348 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1349 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1351 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1352 (let ((next-buffer nil
)
1354 (dolist (proc server-clients
)
1355 (let ((buffers (process-get proc
'buffers
)))
1357 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1358 (when buffers
; Ignore bufferless clients.
1359 (setq buffers
(delq buffer buffers
))
1360 ;; Delete all dead buffers from PROC.
1363 (not (buffer-live-p b
))
1364 (setq buffers
(delq b buffers
))))
1365 (process-put proc
'buffers buffers
)
1366 ;; If client now has no pending buffers,
1367 ;; tell it that it is done, and forget it entirely.
1369 (server-log "Close" proc
)
1371 ;; `server-delete-client' might delete the client's
1372 ;; frames, which might change the current buffer. We
1373 ;; don't want that (bug#640).
1374 (save-current-buffer
1375 (server-delete-client proc
))
1376 (server-delete-client proc
))))))
1377 (when (and (bufferp buffer
) (buffer-name buffer
))
1378 ;; We may or may not kill this buffer;
1379 ;; if we do, do not call server-buffer-done recursively
1380 ;; from kill-buffer-hook.
1381 (let ((server-kill-buffer-running t
))
1382 (with-current-buffer buffer
1383 (setq server-buffer-clients nil
)
1384 (run-hooks 'server-done-hook
))
1385 ;; Notice whether server-done-hook killed the buffer.
1386 (if (null (buffer-name buffer
))
1388 ;; Don't bother killing or burying the buffer
1389 ;; when we are called from kill-buffer.
1391 (when (and (not killed
)
1392 server-kill-new-buffers
1393 (with-current-buffer buffer
1394 (not server-existing-buffer
)))
1396 (bury-buffer buffer
)
1397 ;; Prevent kill-buffer from prompting (Bug#3696).
1398 (with-current-buffer buffer
1399 (set-buffer-modified-p nil
))
1400 (kill-buffer buffer
))
1402 (if (server-temp-file-p buffer
)
1404 (with-current-buffer buffer
1405 (set-buffer-modified-p nil
))
1406 (kill-buffer buffer
)
1408 (bury-buffer buffer
)))))))
1409 (list next-buffer killed
)))
1411 (defun server-temp-file-p (&optional buffer
)
1412 "Return non-nil if BUFFER contains a file considered temporary.
1413 These are files whose names suggest they are repeatedly
1414 reused to pass information to another program.
1416 The variable `server-temp-file-regexp' controls which filenames
1417 are considered temporary."
1418 (and (buffer-file-name buffer
)
1419 (string-match-p server-temp-file-regexp
(buffer-file-name buffer
))))
1421 (defun server-done ()
1422 "Offer to save current buffer, mark it as \"done\" for clients.
1423 This kills or buries the buffer, then returns a list
1424 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1425 as a suggestion for what to select next, or nil.
1426 KILLED is t if we killed BUFFER, which happens if it was created
1427 specifically for the clients and did not exist before their request for it."
1428 (when server-buffer-clients
1429 (if (server-temp-file-p)
1430 ;; For a temp file, save, and do make a non-numeric backup
1431 ;; (unless make-backup-files is nil).
1432 (let ((version-control nil
)
1433 (buffer-backed-up nil
))
1435 (when (and (buffer-modified-p)
1437 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1439 (server-buffer-done (current-buffer))))
1441 ;; Ask before killing a server buffer.
1442 ;; It was suggested to release its client instead,
1443 ;; but I think that is dangerous--the client would proceed
1444 ;; using whatever is on disk in that file. -- rms.
1445 (defun server-kill-buffer-query-function ()
1446 "Ask before killing a server buffer."
1447 (or (not server-buffer-clients
)
1449 (dolist (proc server-buffer-clients
)
1450 (when (and (memq proc server-clients
)
1451 (eq (process-status proc
) 'open
))
1454 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1455 (buffer-name (current-buffer))))))
1457 (defun server-kill-emacs-query-function ()
1458 "Ask before exiting Emacs if it has live clients."
1459 (or (not server-clients
)
1461 (dolist (proc server-clients
)
1462 (when (memq t
(mapcar 'buffer-live-p
(process-get
1464 (setq live-client t
)))
1466 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1468 (defun server-kill-buffer ()
1469 "Remove the current buffer from its clients' buffer list.
1470 Designed to be added to `kill-buffer-hook'."
1471 ;; Prevent infinite recursion if user has made server-done-hook
1472 ;; call kill-buffer.
1473 (or server-kill-buffer-running
1474 (and server-buffer-clients
1475 (let ((server-kill-buffer-running t
))
1476 (when server-process
1477 (server-buffer-done (current-buffer) t
))))))
1479 (defun server-edit (&optional arg
)
1480 "Switch to next server editing buffer; say \"Done\" for current buffer.
1481 If a server buffer is current, it is marked \"done\" and optionally saved.
1482 The buffer is also killed if it did not exist before the clients asked for it.
1483 When all of a client's buffers are marked as \"done\", the client is notified.
1485 Temporary files such as MH <draft> files are always saved and backed up,
1486 no questions asked. (The variable `make-backup-files', if nil, still
1487 inhibits a backup; you can set it locally in a particular buffer to
1488 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1489 which filenames are considered temporary.
1491 If invoked with a prefix argument, or if there is no server process running,
1492 starts server process and that is all. Invoked by \\[server-edit]."
1496 (not server-process
)
1497 (memq (process-status server-process
) '(signal exit
)))
1499 (server-clients (apply 'server-switch-buffer
(server-done)))
1500 (t (message "No server editing buffers exist"))))
1502 (defun server-switch-buffer (&optional next-buffer killed-one filepos
)
1503 "Switch to another buffer, preferably one that has a client.
1504 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1506 KILLED-ONE is t in a recursive call if we have already killed one
1507 temp-file server buffer. This means we should avoid the final
1508 \"switch to some other buffer\" since we've already effectively
1511 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1512 visit NEXT-BUFFER in an existing window. If non-nil, it should
1513 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1514 (if (null next-buffer
)
1516 (let ((rest server-clients
))
1517 (while (and rest
(not next-buffer
))
1518 (let ((proc (car rest
)))
1519 ;; Only look at frameless clients, or those in the selected
1521 (when (or (not (process-get proc
'frame
))
1522 (eq (process-get proc
'frame
) (selected-frame)))
1523 (setq next-buffer
(car (process-get proc
'buffers
))))
1524 (setq rest
(cdr rest
)))))
1525 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1526 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1527 ;; (switch-to-buffer (other-buffer))
1528 (message "No server buffers remain to edit")))
1529 (if (not (buffer-live-p next-buffer
))
1530 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1531 ;; and try the next surviving server buffer.
1532 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1533 ;; OK, we know next-buffer is live, let's display and select it.
1534 (if (functionp server-window
)
1535 (funcall server-window next-buffer
)
1536 (let ((win (get-buffer-window next-buffer
0)))
1537 (if (and win
(not server-window
))
1538 ;; The buffer is already displayed: just reuse the
1539 ;; window. If FILEPOS is non-nil, use it to replace the
1540 ;; window's own value of point.
1543 (set-buffer next-buffer
)
1545 (server-goto-line-column filepos
)))
1546 ;; Otherwise, let's find an appropriate window.
1547 (cond ((window-live-p server-window
)
1548 (select-window server-window
))
1549 ((framep server-window
)
1550 (unless (frame-live-p server-window
)
1551 (setq server-window
(make-frame)))
1552 (select-window (frame-selected-window server-window
))))
1553 (when (window-minibuffer-p (selected-window))
1554 (select-window (next-window nil
'nomini
0)))
1555 ;; Move to a non-dedicated window, if we have one.
1556 (when (window-dedicated-p (selected-window))
1558 (get-window-with-predicate
1560 (and (not (window-dedicated-p w
))
1561 (equal (frame-terminal (window-frame w
))
1562 (frame-terminal (selected-frame)))))
1563 'nomini
'visible
(selected-window))))
1565 (switch-to-buffer next-buffer
)
1566 ;; After all the above, we might still have ended up with
1567 ;; a minibuffer/dedicated-window (if there's no other).
1568 (error (pop-to-buffer next-buffer
)))))))
1569 (when server-raise-frame
1570 (select-frame-set-input-focus (window-frame (selected-window))))))
1573 (defun server-save-buffers-kill-terminal (arg)
1574 ;; Called from save-buffers-kill-terminal in files.el.
1575 "Offer to save each buffer, then kill the current client.
1576 With ARG non-nil, silently save all file-visiting buffers, then kill.
1578 If emacsclient was started with a list of filenames to edit, then
1579 only these files will be asked to be saved."
1580 (let ((proc (frame-parameter (selected-frame) 'client
)))
1581 (cond ((eq proc
'nowait
)
1582 ;; Nowait frames have no client buffer list.
1583 (if (cdr (frame-list))
1584 (progn (save-some-buffers arg
)
1586 ;; If we're the last frame standing, kill Emacs.
1587 (save-buffers-kill-emacs arg
)))
1589 (let ((buffers (process-get proc
'buffers
)))
1590 ;; If client is bufferless, emulate a normal Emacs exit
1591 ;; and offer to save all buffers. Otherwise, offer to
1592 ;; save only the buffers belonging to the client.
1595 (lambda () (memq (current-buffer) buffers
))
1597 (server-delete-client proc
)))
1598 (t (error "Invalid client frame")))))
1600 (define-key ctl-x-map
"#" 'server-edit
)
1602 (defun server-unload-function ()
1603 "Unload the server library."
1605 (substitute-key-definition 'server-edit nil ctl-x-map
)
1606 (save-current-buffer
1607 (dolist (buffer (buffer-list))
1609 (remove-hook 'kill-buffer-hook
'server-kill-buffer t
)))
1610 ;; continue standard unloading
1613 (defun server-eval-at (server form
)
1614 "Contact the Emacs server named SERVER and evaluate FORM there.
1615 Returns the result of the evaluation, or signals an error if it
1616 cannot contact the specified server. For example:
1617 \(server-eval-at \"server\" '(emacs-pid))
1618 returns the process ID of the Emacs instance running \"server\"."
1619 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
1620 (server-file (expand-file-name server server-dir
))
1621 (coding-system-for-read 'binary
)
1622 (coding-system-for-write 'binary
)
1623 address port secret process
)
1624 (unless (file-exists-p server-file
)
1625 (error "No such server: %s" server
))
1627 (when server-use-tcp
1628 (let ((coding-system-for-read 'no-conversion
))
1629 (insert-file-contents server-file
)
1630 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1631 (error "Invalid auth file"))
1632 (setq address
(match-string 1)
1633 port
(string-to-number (match-string 2)))
1635 (setq secret
(buffer-substring (point) (line-end-position)))
1637 (unless (setq process
(make-network-process
1639 :buffer
(current-buffer)
1641 :service
(if server-use-tcp port server-file
)
1642 :family
(if server-use-tcp
'ipv4
'local
)
1644 (error "Unable to contact the server"))
1646 (process-send-string process
(concat "-auth " secret
"\n")))
1647 (process-send-string process
1649 (server-quote-arg (format "%S" form
))
1651 (while (memq (process-status process
) '(open run
))
1652 (accept-process-output process
0 10))
1653 (goto-char (point-min))
1654 ;; If the result is nil, there's nothing in the buffer. If the
1655 ;; result is non-nil, it's after "-print ".
1657 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t
)
1660 (buffer-substring (point)
1661 (progn (skip-chars-forward "^\n")
1663 (if (not (equal answer
""))
1664 (read (decode-coding-string (server-unquote-arg answer
)
1665 'emacs-internal
)))))))
1670 ;;; server.el ends here