Merge from origin/emacs-26
[emacs.git] / lisp / server.el
blob9eedc293a7d4b436bcaefca2b9f41da9bd4c2f6c
1 ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
3 ;; Copyright (C) 1986-1987, 1992, 1994-2018 Free Software Foundation,
4 ;; Inc.
6 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Keywords: processes
10 ;; Changes by peck@sun.com and by rms.
11 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation, either version 3 of the License, or
18 ;; (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
28 ;;; Commentary:
30 ;; This Lisp code is run in Emacs when it is to operate as
31 ;; a server for other processes.
33 ;; Load this library and do M-x server-edit to enable Emacs as a server.
34 ;; Emacs opens up a socket for communication with clients. If there are no
35 ;; client buffers to edit, server-edit acts like (switch-to-buffer
36 ;; (other-buffer))
38 ;; When some other program runs "the editor" to edit a file,
39 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
40 ;; This program transmits the file names to Emacs through
41 ;; the server subprocess, and Emacs visits them and lets you edit them.
43 ;; Note that any number of clients may dispatch files to Emacs to be edited.
45 ;; When you finish editing a Server buffer, again call server-edit
46 ;; to mark that buffer as done for the client and switch to the next
47 ;; Server buffer. When all the buffers for a client have been edited
48 ;; and exited with server-edit, the client "editor" will return
49 ;; to the program that invoked it.
51 ;; Your editing commands and Emacs's display output go to and from
52 ;; the terminal in the usual way. Thus, server operation is possible
53 ;; only when Emacs can talk to the terminal at the time you invoke
54 ;; the client. This is possible in four cases:
56 ;; 1. On a window system, where Emacs runs in one window and the
57 ;; program that wants to use "the editor" runs in another.
59 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
60 ;; program that wants to use "the editor" runs on another.
62 ;; 3. When the program that wants to use "the editor" is running
63 ;; as a subprocess of Emacs.
65 ;; 4. On a system with job control, when Emacs is suspended, the program
66 ;; that wants to use "the editor" will stop and display
67 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
68 ;; brought into the foreground for editing. When done editing, Emacs is
69 ;; suspended again, and the client program is brought into the foreground.
71 ;; The buffer local variable "server-buffer-clients" lists
72 ;; the clients who are waiting for this buffer to be edited.
73 ;; The global variable "server-clients" lists all the waiting clients,
74 ;; and which files are yet to be edited for each.
76 ;; Todo:
78 ;; - handle command-line-args-left.
79 ;; - move most of the args processing and decision making from emacsclient.c
80 ;; to here.
81 ;; - fix up handling of the client's environment (place it in the terminal?).
83 ;;; Code:
85 (eval-when-compile (require 'cl-lib))
87 (defgroup server nil
88 "Emacs running as a server process."
89 :group 'external)
91 (defcustom server-use-tcp nil
92 "If non-nil, use TCP sockets instead of local sockets."
93 :set #'(lambda (sym val)
94 (unless (featurep 'make-network-process '(:family local))
95 (setq val t)
96 (unless load-in-progress
97 (message "Local sockets unsupported, using TCP sockets")))
98 (set-default sym val))
99 :group 'server
100 :type 'boolean
101 :version "22.1")
103 (defcustom server-host nil
104 "The name or IP address to use as host address of the server process.
105 If set, the server accepts remote connections; otherwise it is local.
107 DO NOT give this a non-nil value unless you know what you are doing!
108 On unsecured networks, accepting remote connections is very dangerous,
109 because server-client communication (including session authentication)
110 is not encrypted."
111 :group 'server
112 :type '(choice
113 (string :tag "Name or IP address")
114 (const :tag "Local" nil))
115 :version "22.1")
116 ;;;###autoload
117 (put 'server-host 'risky-local-variable t)
119 (defcustom server-port nil
120 "The port number that the server process should listen on.
121 This variable only takes effect when the Emacs server is using
122 TCP instead of local sockets. A nil value means to use a random
123 port number."
124 :group 'server
125 :type '(choice
126 (string :tag "Port number")
127 (const :tag "Random" nil))
128 :version "24.1")
129 ;;;###autoload
130 (put 'server-port 'risky-local-variable t)
132 (defcustom server-auth-dir (locate-user-emacs-file "server/")
133 "Directory for server authentication files.
134 We only use this if `server-use-tcp' is non-nil.
135 Otherwise we use `server-socket-dir'.
137 NOTE: On FAT32 filesystems, directories are not secure;
138 files can be read and modified by any user or process.
139 It is strongly suggested to set `server-auth-dir' to a
140 directory residing in a NTFS partition instead."
141 :group 'server
142 :type 'directory
143 :version "22.1")
144 ;;;###autoload
145 (put 'server-auth-dir 'risky-local-variable t)
147 (defcustom server-auth-key nil
148 "Server authentication key.
149 This is only used if `server-use-tcp' is non-nil.
151 Normally, the authentication key is randomly generated when the
152 server starts. It is recommended to leave it that way. Using a
153 long-lived shared key will decrease security (especially since
154 the key is transmitted as plain-text).
156 In some situations however, it can be difficult to share randomly
157 generated passwords with remote hosts (e.g., no shared directory),
158 so you can set the key with this variable and then copy the
159 server file to the remote host (with possible changes to IP
160 address and/or port if that applies).
162 Note that the usual security risks of using the server over
163 remote TCP, arising from the fact that client-server
164 communications are unencrypted, still apply.
166 The key must consist of 64 ASCII printable characters except for
167 space (this means characters from ! to ~; or from code 33 to
168 126). You can use \\[server-generate-key] to get a random key."
169 :group 'server
170 :type '(choice
171 (const :tag "Random" nil)
172 (string :tag "Password"))
173 :version "24.3")
175 (defcustom server-raise-frame t
176 "If non-nil, raise frame when switching to a buffer."
177 :group 'server
178 :type 'boolean
179 :version "22.1")
181 (defcustom server-visit-hook nil
182 "Hook run when visiting a file for the Emacs server."
183 :group 'server
184 :type 'hook)
186 (defcustom server-switch-hook nil
187 "Hook run when switching to a buffer for the Emacs server."
188 :group 'server
189 :type 'hook)
191 (defcustom server-after-make-frame-hook nil
192 "Hook run when the Emacs server creates a client frame.
193 The created frame is selected when the hook is called."
194 :group 'server
195 :type 'hook
196 :version "27.1")
198 (defcustom server-done-hook nil
199 "Hook run when done editing a buffer for the Emacs server."
200 :group 'server
201 :type 'hook)
203 (defvar server-process nil
204 "The current server process.")
206 (defvar server-clients nil
207 "List of current server clients.
208 Each element is a process.")
210 (defvar server-buffer-clients nil
211 "List of client processes requesting editing of current buffer.")
212 (make-variable-buffer-local 'server-buffer-clients)
213 ;; Changing major modes should not erase this local.
214 (put 'server-buffer-clients 'permanent-local t)
216 (defcustom server-window nil
217 "Specification of the window to use for selecting Emacs server buffers.
218 If nil, use the selected window.
219 If it is a function, it should take one argument (a buffer) and
220 display and select it. A common value is `pop-to-buffer'.
221 If it is a window, use that.
222 If it is a frame, use the frame's selected window.
224 It is not meaningful to set this to a specific frame or window with Custom.
225 Only programs can do so."
226 :group 'server
227 :version "22.1"
228 :type '(choice (const :tag "Use selected window"
229 :match (lambda (widget value)
230 (not (functionp value)))
231 nil)
232 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
233 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
234 (function :tag "Other function")))
236 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
237 "Regexp matching names of temporary files.
238 These are deleted and reused after each edit by the programs that
239 invoke the Emacs server."
240 :group 'server
241 :type 'regexp)
243 (defcustom server-kill-new-buffers t
244 "Whether to kill buffers when done with them.
245 If non-nil, kill a buffer unless it already existed before editing
246 it with the Emacs server. If nil, kill only buffers as specified by
247 `server-temp-file-regexp'.
248 Please note that only buffers that still have a client are killed,
249 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
250 in this way."
251 :group 'server
252 :type 'boolean
253 :version "21.1")
255 (defvar server-existing-buffer nil
256 "Non-nil means the buffer existed before the server was asked to visit it.
257 This means that the server should not kill the buffer when you say you
258 are done with it in the server.")
259 (make-variable-buffer-local 'server-existing-buffer)
261 (defvar server--external-socket-initialized nil
262 "When an external socket is passed into Emacs, we need to call
263 `server-start' in order to initialize the connection. This flag
264 prevents multiple initializations when an external socket has
265 been consumed.")
267 (defcustom server-name
268 (if internal--daemon-sockname
269 (file-name-nondirectory internal--daemon-sockname)
270 "server")
271 "The name of the Emacs server, if this Emacs process creates one.
272 The command `server-start' makes use of this. It should not be
273 changed while a server is running."
274 :group 'server
275 :type 'string
276 :version "23.1")
278 ;; We do not use `temporary-file-directory' here, because emacsclient
279 ;; does not read the init file.
280 (defvar server-socket-dir
281 (if internal--daemon-sockname
282 (file-name-directory internal--daemon-sockname)
283 (and (featurep 'make-network-process '(:family local))
284 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid))))
285 "The directory in which to place the server socket.
286 If local sockets are not supported, this is nil.")
288 (defun server-clients-with (property value)
289 "Return a list of clients with PROPERTY set to VALUE."
290 (let (result)
291 (dolist (proc server-clients)
292 (when (equal value (process-get proc property))
293 (push proc result)))
294 result))
296 (defun server-add-client (proc)
297 "Create a client for process PROC, if it doesn't already have one.
298 New clients have no properties."
299 (add-to-list 'server-clients proc))
301 (defmacro server-with-environment (env vars &rest body)
302 "Evaluate BODY with environment variables VARS set to those in ENV.
303 The environment variables are then restored to their previous values.
305 VARS should be a list of strings.
306 ENV should be in the same format as `process-environment'."
307 (declare (indent 2))
308 (let ((var (make-symbol "var"))
309 (value (make-symbol "value")))
310 `(let ((process-environment process-environment))
311 (dolist (,var ,vars)
312 (let ((,value (getenv-internal ,var ,env)))
313 (push (if (stringp ,value)
314 (concat ,var "=" ,value)
315 ,var)
316 process-environment)))
317 (progn ,@body))))
319 (defun server-delete-client (proc &optional noframe)
320 "Delete PROC, including its buffers, terminals and frames.
321 If NOFRAME is non-nil, let the frames live.
322 Updates `server-clients'."
323 (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
324 ;; Force a new lookup of client (prevents infinite recursion).
325 (when (memq proc server-clients)
326 (let ((buffers (process-get proc 'buffers)))
328 ;; Kill the client's buffers.
329 (dolist (buf buffers)
330 (when (buffer-live-p buf)
331 (with-current-buffer buf
332 ;; Kill the buffer if necessary.
333 (when (and (equal server-buffer-clients
334 (list proc))
335 (or (and server-kill-new-buffers
336 (not server-existing-buffer))
337 (server-temp-file-p))
338 (not (buffer-modified-p)))
339 (let (flag)
340 (unwind-protect
341 (progn (setq server-buffer-clients nil)
342 (kill-buffer (current-buffer))
343 (setq flag t))
344 (unless flag
345 ;; Restore clients if user pressed C-g in `kill-buffer'.
346 (setq server-buffer-clients (list proc)))))))))
348 ;; Delete the client's frames.
349 (unless noframe
350 (dolist (frame (frame-list))
351 (when (and (frame-live-p frame)
352 (equal proc (frame-parameter frame 'client)))
353 ;; Prevent `server-handle-delete-frame' from calling us
354 ;; recursively.
355 (set-frame-parameter frame 'client nil)
356 (delete-frame frame))))
358 (setq server-clients (delq proc server-clients))
360 ;; Delete the client's tty, except on Windows (both GUI and console),
361 ;; where there's only one terminal and does not make sense to delete it.
362 (unless (eq system-type 'windows-nt)
363 (let ((terminal (process-get proc 'terminal)))
364 ;; Only delete the terminal if it is non-nil.
365 (when (and terminal (eq (terminal-live-p terminal) t))
366 (delete-terminal terminal))))
368 ;; Delete the client's process.
369 (if (eq (process-status proc) 'open)
370 (delete-process proc))
372 (server-log "Deleted" proc))))
374 (defvar server-log-time-function 'current-time-string
375 "Function to generate timestamps for `server-buffer'.")
377 (defconst server-buffer " *server*"
378 "Buffer used internally by Emacs's server.
379 One use is to log the I/O for debugging purposes (see option `server-log'),
380 the other is to provide a current buffer in which the process filter can
381 safely let-bind buffer-local variables like `default-directory'.")
383 (defvar server-log nil
384 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
386 (defun server-log (string &optional client)
387 "If option `server-log' is non-nil, log STRING to `server-buffer'.
388 If CLIENT is non-nil, add a description of it to the logged message."
389 (when server-log
390 (with-current-buffer (get-buffer-create server-buffer)
391 (goto-char (point-max))
392 (insert (funcall server-log-time-function)
393 (cond
394 ((null client) " ")
395 ((listp client) (format " %s: " (car client)))
396 (t (format " %s: " client)))
397 string)
398 (or (bolp) (newline)))))
400 (defun server-sentinel (proc msg)
401 "The process sentinel for Emacs server connections."
402 ;; If this is a new client process, set the query-on-exit flag to nil
403 ;; for this process (it isn't inherited from the server process).
404 (when (and (eq (process-status proc) 'open)
405 (process-query-on-exit-flag proc))
406 (set-process-query-on-exit-flag proc nil))
407 ;; Delete the associated connection file, if applicable.
408 ;; Although there's no 100% guarantee that the file is owned by the
409 ;; running Emacs instance, server-start uses server-running-p to check
410 ;; for possible servers before doing anything, so it *should* be ours.
411 (and (process-contact proc :server)
412 (eq (process-status proc) 'closed)
413 (ignore-errors
414 (delete-file (process-get proc :server-file))))
415 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
416 (server-delete-client proc))
418 (defun server--on-display-p (frame display)
419 (and (equal (frame-parameter frame 'display) display)
420 ;; Note: TTY frames still get a `display' parameter set to the value of
421 ;; $DISPLAY. This is useful when running from that tty frame
422 ;; sub-processes that want to connect to the X server, but that means we
423 ;; have to be careful here not to be tricked into thinking those frames
424 ;; are on `display'.
425 (not (eq (framep frame) t))))
427 (defun server-select-display (display)
428 ;; If the current frame is on `display' we're all set.
429 ;; Similarly if we are unable to open frames on other displays, there's
430 ;; nothing more we can do.
431 (unless (or (not (fboundp 'make-frame-on-display))
432 (server--on-display-p (selected-frame) display))
433 ;; Otherwise, look for an existing frame there and select it.
434 (dolist (frame (frame-list))
435 (when (server--on-display-p frame display)
436 (select-frame frame)))
437 ;; If there's no frame on that display yet, create and select one.
438 (unless (server--on-display-p (selected-frame) display)
439 (let* ((buffer (generate-new-buffer " *server-dummy*"))
440 (frame (make-frame-on-display
441 display
442 ;; Make it display (and remember) some dummy buffer, so
443 ;; we can detect later if the frame is in use or not.
444 `((server-dummy-buffer . ,buffer)
445 ;; This frame may be deleted later (see
446 ;; server-unselect-display) so we want it to be as
447 ;; unobtrusive as possible.
448 (visibility . nil)))))
449 (select-frame frame)
450 (set-window-buffer (selected-window) buffer)
451 frame))))
453 (defun server-unselect-display (frame)
454 (when (frame-live-p frame)
455 ;; If the temporary frame is in use (displays something real), make it
456 ;; visible. If not (which can happen if the user's customizations call
457 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
458 ;; the last real frame is deleted.
460 ;; Rewritten to avoid inadvertently killing the current buffer after
461 ;; `delete-frame' removed FRAME (Bug#10729).
462 (let ((buffer (frame-parameter frame 'server-dummy-buffer)))
463 (if (and (one-window-p 'nomini frame)
464 (eq (window-buffer (frame-first-window frame)) buffer))
465 ;; The temp frame still only shows one buffer, and that is the
466 ;; internal temp buffer.
467 (delete-frame frame)
468 (set-frame-parameter frame 'visibility t)
469 (set-frame-parameter frame 'server-dummy-buffer nil))
470 (when (buffer-live-p buffer)
471 (kill-buffer buffer)))))
473 (defun server-handle-delete-frame (frame)
474 "Delete the client connection when the emacsclient frame is deleted.
475 \(To be used from `delete-frame-functions'.)"
476 (let ((proc (frame-parameter frame 'client)))
477 (when (and (frame-live-p frame)
478 proc
479 ;; See if this is the last frame for this client.
480 (>= 1 (let ((frame-num 0))
481 (dolist (f (frame-list))
482 (when (eq proc (frame-parameter f 'client))
483 (setq frame-num (1+ frame-num))))
484 frame-num)))
485 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
486 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
488 (defun server-handle-suspend-tty (terminal)
489 "Notify the client process that its tty device is suspended."
490 (dolist (proc (server-clients-with 'terminal terminal))
491 (server-log (format "server-handle-suspend-tty, terminal %s" terminal)
492 proc)
493 (condition-case nil
494 (server-send-string proc "-suspend \n")
495 (file-error ;The pipe/socket was closed.
496 (ignore-errors (server-delete-client proc))))))
498 (defun server-unquote-arg (arg)
499 "Remove &-quotation from ARG.
500 See `server-quote-arg' and `server-process-filter'."
501 (replace-regexp-in-string
502 "&." (lambda (s)
503 (pcase (aref s 1)
504 (?& "&")
505 (?- "-")
506 (?n "\n")
507 (_ " ")))
508 arg t t))
510 (defun server-quote-arg (arg)
511 "In ARG, insert a & before each &, each space, each newline, and -.
512 Change spaces to underscores, too, so that the return value never
513 contains a space.
515 See `server-unquote-arg' and `server-process-filter'."
516 (replace-regexp-in-string
517 "[-&\n ]" (lambda (s)
518 (pcase (aref s 0)
519 (?& "&&")
520 (?- "&-")
521 (?\n "&n")
522 (?\s "&_")))
523 arg t t))
525 (defun server-send-string (proc string)
526 "A wrapper around `process-send-string' for logging."
527 (server-log (concat "Sent " string) proc)
528 (process-send-string proc string))
530 (defun server-ensure-safe-dir (dir)
531 "Make sure DIR is a directory with no race-condition issues.
532 Creates the directory if necessary and makes sure:
533 - there's no symlink involved
534 - it's owned by us
535 - it's not readable/writable by anybody else."
536 (setq dir (directory-file-name dir))
537 (let ((attrs (file-attributes dir 'integer)))
538 (unless attrs
539 (cl-letf (((default-file-modes) ?\700)) (make-directory dir t))
540 (setq attrs (file-attributes dir 'integer)))
542 ;; Check that it's safe for use.
543 (let* ((uid (nth 2 attrs))
544 (w32 (eq system-type 'windows-nt))
545 (unsafe (cond
546 ((not (eq t (car attrs)))
547 (if (null attrs) "its attributes can't be checked"
548 (format "it is a %s"
549 (if (stringp (car attrs))
550 "symlink" "file"))))
551 ((and w32 (zerop uid)) ; on FAT32?
552 (display-warning
553 'server
554 (format-message "\
555 Using `%s' to store Emacs-server authentication files.
556 Directories on FAT32 filesystems are NOT secure against tampering.
557 See variable `server-auth-dir' for details."
558 (file-name-as-directory dir))
559 :warning)
560 nil)
561 ((and (/= uid (user-uid)) ; is the dir ours?
562 (or (not w32)
563 ;; Files created on Windows by Administrator
564 ;; (RID=500) have the Administrators (RID=544)
565 ;; group recorded as the owner.
566 (/= uid 544) (/= (user-uid) 500)))
567 (format "it is not owned by you (owner = %s (%d))"
568 (user-full-name uid) uid))
569 (w32 nil) ; on NTFS?
570 ((/= 0 (logand ?\077 (file-modes dir)))
571 (format "it is accessible by others (%03o)"
572 (file-modes dir)))
573 (t nil))))
574 (when unsafe
575 (error "`%s' is not a safe directory because %s"
576 (expand-file-name dir) unsafe)))))
578 (defun server-generate-key ()
579 "Generate and return a random authentication key.
580 The key is a 64-byte string of random chars in the range `!'..`~'.
581 If called interactively, also inserts it into current buffer."
582 (interactive)
583 (let ((auth-key
584 (cl-loop repeat 64
585 collect (+ 33 (random 94)) into auth
586 finally return (concat auth))))
587 (if (called-interactively-p 'interactive)
588 (insert auth-key))
589 auth-key))
591 (defun server-get-auth-key ()
592 "Return server's authentication key.
594 If `server-auth-key' is nil, just call `server-generate-key'.
595 Otherwise, if `server-auth-key' is a valid key, return it.
596 If the key is not valid, signal an error."
597 (if server-auth-key
598 (if (string-match-p "^[!-~]\\{64\\}$" server-auth-key)
599 server-auth-key
600 (error "The key `%s' is invalid" server-auth-key))
601 (server-generate-key)))
603 ;;;###autoload
604 (defun server-start (&optional leave-dead inhibit-prompt)
605 "Allow this Emacs process to be a server for client processes.
606 This starts a server communications subprocess through which client
607 \"editors\" can send your editing commands to this Emacs job.
608 To use the server, set up the program `emacsclient' in the Emacs
609 distribution as your standard \"editor\".
611 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
612 kill any existing server communications subprocess.
614 If a server is already running, restart it. If clients are
615 running, ask the user for confirmation first, unless optional
616 argument INHIBIT-PROMPT is non-nil.
618 To force-start a server, do \\[server-force-delete] and then
619 \\[server-start].
621 To check from a Lisp program whether a server is running, use
622 the `server-process' variable."
623 (interactive "P")
624 (when (or (not server-clients)
625 ;; Ask the user before deleting existing clients---except
626 ;; when we can't get user input, which may happen when
627 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
628 (cond
629 ((and (daemonp)
630 (null (cdr (frame-list)))
631 (eq (selected-frame) terminal-frame))
632 leave-dead)
633 (inhibit-prompt t)
634 (t (yes-or-no-p
635 "The current server still has clients; delete them? "))))
636 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
637 (server-file (expand-file-name server-name server-dir)))
638 (when server-process
639 ;; kill it dead!
640 (ignore-errors (delete-process server-process)))
641 ;; Check to see if an uninitialized external socket has been
642 ;; passed in, if that is the case, skip checking
643 ;; `server-running-p' as this will return the wrong result.
644 (if (and internal--daemon-sockname
645 (not server--external-socket-initialized))
646 (setq server--external-socket-initialized t)
647 ;; Delete the socket files made by previous server invocations.
648 (if (not (eq t (server-running-p server-name)))
649 ;; Remove any leftover socket or authentication file.
650 (ignore-errors
651 (let (delete-by-moving-to-trash)
652 (delete-file server-file)))
653 (setq server-mode nil) ;; already set by the minor mode code
654 (display-warning
655 'server
656 (concat "Unable to start the Emacs server.\n"
657 (format "There is an existing Emacs server, named %S.\n"
658 server-name)
659 (substitute-command-keys
660 "To start the server in this Emacs process, stop the existing
661 server or call `\\[server-force-delete]' to forcibly disconnect it."))
662 :warning)
663 (setq leave-dead t)))
664 ;; If this Emacs already had a server, clear out associated status.
665 (while server-clients
666 (server-delete-client (car server-clients)))
667 ;; Now any previous server is properly stopped.
668 (if leave-dead
669 (progn
670 (unless (eq t leave-dead) (server-log (message "Server stopped")))
671 (setq server-process nil))
672 ;; Make sure there is a safe directory in which to place the socket.
673 (server-ensure-safe-dir server-dir)
674 (when server-process
675 (server-log (message "Restarting server")))
676 (cl-letf (((default-file-modes) ?\700))
677 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
678 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
679 (add-hook 'kill-emacs-query-functions
680 'server-kill-emacs-query-function)
681 ;; We put server's kill-emacs-hook after the others, so that
682 ;; frames are not deleted too early, because doing that
683 ;; would severely degrade our abilities to communicate with
684 ;; the user, while some hooks may wish to ask the user
685 ;; questions (e.g., desktop-kill).
686 (add-hook 'kill-emacs-hook 'server-force-stop t) ;Cleanup upon exit.
687 (setq server-process
688 (apply #'make-network-process
689 :name server-name
690 :server t
691 :noquery t
692 :sentinel #'server-sentinel
693 :filter #'server-process-filter
694 :use-external-socket t
695 ;; We must receive file names without being decoded.
696 ;; Those are decoded by server-process-filter according
697 ;; to file-name-coding-system. Also don't get
698 ;; confused by CRs since we don't quote them.
699 :coding 'raw-text-unix
700 ;; The other args depend on the kind of socket used.
701 (if server-use-tcp
702 (list :family 'ipv4 ;; We're not ready for IPv6 yet
703 :service (or server-port t)
704 :host (or server-host 'local)
705 :plist '(:authenticated nil))
706 (list :family 'local
707 :service server-file
708 :plist '(:authenticated t)))))
709 (unless server-process (error "Could not start server process"))
710 (process-put server-process :server-file server-file)
711 (when server-use-tcp
712 (let ((auth-key (server-get-auth-key)))
713 (process-put server-process :auth-key auth-key)
714 (with-temp-file server-file
715 (set-buffer-multibyte nil)
716 (setq buffer-file-coding-system 'no-conversion)
717 (insert (format-network-address
718 (process-contact server-process :local))
719 " " (number-to-string (emacs-pid)) ; Kept for compatibility
720 "\n" auth-key)))))))))
722 (defun server-force-stop ()
723 "Kill all connections to the current server.
724 This function is meant to be called from `kill-emacs-hook'."
725 (server-start t t))
727 ;;;###autoload
728 (defun server-force-delete (&optional name)
729 "Unconditionally delete connection file for server NAME.
730 If server is running, it is first stopped.
731 NAME defaults to `server-name'. With argument, ask for NAME."
732 (interactive
733 (list (if current-prefix-arg
734 (read-string "Server name: " nil nil server-name))))
735 (when server-mode (with-temp-message nil (server-mode -1)))
736 (let ((file (expand-file-name (or name server-name)
737 (if server-use-tcp
738 server-auth-dir
739 server-socket-dir))))
740 (condition-case nil
741 (let (delete-by-moving-to-trash)
742 (delete-file file)
743 (message "Connection file %S deleted" file))
744 (file-error
745 (message "No connection file %S" file)))))
747 (defun server-running-p (&optional name)
748 "Test whether server NAME is running.
750 Return values:
751 nil the server is definitely not running.
752 t the server seems to be running.
753 something else we cannot determine whether it's running without using
754 commands which may have to wait for a long time.
756 This function can return non-nil if the server was started by some other
757 Emacs process. To check from a Lisp program whether a server was started
758 by the current Emacs process, use the `server-process' variable."
759 (unless name (setq name server-name))
760 (condition-case nil
761 (if server-use-tcp
762 (with-temp-buffer
763 (insert-file-contents-literally (expand-file-name name server-auth-dir))
764 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
765 (assq 'comm
766 (process-attributes
767 (string-to-number (match-string 1))))
769 :other))
770 (delete-process
771 (make-network-process
772 :name "server-client-test" :family 'local :server nil :noquery t
773 :service (expand-file-name name server-socket-dir)))
775 (file-error nil)))
777 ;;;###autoload
778 (define-minor-mode server-mode
779 "Toggle Server mode.
780 With a prefix argument ARG, enable Server mode if ARG is
781 positive, and disable it otherwise. If called from Lisp, enable
782 Server mode if ARG is omitted or nil.
784 Server mode runs a process that accepts commands from the
785 `emacsclient' program. See Info node `Emacs server' and
786 `server-start' for details."
787 :global t
788 :group 'server
789 :version "22.1"
790 ;; Fixme: Should this check for an existing server socket and do
791 ;; nothing if there is one (for multiple Emacs sessions)?
792 (server-start (not server-mode)))
794 (defun server-eval-and-print (expr proc)
795 "Eval EXPR and send the result back to client PROC."
796 ;; While we're running asynchronously (from a process filter), it is likely
797 ;; that the emacsclient command was run in response to a user
798 ;; action, so the user probably knows that Emacs is processing this
799 ;; emacsclient request, so if we get a C-g it's likely that the user
800 ;; intended it to interrupt us rather than interrupt whatever Emacs
801 ;; was doing before it started handling the process filter.
802 ;; Hence `with-local-quit' (bug#6585).
803 (let ((v (with-local-quit (eval (car (read-from-string expr))))))
804 (when proc
805 (with-temp-buffer
806 (let ((standard-output (current-buffer)))
807 (pp v)
808 (let ((text (buffer-substring-no-properties
809 (point-min) (point-max))))
810 (server-reply-print (server-quote-arg text) proc)))))))
812 (defconst server-msg-size 1024
813 "Maximum size of a message sent to a client.")
815 (defun server-reply-print (qtext proc)
816 "Send a `-print QTEXT' command to client PROC.
817 QTEXT must be already quoted.
818 This handles splitting the command if it would be bigger than
819 `server-msg-size'."
820 (let ((prefix "-print ")
821 part)
822 (while (> (+ (length qtext) (length prefix) 1) server-msg-size)
823 ;; We have to split the string
824 (setq part (substring qtext 0 (- server-msg-size (length prefix) 1)))
825 ;; Don't split in the middle of a quote sequence
826 (if (string-match "\\(^\\|[^&]\\)&\\(&&\\)*$" part)
827 ;; There is an uneven number of & at the end
828 (setq part (substring part 0 -1)))
829 (setq qtext (substring qtext (length part)))
830 (server-send-string proc (concat prefix part "\n"))
831 (setq prefix "-print-nonl "))
832 (server-send-string proc (concat prefix qtext "\n"))))
834 (defun server-create-tty-frame (tty type proc)
835 (unless tty
836 (error "Invalid terminal device"))
837 (unless type
838 (error "Invalid terminal type"))
839 (add-to-list 'frame-inherited-parameters 'client)
840 (let ((frame
841 (server-with-environment
842 (process-get proc 'env)
843 '("LANG" "LC_CTYPE" "LC_ALL"
844 ;; For tgetent(3); list according to ncurses(3).
845 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
846 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
847 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
848 "TERMINFO_DIRS" "TERMPATH"
849 ;; rxvt wants these
850 "COLORFGBG" "COLORTERM")
851 (make-frame `((window-system . nil)
852 (tty . ,tty)
853 (tty-type . ,type)
854 ;; Ignore nowait here; we always need to
855 ;; clean up opened ttys when the client dies.
856 (client . ,proc)
857 ;; This is a leftover from an earlier
858 ;; attempt at making it possible for process
859 ;; run in the server process to use the
860 ;; environment of the client process.
861 ;; It has no effect now and to make it work
862 ;; we'd need to decide how to make
863 ;; process-environment interact with client
864 ;; envvars, and then to change the
865 ;; C functions `child_setup' and
866 ;; `getenv_internal' accordingly.
867 (environment . ,(process-get proc 'env)))))))
869 ;; ttys don't use the `display' parameter, but callproc.c does to set
870 ;; the DISPLAY environment on subprocesses.
871 (set-frame-parameter frame 'display
872 (getenv-internal "DISPLAY" (process-get proc 'env)))
873 (select-frame frame)
874 (process-put proc 'frame frame)
875 (process-put proc 'terminal (frame-terminal frame))
876 frame))
878 (defun server-create-window-system-frame (display nowait proc parent-id
879 &optional parameters)
880 (let* ((display (or display
881 (frame-parameter nil 'display)
882 (error "Please specify display.")))
883 (w (or (cdr (assq 'window-system parameters))
884 (window-system-for-display display))))
886 ;; Special case for ns. This is because DISPLAY may not be set at all
887 ;; which in the ns case isn't an error. The variable display then becomes
888 ;; the fully qualified hostname, which make-frame-on-display below
889 ;; does not understand and throws an error.
890 ;; It may also be a valid X display, but if Emacs is compiled for ns, it
891 ;; can not make X frames.
892 (if (featurep 'ns-win)
893 (setq w 'ns display "ns")
894 ;; FIXME! Not sure what this was for, and not sure how it should work
895 ;; in the cl-defmethod new world!
896 ;;(unless (assq w window-system-initialization-alist)
897 ;; (setq w nil))
900 (cond (w
901 ;; Flag frame as client-created, but use a dummy client.
902 ;; This will prevent the frame from being deleted when
903 ;; emacsclient quits while also preventing
904 ;; `server-save-buffers-kill-terminal' from unexpectedly
905 ;; killing emacs on that frame.
906 (let* ((params `((client . ,(if nowait 'nowait proc))
907 ;; This is a leftover, see above.
908 (environment . ,(process-get proc 'env))
909 ,@parameters))
910 frame)
911 (if parent-id
912 (push (cons 'parent-id (string-to-number parent-id)) params))
913 (add-to-list 'frame-inherited-parameters 'client)
914 (setq frame (make-frame-on-display display params))
915 (server-log (format "%s created" frame) proc)
916 (select-frame frame)
917 (process-put proc 'frame frame)
918 (process-put proc 'terminal (frame-terminal frame))
919 frame))
922 (server-log "Window system unsupported" proc)
923 (server-send-string proc "-window-system-unsupported \n")
924 nil))))
926 (defun server-goto-toplevel (proc)
927 (condition-case nil
928 ;; If we're running isearch, we must abort it to allow Emacs to
929 ;; display the buffer and switch to it.
930 (dolist (buffer (buffer-list))
931 (with-current-buffer buffer
932 (when (bound-and-true-p isearch-mode)
933 (isearch-cancel))))
934 ;; Signaled by isearch-cancel.
935 (quit (message nil)))
936 (when (> (recursion-depth) 0)
937 ;; We're inside a minibuffer already, so if the emacs-client is trying
938 ;; to open a frame on a new display, we might end up with an unusable
939 ;; frame because input from that display will be blocked (until exiting
940 ;; the minibuffer). Better exit this minibuffer right away.
941 ;; Similarly with recursive-edits such as the splash screen.
942 (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
943 (top-level)))
945 ;; We use various special properties on process objects:
946 ;; - `env' stores the info about the environment of the emacsclient process.
947 ;; - `continuation' is a no-arg function that we need to execute. It contains
948 ;; commands we wanted to execute in some earlier invocation of the process
949 ;; filter but that we somehow were unable to process at that time
950 ;; (e.g. because we first need to throw to the toplevel).
952 (defun server-execute-continuation (proc)
953 (let ((continuation (process-get proc 'continuation)))
954 (process-put proc 'continuation nil)
955 (if continuation (ignore-errors (funcall continuation)))))
957 (cl-defun server-process-filter (proc string)
958 "Process a request from the server to edit some files.
959 PROC is the server process. STRING consists of a sequence of
960 commands prefixed by a dash. Some commands have arguments;
961 these are &-quoted and need to be decoded by `server-unquote-arg'.
962 The filter parses and executes these commands.
964 To illustrate the protocol, here is an example command that
965 emacsclient sends to create a new X frame (note that the whole
966 sequence is sent on a single line):
968 -env HOME=/home/lorentey
969 -env DISPLAY=:0.0
970 ... lots of other -env commands
971 -display :0.0
972 -window-system
974 The following commands are accepted by the server:
976 `-auth AUTH-STRING'
977 Authenticate the client using the secret authentication string
978 AUTH-STRING.
980 `-env NAME=VALUE'
981 An environment variable on the client side.
983 `-dir DIRNAME'
984 The current working directory of the client process.
986 `-current-frame'
987 Forbid the creation of new frames.
989 `-frame-parameters ALIST'
990 Set the parameters of the created frame.
992 `-nowait'
993 Request that the next frame created should not be
994 associated with this client.
996 `-display DISPLAY'
997 Set the display name to open X frames on.
999 `-position LINE[:COLUMN]'
1000 Go to the given line and column number
1001 in the next file opened.
1003 `-file FILENAME'
1004 Load the given file in the current frame.
1006 `-eval EXPR'
1007 Evaluate EXPR as a Lisp expression and return the
1008 result in -print commands.
1010 `-window-system'
1011 Open a new X frame.
1013 `-tty DEVICENAME TYPE'
1014 Open a new tty frame at the client.
1016 `-suspend'
1017 Suspend this tty frame. The client sends this string in
1018 response to SIGTSTP and SIGTTOU. The server must cease all I/O
1019 on this tty until it gets a -resume command.
1021 `-resume'
1022 Resume this tty frame. The client sends this string when it
1023 gets the SIGCONT signal and it is the foreground process on its
1024 controlling tty.
1026 `-ignore COMMENT'
1027 Do nothing, but put the comment in the server log.
1028 Useful for debugging.
1031 The following commands are accepted by the client:
1033 `-emacs-pid PID'
1034 Describes the process id of the Emacs process;
1035 used to forward window change signals to it.
1037 `-window-system-unsupported'
1038 Signals that the server does not support creating X frames;
1039 the client must try again with a tty frame.
1041 `-print STRING'
1042 Print STRING on stdout. Used to send values
1043 returned by -eval.
1045 `-print-nonl STRING'
1046 Print STRING on stdout. Used to continue a
1047 preceding -print command that would be too big to send
1048 in a single message.
1050 `-error DESCRIPTION'
1051 Signal an error and delete process PROC.
1053 `-suspend'
1054 Suspend this terminal, i.e., stop the client process.
1055 Sent when the user presses C-z."
1056 (server-log (concat "Received " string) proc)
1057 ;; First things first: let's check the authentication
1058 (unless (process-get proc :authenticated)
1059 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
1060 (equal (match-string 1 string) (process-get proc :auth-key)))
1061 (progn
1062 (setq string (substring string (match-end 0)))
1063 (process-put proc :authenticated t)
1064 (server-log "Authentication successful" proc))
1065 (server-log "Authentication failed" proc)
1066 (server-send-string
1067 proc (concat "-error " (server-quote-arg "Authentication failed")))
1068 ;; Before calling `delete-process', give emacsclient time to
1069 ;; receive the error string and shut down on its own.
1070 (sit-for 1)
1071 (delete-process proc)
1072 ;; We return immediately.
1073 (cl-return-from server-process-filter)))
1074 (let ((prev (process-get proc 'previous-string)))
1075 (when prev
1076 (setq string (concat prev string))
1077 (process-put proc 'previous-string nil)))
1078 (condition-case err
1079 (progn
1080 (server-add-client proc)
1081 ;; Send our pid
1082 (server-send-string proc (concat "-emacs-pid "
1083 (number-to-string (emacs-pid)) "\n"))
1084 (if (not (string-match "\n" string))
1085 ;; Save for later any partial line that remains.
1086 (when (> (length string) 0)
1087 (process-put proc 'previous-string string))
1089 ;; In earlier versions of server.el (where we used an `emacsserver'
1090 ;; process), there could be multiple lines. Nowadays this is not
1091 ;; supported any more.
1092 (cl-assert (eq (match-end 0) (length string)))
1093 (let ((request (substring string 0 (match-beginning 0)))
1094 (coding-system (or file-name-coding-system
1095 default-file-name-coding-system))
1096 nowait ; t if emacsclient does not want to wait for us.
1097 frame ; Frame opened for the client (if any).
1098 display ; Open frame on this display.
1099 parent-id ; Window ID for XEmbed
1100 dontkill ; t if client should not be killed.
1101 commands
1103 use-current-frame
1104 frame-parameters ;parameters for newly created frame
1105 tty-name ; nil, `window-system', or the tty name.
1106 tty-type ; string.
1107 files
1108 filepos
1109 args-left
1110 create-frame-func)
1111 ;; Remove this line from STRING.
1112 (setq string (substring string (match-end 0)))
1113 (setq args-left
1114 (mapcar 'server-unquote-arg (split-string request " " t)))
1115 (while args-left
1116 (pcase (pop args-left)
1117 ;; -version CLIENT-VERSION: obsolete at birth.
1118 (`"-version" (pop args-left))
1120 ;; -nowait: Emacsclient won't wait for a result.
1121 (`"-nowait" (setq nowait t))
1123 ;; -current-frame: Don't create frames.
1124 (`"-current-frame" (setq use-current-frame t))
1126 ;; -frame-parameters: Set frame parameters
1127 (`"-frame-parameters"
1128 (let ((alist (pop args-left)))
1129 (if coding-system
1130 (setq alist (decode-coding-string alist coding-system)))
1131 (setq frame-parameters (car (read-from-string alist)))))
1133 ;; -display DISPLAY:
1134 ;; Open X frames on the given display instead of the default.
1135 (`"-display"
1136 (setq display (pop args-left))
1137 (if (zerop (length display)) (setq display nil)))
1139 ;; -parent-id ID:
1140 ;; Open X frame within window ID, via XEmbed.
1141 (`"-parent-id"
1142 (setq parent-id (pop args-left))
1143 (if (zerop (length parent-id)) (setq parent-id nil)))
1145 ;; -window-system: Open a new X frame.
1146 (`"-window-system"
1147 (if (fboundp 'x-create-frame)
1148 (setq dontkill t
1149 tty-name 'window-system)))
1151 ;; -resume: Resume a suspended tty frame.
1152 (`"-resume"
1153 (let ((terminal (process-get proc 'terminal)))
1154 (setq dontkill t)
1155 (push (lambda ()
1156 (when (eq (terminal-live-p terminal) t)
1157 (resume-tty terminal)))
1158 commands)))
1160 ;; -suspend: Suspend the client's frame. (In case we
1161 ;; get out of sync, and a C-z sends a SIGTSTP to
1162 ;; emacsclient.)
1163 (`"-suspend"
1164 (let ((terminal (process-get proc 'terminal)))
1165 (setq dontkill t)
1166 (push (lambda ()
1167 (when (eq (terminal-live-p terminal) t)
1168 (suspend-tty terminal)))
1169 commands)))
1171 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1172 ;; (The given comment appears in the server log.)
1173 (`"-ignore"
1174 (setq dontkill t)
1175 (pop args-left))
1177 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1178 ;; (But if we see -window-system later, use that.)
1179 (`"-tty"
1180 (setq tty-name (pop args-left)
1181 tty-type (pop args-left)
1182 dontkill (or dontkill
1183 (not use-current-frame)))
1184 ;; On Windows, emacsclient always asks for a tty
1185 ;; frame. If running a GUI server, force the frame
1186 ;; type to GUI. (Cygwin is perfectly happy with
1187 ;; multi-tty support, so don't override the user's
1188 ;; choice there.) In daemon mode on Windows, we can't
1189 ;; make tty frames, so force the frame type to GUI
1190 ;; there too.
1191 (when (and (eq system-type 'windows-nt)
1192 (or (daemonp)
1193 (eq window-system 'w32)))
1194 (push "-window-system" args-left)))
1196 ;; -position LINE[:COLUMN]: Set point to the given
1197 ;; position in the next file.
1198 (`"-position"
1199 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1200 (car args-left)))
1201 (error "Invalid -position command in client args"))
1202 (let ((arg (pop args-left)))
1203 (setq filepos
1204 (cons (string-to-number (match-string 1 arg))
1205 (string-to-number (or (match-string 2 arg)
1206 ""))))))
1208 ;; -file FILENAME: Load the given file.
1209 (`"-file"
1210 (let ((file (pop args-left)))
1211 (if coding-system
1212 (setq file (decode-coding-string file coding-system)))
1213 ;; Allow Cygwin's emacsclient to be used as a file
1214 ;; handler on MS-Windows, in which case FILENAME
1215 ;; might start with a drive letter.
1216 (when (and (fboundp 'cygwin-convert-file-name-from-windows)
1217 (string-match "\\`[A-Za-z]:" file))
1218 (setq file (cygwin-convert-file-name-from-windows file)))
1219 (setq file (expand-file-name file dir))
1220 (push (cons file filepos) files)
1221 (server-log (format "New file: %s %s"
1222 file (or filepos ""))
1223 proc))
1224 (setq filepos nil))
1226 ;; -eval EXPR: Evaluate a Lisp expression.
1227 (`"-eval"
1228 (if use-current-frame
1229 (setq use-current-frame 'always))
1230 (let ((expr (pop args-left)))
1231 (if coding-system
1232 (setq expr (decode-coding-string expr coding-system)))
1233 (push (lambda () (server-eval-and-print expr proc))
1234 commands)
1235 (setq filepos nil)))
1237 ;; -env NAME=VALUE: An environment variable.
1238 (`"-env"
1239 (let ((var (pop args-left)))
1240 ;; XXX Variables should be encoded as in getenv/setenv.
1241 (process-put proc 'env
1242 (cons var (process-get proc 'env)))))
1244 ;; -dir DIRNAME: The cwd of the emacsclient process.
1245 (`"-dir"
1246 (setq dir (pop args-left))
1247 (if coding-system
1248 (setq dir (decode-coding-string dir coding-system)))
1249 (setq dir (command-line-normalize-file-name dir))
1250 (process-put proc 'server-client-directory dir))
1252 ;; Unknown command.
1253 (arg (error "Unknown command: %s" arg))))
1255 ;; If both -no-wait and -tty are given with file or sexp
1256 ;; arguments, use an existing frame.
1257 (and nowait
1258 (not (eq tty-name 'window-system))
1259 (or files commands)
1260 (setq use-current-frame t))
1262 (setq create-frame-func
1263 (lambda ()
1264 (cond
1265 ((and use-current-frame
1266 (or (eq use-current-frame 'always)
1267 ;; We can't use the Emacs daemon's
1268 ;; terminal frame.
1269 (not (and (daemonp)
1270 (null (cdr (frame-list)))
1271 (eq (selected-frame)
1272 terminal-frame)))))
1273 (setq tty-name nil tty-type nil)
1274 (if display (server-select-display display)))
1275 ((or (and (eq system-type 'windows-nt)
1276 (daemonp)
1277 (setq display "w32"))
1278 (eq tty-name 'window-system))
1279 (server-create-window-system-frame display nowait proc
1280 parent-id
1281 frame-parameters))
1282 ;; When resuming on a tty, tty-name is nil.
1283 (tty-name
1284 (server-create-tty-frame tty-name tty-type proc)))))
1286 (process-put
1287 proc 'continuation
1288 (lambda ()
1289 (with-current-buffer (get-buffer-create server-buffer)
1290 ;; Use the same cwd as the emacsclient, if possible, so
1291 ;; relative file names work correctly, even in `eval'.
1292 (let ((default-directory
1293 (if (and dir (file-directory-p dir))
1294 dir default-directory)))
1295 (server-execute proc files nowait commands
1296 dontkill create-frame-func tty-name)))))
1298 (when (or frame files)
1299 (server-goto-toplevel proc))
1301 (server-execute-continuation proc))))
1302 ;; condition-case
1303 (error (server-return-error proc err))))
1305 (defun server-execute (proc files nowait commands dontkill create-frame-func tty-name)
1306 ;; This is run from timers and process-filters, i.e. "asynchronously".
1307 ;; But w.r.t the user, this is not really asynchronous since the timer
1308 ;; is run after 0s and the process-filter is run in response to the
1309 ;; user running `emacsclient'. So it is OK to override the
1310 ;; inhibit-quit flag, which is good since `commands' (as well as
1311 ;; find-file-noselect via the major-mode) can run arbitrary code,
1312 ;; including code that needs to wait.
1313 (with-local-quit
1314 (condition-case err
1315 (let* ((buffers (server-visit-files files proc nowait))
1316 ;; If we were told only to open a new client, obey
1317 ;; `initial-buffer-choice' if it specifies a file
1318 ;; or a function.
1319 (initial-buffer (unless (or files commands)
1320 (let ((buf
1321 (cond ((stringp initial-buffer-choice)
1322 (find-file-noselect initial-buffer-choice))
1323 ((functionp initial-buffer-choice)
1324 (funcall initial-buffer-choice)))))
1325 (if (buffer-live-p buf) buf (get-buffer-create "*scratch*")))))
1326 ;; Set current buffer so that newly created tty frames
1327 ;; show the correct buffer initially.
1328 (frame (with-current-buffer (or (car buffers)
1329 initial-buffer
1330 (current-buffer))
1331 (prog1
1332 (funcall create-frame-func)
1333 ;; Switch to initial buffer in case the frame was reused.
1334 (when initial-buffer
1335 (switch-to-buffer initial-buffer 'norecord))))))
1337 (mapc 'funcall (nreverse commands))
1339 ;; Delete the client if necessary.
1340 (cond
1341 (nowait
1342 ;; Client requested nowait; return immediately.
1343 (server-log "Close nowait client" proc)
1344 (server-delete-client proc))
1345 ((and (not dontkill) (null buffers))
1346 ;; This client is empty; get rid of it immediately.
1347 (server-log "Close empty client" proc)
1348 (server-delete-client proc)))
1349 (cond
1350 ((or isearch-mode (minibufferp))
1351 nil)
1352 ((and frame (null buffers))
1353 (run-hooks 'server-after-make-frame-hook)
1354 (message "%s" (substitute-command-keys
1355 "When done with this frame, type \\[delete-frame]")))
1356 ((not (null buffers))
1357 (run-hooks 'server-after-make-frame-hook)
1358 (server-switch-buffer (car buffers) nil (cdr (car files)))
1359 (run-hooks 'server-switch-hook)
1360 (unless nowait
1361 (message "%s" (substitute-command-keys
1362 "When done with a buffer, type \\[server-edit]")))))
1363 (when (and frame (null tty-name))
1364 (server-unselect-display frame)))
1365 ((quit error)
1366 (when (eq (car err) 'quit)
1367 (message "Quit emacsclient request"))
1368 (server-return-error proc err)))))
1370 (defun server-return-error (proc err)
1371 (ignore-errors
1372 (server-send-string
1373 proc (concat "-error " (server-quote-arg
1374 (error-message-string err))))
1375 (server-log (error-message-string err) proc)
1376 ;; Before calling `delete-process', give emacsclient time to
1377 ;; receive the error string and shut down on its own.
1378 (sit-for 5)
1379 (delete-process proc)))
1381 (defun server-goto-line-column (line-col)
1382 "Move point to the position indicated in LINE-COL.
1383 LINE-COL should be a pair (LINE . COL)."
1384 (when line-col
1385 (goto-char (point-min))
1386 (forward-line (1- (car line-col)))
1387 (let ((column-number (cdr line-col)))
1388 (when (> column-number 0)
1389 (move-to-column (1- column-number))))))
1391 (defun server-visit-files (files proc &optional nowait)
1392 "Find FILES and return a list of buffers created.
1393 FILES is an alist whose elements are (FILENAME . FILEPOS)
1394 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1395 PROC is the client that requested this operation.
1396 NOWAIT non-nil means this client is not waiting for the results,
1397 so don't mark these buffers specially, just visit them normally."
1398 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1399 (let ((last-nonmenu-event t) client-record)
1400 ;; Restore the current buffer afterward, but not using save-excursion,
1401 ;; because we don't want to save point in this buffer
1402 ;; if it happens to be one of those specified by the server.
1403 (save-current-buffer
1404 (dolist (file files)
1405 ;; If there is an existing buffer modified or the file is
1406 ;; modified, revert it. If there is an existing buffer with
1407 ;; deleted file, offer to write it.
1408 (let* ((minibuffer-auto-raise (or server-raise-frame
1409 minibuffer-auto-raise))
1410 (filen (car file))
1411 (obuf (get-file-buffer filen)))
1412 (add-to-history 'file-name-history filen)
1413 (if (null obuf)
1414 (progn
1415 (run-hooks 'pre-command-hook)
1416 (set-buffer (find-file-noselect filen)))
1417 (set-buffer obuf)
1418 ;; separately for each file, in sync with post-command hooks,
1419 ;; with the new buffer current:
1420 (run-hooks 'pre-command-hook)
1421 (cond ((file-exists-p filen)
1422 (when (not (verify-visited-file-modtime obuf))
1423 (revert-buffer t nil)))
1425 (when (y-or-n-p
1426 (concat "File no longer exists: " filen
1427 ", write buffer to file? "))
1428 (write-file filen))))
1429 (unless server-buffer-clients
1430 (setq server-existing-buffer t)))
1431 (server-goto-line-column (cdr file))
1432 (run-hooks 'server-visit-hook)
1433 ;; hooks may be specific to current buffer:
1434 (run-hooks 'post-command-hook))
1435 (unless nowait
1436 ;; When the buffer is killed, inform the clients.
1437 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1438 (push proc server-buffer-clients))
1439 (push (current-buffer) client-record)))
1440 (unless nowait
1441 (process-put proc 'buffers
1442 (nconc (process-get proc 'buffers) client-record)))
1443 client-record))
1445 (defvar server-kill-buffer-running nil
1446 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1448 (defun server-buffer-done (buffer &optional for-killing)
1449 "Mark BUFFER as \"done\" for its client(s).
1450 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1451 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1452 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1453 a temp file).
1454 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1455 (let ((next-buffer nil)
1456 (killed nil))
1457 (dolist (proc server-clients)
1458 (let ((buffers (process-get proc 'buffers)))
1459 (or next-buffer
1460 (setq next-buffer (nth 1 (memq buffer buffers))))
1461 (when buffers ; Ignore bufferless clients.
1462 (setq buffers (delq buffer buffers))
1463 ;; Delete all dead buffers from PROC.
1464 (dolist (b buffers)
1465 (and (bufferp b)
1466 (not (buffer-live-p b))
1467 (setq buffers (delq b buffers))))
1468 (process-put proc 'buffers buffers)
1469 ;; If client now has no pending buffers,
1470 ;; tell it that it is done, and forget it entirely.
1471 (unless buffers
1472 (server-log "Close" proc)
1473 (if for-killing
1474 ;; `server-delete-client' might delete the client's
1475 ;; frames, which might change the current buffer. We
1476 ;; don't want that (bug#640).
1477 (save-current-buffer
1478 (server-delete-client proc))
1479 (server-delete-client proc))))))
1480 (when (and (bufferp buffer) (buffer-name buffer))
1481 ;; We may or may not kill this buffer;
1482 ;; if we do, do not call server-buffer-done recursively
1483 ;; from kill-buffer-hook.
1484 (let ((server-kill-buffer-running t))
1485 (with-current-buffer buffer
1486 (setq server-buffer-clients nil)
1487 (run-hooks 'server-done-hook))
1488 ;; Notice whether server-done-hook killed the buffer.
1489 (if (null (buffer-name buffer))
1490 (setq killed t)
1491 ;; Don't bother killing or burying the buffer
1492 ;; when we are called from kill-buffer.
1493 (unless for-killing
1494 (when (and (not killed)
1495 server-kill-new-buffers
1496 (with-current-buffer buffer
1497 (not server-existing-buffer)))
1498 (setq killed t)
1499 (bury-buffer buffer)
1500 ;; Prevent kill-buffer from prompting (Bug#3696).
1501 (with-current-buffer buffer
1502 (set-buffer-modified-p nil))
1503 (kill-buffer buffer))
1504 (unless killed
1505 (if (server-temp-file-p buffer)
1506 (progn
1507 (with-current-buffer buffer
1508 (set-buffer-modified-p nil))
1509 (kill-buffer buffer)
1510 (setq killed t))
1511 (bury-buffer buffer)))))))
1512 (list next-buffer killed)))
1514 (defun server-temp-file-p (&optional buffer)
1515 "Return non-nil if BUFFER contains a file considered temporary.
1516 These are files whose names suggest they are repeatedly
1517 reused to pass information to another program.
1519 The variable `server-temp-file-regexp' controls which filenames
1520 are considered temporary."
1521 (and (buffer-file-name buffer)
1522 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1524 (defun server-done ()
1525 "Offer to save current buffer, mark it as \"done\" for clients.
1526 This kills or buries the buffer, then returns a list
1527 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1528 as a suggestion for what to select next, or nil.
1529 KILLED is t if we killed BUFFER, which happens if it was created
1530 specifically for the clients and did not exist before their request for it."
1531 (when server-buffer-clients
1532 (if (server-temp-file-p)
1533 ;; For a temp file, save, and do make a non-numeric backup
1534 ;; (unless make-backup-files is nil).
1535 (let ((version-control nil)
1536 (buffer-backed-up nil))
1537 (save-buffer))
1538 (when (and (buffer-modified-p)
1539 buffer-file-name
1540 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1541 (save-buffer)))
1542 (server-buffer-done (current-buffer))))
1544 (defun server-kill-emacs-query-function ()
1545 "Ask before exiting Emacs if it has live clients."
1546 (or (not (let (live-client)
1547 (dolist (proc server-clients)
1548 (when (memq t (mapcar 'buffer-live-p (process-get
1549 proc 'buffers)))
1550 (setq live-client t)))
1551 live-client))
1552 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1554 (defun server-kill-buffer ()
1555 "Remove the current buffer from its clients' buffer list.
1556 Designed to be added to `kill-buffer-hook'."
1557 ;; Prevent infinite recursion if user has made server-done-hook
1558 ;; call kill-buffer.
1559 (or server-kill-buffer-running
1560 (and server-buffer-clients
1561 (let ((server-kill-buffer-running t))
1562 (when server-process
1563 (server-buffer-done (current-buffer) t))))))
1565 (defun server-edit (&optional arg)
1566 "Switch to next server editing buffer; say \"Done\" for current buffer.
1567 If a server buffer is current, it is marked \"done\" and optionally saved.
1568 The buffer is also killed if it did not exist before the clients asked for it.
1569 When all of a client's buffers are marked as \"done\", the client is notified.
1571 Temporary files such as MH <draft> files are always saved and backed up,
1572 no questions asked. (The variable `make-backup-files', if nil, still
1573 inhibits a backup; you can set it locally in a particular buffer to
1574 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1575 which filenames are considered temporary.
1577 If invoked with a prefix argument, or if there is no server process running,
1578 starts server process and that is all. Invoked by \\[server-edit]."
1579 (interactive "P")
1580 (cond
1581 ((or arg
1582 (not server-process)
1583 (memq (process-status server-process) '(signal exit)))
1584 (server-mode 1))
1585 (server-clients (apply 'server-switch-buffer (server-done)))
1586 (t (message "No server editing buffers exist"))))
1588 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1589 "Switch to another buffer, preferably one that has a client.
1590 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1592 KILLED-ONE is t in a recursive call if we have already killed one
1593 temp-file server buffer. This means we should avoid the final
1594 \"switch to some other buffer\" since we've already effectively
1595 done that.
1597 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1598 visit NEXT-BUFFER in an existing window. If non-nil, it should
1599 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1600 (if (null next-buffer)
1601 (progn
1602 (let ((rest server-clients))
1603 (while (and rest (not next-buffer))
1604 (let ((proc (car rest)))
1605 ;; Only look at frameless clients, or those in the selected
1606 ;; frame.
1607 (when (or (not (process-get proc 'frame))
1608 (eq (process-get proc 'frame) (selected-frame)))
1609 (setq next-buffer (car (process-get proc 'buffers))))
1610 (setq rest (cdr rest)))))
1611 (and next-buffer (server-switch-buffer next-buffer killed-one))
1612 (unless (or next-buffer killed-one (window-dedicated-p))
1613 ;; (switch-to-buffer (other-buffer))
1614 (message "No server buffers remain to edit")))
1615 (if (not (buffer-live-p next-buffer))
1616 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1617 ;; and try the next surviving server buffer.
1618 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1619 ;; OK, we know next-buffer is live, let's display and select it.
1620 (if (functionp server-window)
1621 (funcall server-window next-buffer)
1622 (let ((win (get-buffer-window next-buffer 0)))
1623 (if (and win (not server-window))
1624 ;; The buffer is already displayed: just reuse the
1625 ;; window. If FILEPOS is non-nil, use it to replace the
1626 ;; window's own value of point.
1627 (progn
1628 (select-window win)
1629 (set-buffer next-buffer)
1630 (when filepos
1631 (server-goto-line-column filepos)))
1632 ;; Otherwise, let's find an appropriate window.
1633 (cond ((window-live-p server-window)
1634 (select-window server-window))
1635 ((framep server-window)
1636 (unless (frame-live-p server-window)
1637 (setq server-window (make-frame)))
1638 (select-window (frame-selected-window server-window))))
1639 (when (window-minibuffer-p)
1640 (select-window (next-window nil 'nomini 0)))
1641 ;; Move to a non-dedicated window, if we have one.
1642 (when (window-dedicated-p)
1643 (select-window
1644 (get-window-with-predicate
1645 (lambda (w)
1646 (and (not (window-dedicated-p w))
1647 (equal (frame-terminal (window-frame w))
1648 (frame-terminal))))
1649 'nomini 'visible (selected-window))))
1650 (condition-case nil
1651 (switch-to-buffer next-buffer)
1652 ;; After all the above, we might still have ended up with
1653 ;; a minibuffer/dedicated-window (if there's no other).
1654 (error (pop-to-buffer next-buffer)))))))
1655 (when server-raise-frame
1656 (select-frame-set-input-focus (window-frame)))))
1658 ;;;###autoload
1659 (defun server-save-buffers-kill-terminal (arg)
1660 ;; Called from save-buffers-kill-terminal in files.el.
1661 "Offer to save each buffer, then kill the current client.
1662 With ARG non-nil, silently save all file-visiting buffers, then kill.
1664 If emacsclient was started with a list of filenames to edit, then
1665 only these files will be asked to be saved."
1666 (let ((proc (frame-parameter nil 'client)))
1667 (cond ((eq proc 'nowait)
1668 ;; Nowait frames have no client buffer list.
1669 (if (cdr (frame-list))
1670 (progn (save-some-buffers arg)
1671 (delete-frame))
1672 ;; If we're the last frame standing, kill Emacs.
1673 (save-buffers-kill-emacs arg)))
1674 ((processp proc)
1675 (let ((buffers (process-get proc 'buffers)))
1676 ;; If client is bufferless, emulate a normal Emacs exit
1677 ;; and offer to save all buffers. Otherwise, offer to
1678 ;; save only the buffers belonging to the client.
1679 (save-some-buffers
1680 arg (if buffers
1681 (lambda () (memq (current-buffer) buffers))
1683 (server-delete-client proc)))
1684 (t (error "Invalid client frame")))))
1686 (define-key ctl-x-map "#" 'server-edit)
1688 (defun server-unload-function ()
1689 "Unload the Server library."
1690 (server-mode -1)
1691 (substitute-key-definition 'server-edit nil ctl-x-map)
1692 (save-current-buffer
1693 (dolist (buffer (buffer-list))
1694 (set-buffer buffer)
1695 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1696 ;; continue standard unloading
1697 nil)
1699 (defun server-eval-at (server form)
1700 "Contact the Emacs server named SERVER and evaluate FORM there.
1701 Returns the result of the evaluation, or signals an error if it
1702 cannot contact the specified server. For example:
1703 (server-eval-at \"server\" \\='(emacs-pid))
1704 returns the process ID of the Emacs instance running \"server\"."
1705 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
1706 (server-file (expand-file-name server server-dir))
1707 (coding-system-for-read 'binary)
1708 (coding-system-for-write 'binary)
1709 address port secret process)
1710 (unless (file-exists-p server-file)
1711 (error "No such server: %s" server))
1712 (with-temp-buffer
1713 (when server-use-tcp
1714 (let ((coding-system-for-read 'no-conversion))
1715 (insert-file-contents server-file)
1716 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1717 (error "Invalid auth file"))
1718 (setq address (match-string 1)
1719 port (string-to-number (match-string 2)))
1720 (forward-line 1)
1721 (setq secret (buffer-substring (point) (line-end-position)))
1722 (erase-buffer)))
1723 (unless (setq process (make-network-process
1724 :name "eval-at"
1725 :buffer (current-buffer)
1726 :host address
1727 :service (if server-use-tcp port server-file)
1728 :family (if server-use-tcp 'ipv4 'local)
1729 :noquery t))
1730 (error "Unable to contact the server"))
1731 (if server-use-tcp
1732 (process-send-string process (concat "-auth " secret "\n")))
1733 (process-send-string process
1734 (concat "-eval "
1735 (server-quote-arg (format "%S" form))
1736 "\n"))
1737 (while (memq (process-status process) '(open run))
1738 (accept-process-output process 0 10))
1739 (goto-char (point-min))
1740 ;; If the result is nil, there's nothing in the buffer. If the
1741 ;; result is non-nil, it's after "-print ".
1742 (let ((answer ""))
1743 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t)
1744 (setq answer
1745 (concat answer
1746 (buffer-substring (point)
1747 (progn (skip-chars-forward "^\n")
1748 (point))))))
1749 (if (not (equal answer ""))
1750 (read (decode-coding-string (server-unquote-arg answer)
1751 'emacs-internal)))))))
1754 (provide 'server)
1756 ;;; server.el ends here