* lisp/emacs-lisp/benchmark.el (benchmark-run): Allow variable.
[emacs.git] / lisp / server.el
blobff03cbe622c4ee674309358087fbeadc8373897c
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]."
620 (interactive "P")
621 (when (or (not server-clients)
622 ;; Ask the user before deleting existing clients---except
623 ;; when we can't get user input, which may happen when
624 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
625 (cond
626 ((and (daemonp)
627 (null (cdr (frame-list)))
628 (eq (selected-frame) terminal-frame))
629 leave-dead)
630 (inhibit-prompt t)
631 (t (yes-or-no-p
632 "The current server still has clients; delete them? "))))
633 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
634 (server-file (expand-file-name server-name server-dir)))
635 (when server-process
636 ;; kill it dead!
637 (ignore-errors (delete-process server-process)))
638 ;; Check to see if an uninitialized external socket has been
639 ;; passed in, if that is the case, skip checking
640 ;; `server-running-p' as this will return the wrong result.
641 (if (and internal--daemon-sockname
642 (not server--external-socket-initialized))
643 (setq server--external-socket-initialized t)
644 ;; Delete the socket files made by previous server invocations.
645 (if (not (eq t (server-running-p server-name)))
646 ;; Remove any leftover socket or authentication file.
647 (ignore-errors
648 (let (delete-by-moving-to-trash)
649 (delete-file server-file)))
650 (setq server-mode nil) ;; already set by the minor mode code
651 (display-warning
652 'server
653 (concat "Unable to start the Emacs server.\n"
654 (format "There is an existing Emacs server, named %S.\n"
655 server-name)
656 (substitute-command-keys
657 "To start the server in this Emacs process, stop the existing
658 server or call `\\[server-force-delete]' to forcibly disconnect it."))
659 :warning)
660 (setq leave-dead t)))
661 ;; If this Emacs already had a server, clear out associated status.
662 (while server-clients
663 (server-delete-client (car server-clients)))
664 ;; Now any previous server is properly stopped.
665 (if leave-dead
666 (progn
667 (unless (eq t leave-dead) (server-log (message "Server stopped")))
668 (setq server-process nil))
669 ;; Make sure there is a safe directory in which to place the socket.
670 (server-ensure-safe-dir server-dir)
671 (when server-process
672 (server-log (message "Restarting server")))
673 (cl-letf (((default-file-modes) ?\700))
674 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
675 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
676 (add-hook 'kill-emacs-query-functions
677 'server-kill-emacs-query-function)
678 ;; We put server's kill-emacs-hook after the others, so that
679 ;; frames are not deleted too early, because doing that
680 ;; would severely degrade our abilities to communicate with
681 ;; the user, while some hooks may wish to ask the user
682 ;; questions (e.g., desktop-kill).
683 (add-hook 'kill-emacs-hook 'server-force-stop t) ;Cleanup upon exit.
684 (setq server-process
685 (apply #'make-network-process
686 :name server-name
687 :server t
688 :noquery t
689 :sentinel #'server-sentinel
690 :filter #'server-process-filter
691 :use-external-socket t
692 ;; We must receive file names without being decoded.
693 ;; Those are decoded by server-process-filter according
694 ;; to file-name-coding-system. Also don't get
695 ;; confused by CRs since we don't quote them.
696 :coding 'raw-text-unix
697 ;; The other args depend on the kind of socket used.
698 (if server-use-tcp
699 (list :family 'ipv4 ;; We're not ready for IPv6 yet
700 :service (or server-port t)
701 :host (or server-host 'local)
702 :plist '(:authenticated nil))
703 (list :family 'local
704 :service server-file
705 :plist '(:authenticated t)))))
706 (unless server-process (error "Could not start server process"))
707 (process-put server-process :server-file server-file)
708 (when server-use-tcp
709 (let ((auth-key (server-get-auth-key)))
710 (process-put server-process :auth-key auth-key)
711 (with-temp-file server-file
712 (set-buffer-multibyte nil)
713 (setq buffer-file-coding-system 'no-conversion)
714 (insert (format-network-address
715 (process-contact server-process :local))
716 " " (number-to-string (emacs-pid)) ; Kept for compatibility
717 "\n" auth-key)))))))))
719 (defun server-force-stop ()
720 "Kill all connections to the current server.
721 This function is meant to be called from `kill-emacs-hook'."
722 (server-start t t))
724 ;;;###autoload
725 (defun server-force-delete (&optional name)
726 "Unconditionally delete connection file for server NAME.
727 If server is running, it is first stopped.
728 NAME defaults to `server-name'. With argument, ask for NAME."
729 (interactive
730 (list (if current-prefix-arg
731 (read-string "Server name: " nil nil server-name))))
732 (when server-mode (with-temp-message nil (server-mode -1)))
733 (let ((file (expand-file-name (or name server-name)
734 (if server-use-tcp
735 server-auth-dir
736 server-socket-dir))))
737 (condition-case nil
738 (let (delete-by-moving-to-trash)
739 (delete-file file)
740 (message "Connection file %S deleted" file))
741 (file-error
742 (message "No connection file %S" file)))))
744 (defun server-running-p (&optional name)
745 "Test whether server NAME is running.
747 Return values:
748 nil the server is definitely not running.
749 t the server seems to be running.
750 something else we cannot determine whether it's running without using
751 commands which may have to wait for a long time."
752 (unless name (setq name server-name))
753 (condition-case nil
754 (if server-use-tcp
755 (with-temp-buffer
756 (insert-file-contents-literally (expand-file-name name server-auth-dir))
757 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
758 (assq 'comm
759 (process-attributes
760 (string-to-number (match-string 1))))
762 :other))
763 (delete-process
764 (make-network-process
765 :name "server-client-test" :family 'local :server nil :noquery t
766 :service (expand-file-name name server-socket-dir)))
768 (file-error nil)))
770 ;;;###autoload
771 (define-minor-mode server-mode
772 "Toggle Server mode.
773 With a prefix argument ARG, enable Server mode if ARG is
774 positive, and disable it otherwise. If called from Lisp, enable
775 Server mode if ARG is omitted or nil.
777 Server mode runs a process that accepts commands from the
778 `emacsclient' program. See Info node `Emacs server' and
779 `server-start' for details."
780 :global t
781 :group 'server
782 :version "22.1"
783 ;; Fixme: Should this check for an existing server socket and do
784 ;; nothing if there is one (for multiple Emacs sessions)?
785 (server-start (not server-mode)))
787 (defun server-eval-and-print (expr proc)
788 "Eval EXPR and send the result back to client PROC."
789 ;; While we're running asynchronously (from a process filter), it is likely
790 ;; that the emacsclient command was run in response to a user
791 ;; action, so the user probably knows that Emacs is processing this
792 ;; emacsclient request, so if we get a C-g it's likely that the user
793 ;; intended it to interrupt us rather than interrupt whatever Emacs
794 ;; was doing before it started handling the process filter.
795 ;; Hence `with-local-quit' (bug#6585).
796 (let ((v (with-local-quit (eval (car (read-from-string expr))))))
797 (when proc
798 (with-temp-buffer
799 (let ((standard-output (current-buffer)))
800 (pp v)
801 (let ((text (buffer-substring-no-properties
802 (point-min) (point-max))))
803 (server-reply-print (server-quote-arg text) proc)))))))
805 (defconst server-msg-size 1024
806 "Maximum size of a message sent to a client.")
808 (defun server-reply-print (qtext proc)
809 "Send a `-print QTEXT' command to client PROC.
810 QTEXT must be already quoted.
811 This handles splitting the command if it would be bigger than
812 `server-msg-size'."
813 (let ((prefix "-print ")
814 part)
815 (while (> (+ (length qtext) (length prefix) 1) server-msg-size)
816 ;; We have to split the string
817 (setq part (substring qtext 0 (- server-msg-size (length prefix) 1)))
818 ;; Don't split in the middle of a quote sequence
819 (if (string-match "\\(^\\|[^&]\\)&\\(&&\\)*$" part)
820 ;; There is an uneven number of & at the end
821 (setq part (substring part 0 -1)))
822 (setq qtext (substring qtext (length part)))
823 (server-send-string proc (concat prefix part "\n"))
824 (setq prefix "-print-nonl "))
825 (server-send-string proc (concat prefix qtext "\n"))))
827 (defun server-create-tty-frame (tty type proc)
828 (unless tty
829 (error "Invalid terminal device"))
830 (unless type
831 (error "Invalid terminal type"))
832 (add-to-list 'frame-inherited-parameters 'client)
833 (let ((frame
834 (server-with-environment
835 (process-get proc 'env)
836 '("LANG" "LC_CTYPE" "LC_ALL"
837 ;; For tgetent(3); list according to ncurses(3).
838 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
839 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
840 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
841 "TERMINFO_DIRS" "TERMPATH"
842 ;; rxvt wants these
843 "COLORFGBG" "COLORTERM")
844 (make-frame `((window-system . nil)
845 (tty . ,tty)
846 (tty-type . ,type)
847 ;; Ignore nowait here; we always need to
848 ;; clean up opened ttys when the client dies.
849 (client . ,proc)
850 ;; This is a leftover from an earlier
851 ;; attempt at making it possible for process
852 ;; run in the server process to use the
853 ;; environment of the client process.
854 ;; It has no effect now and to make it work
855 ;; we'd need to decide how to make
856 ;; process-environment interact with client
857 ;; envvars, and then to change the
858 ;; C functions `child_setup' and
859 ;; `getenv_internal' accordingly.
860 (environment . ,(process-get proc 'env)))))))
862 ;; ttys don't use the `display' parameter, but callproc.c does to set
863 ;; the DISPLAY environment on subprocesses.
864 (set-frame-parameter frame 'display
865 (getenv-internal "DISPLAY" (process-get proc 'env)))
866 (select-frame frame)
867 (process-put proc 'frame frame)
868 (process-put proc 'terminal (frame-terminal frame))
869 frame))
871 (defun server-create-window-system-frame (display nowait proc parent-id
872 &optional parameters)
873 (let* ((display (or display
874 (frame-parameter nil 'display)
875 (error "Please specify display.")))
876 (w (or (cdr (assq 'window-system parameters))
877 (window-system-for-display display))))
879 ;; Special case for ns. This is because DISPLAY may not be set at all
880 ;; which in the ns case isn't an error. The variable display then becomes
881 ;; the fully qualified hostname, which make-frame-on-display below
882 ;; does not understand and throws an error.
883 ;; It may also be a valid X display, but if Emacs is compiled for ns, it
884 ;; can not make X frames.
885 (if (featurep 'ns-win)
886 (setq w 'ns display "ns")
887 ;; FIXME! Not sure what this was for, and not sure how it should work
888 ;; in the cl-defmethod new world!
889 ;;(unless (assq w window-system-initialization-alist)
890 ;; (setq w nil))
893 (cond (w
894 ;; Flag frame as client-created, but use a dummy client.
895 ;; This will prevent the frame from being deleted when
896 ;; emacsclient quits while also preventing
897 ;; `server-save-buffers-kill-terminal' from unexpectedly
898 ;; killing emacs on that frame.
899 (let* ((params `((client . ,(if nowait 'nowait proc))
900 ;; This is a leftover, see above.
901 (environment . ,(process-get proc 'env))
902 ,@parameters))
903 frame)
904 (if parent-id
905 (push (cons 'parent-id (string-to-number parent-id)) params))
906 (add-to-list 'frame-inherited-parameters 'client)
907 (setq frame (make-frame-on-display display params))
908 (server-log (format "%s created" frame) proc)
909 (select-frame frame)
910 (process-put proc 'frame frame)
911 (process-put proc 'terminal (frame-terminal frame))
912 frame))
915 (server-log "Window system unsupported" proc)
916 (server-send-string proc "-window-system-unsupported \n")
917 nil))))
919 (defun server-goto-toplevel (proc)
920 (condition-case nil
921 ;; If we're running isearch, we must abort it to allow Emacs to
922 ;; display the buffer and switch to it.
923 (dolist (buffer (buffer-list))
924 (with-current-buffer buffer
925 (when (bound-and-true-p isearch-mode)
926 (isearch-cancel))))
927 ;; Signaled by isearch-cancel.
928 (quit (message nil)))
929 (when (> (recursion-depth) 0)
930 ;; We're inside a minibuffer already, so if the emacs-client is trying
931 ;; to open a frame on a new display, we might end up with an unusable
932 ;; frame because input from that display will be blocked (until exiting
933 ;; the minibuffer). Better exit this minibuffer right away.
934 ;; Similarly with recursive-edits such as the splash screen.
935 (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
936 (top-level)))
938 ;; We use various special properties on process objects:
939 ;; - `env' stores the info about the environment of the emacsclient process.
940 ;; - `continuation' is a no-arg function that we need to execute. It contains
941 ;; commands we wanted to execute in some earlier invocation of the process
942 ;; filter but that we somehow were unable to process at that time
943 ;; (e.g. because we first need to throw to the toplevel).
945 (defun server-execute-continuation (proc)
946 (let ((continuation (process-get proc 'continuation)))
947 (process-put proc 'continuation nil)
948 (if continuation (ignore-errors (funcall continuation)))))
950 (cl-defun server-process-filter (proc string)
951 "Process a request from the server to edit some files.
952 PROC is the server process. STRING consists of a sequence of
953 commands prefixed by a dash. Some commands have arguments;
954 these are &-quoted and need to be decoded by `server-unquote-arg'.
955 The filter parses and executes these commands.
957 To illustrate the protocol, here is an example command that
958 emacsclient sends to create a new X frame (note that the whole
959 sequence is sent on a single line):
961 -env HOME=/home/lorentey
962 -env DISPLAY=:0.0
963 ... lots of other -env commands
964 -display :0.0
965 -window-system
967 The following commands are accepted by the server:
969 `-auth AUTH-STRING'
970 Authenticate the client using the secret authentication string
971 AUTH-STRING.
973 `-env NAME=VALUE'
974 An environment variable on the client side.
976 `-dir DIRNAME'
977 The current working directory of the client process.
979 `-current-frame'
980 Forbid the creation of new frames.
982 `-frame-parameters ALIST'
983 Set the parameters of the created frame.
985 `-nowait'
986 Request that the next frame created should not be
987 associated with this client.
989 `-display DISPLAY'
990 Set the display name to open X frames on.
992 `-position LINE[:COLUMN]'
993 Go to the given line and column number
994 in the next file opened.
996 `-file FILENAME'
997 Load the given file in the current frame.
999 `-eval EXPR'
1000 Evaluate EXPR as a Lisp expression and return the
1001 result in -print commands.
1003 `-window-system'
1004 Open a new X frame.
1006 `-tty DEVICENAME TYPE'
1007 Open a new tty frame at the client.
1009 `-suspend'
1010 Suspend this tty frame. The client sends this string in
1011 response to SIGTSTP and SIGTTOU. The server must cease all I/O
1012 on this tty until it gets a -resume command.
1014 `-resume'
1015 Resume this tty frame. The client sends this string when it
1016 gets the SIGCONT signal and it is the foreground process on its
1017 controlling tty.
1019 `-ignore COMMENT'
1020 Do nothing, but put the comment in the server log.
1021 Useful for debugging.
1024 The following commands are accepted by the client:
1026 `-emacs-pid PID'
1027 Describes the process id of the Emacs process;
1028 used to forward window change signals to it.
1030 `-window-system-unsupported'
1031 Signals that the server does not support creating X frames;
1032 the client must try again with a tty frame.
1034 `-print STRING'
1035 Print STRING on stdout. Used to send values
1036 returned by -eval.
1038 `-print-nonl STRING'
1039 Print STRING on stdout. Used to continue a
1040 preceding -print command that would be too big to send
1041 in a single message.
1043 `-error DESCRIPTION'
1044 Signal an error and delete process PROC.
1046 `-suspend'
1047 Suspend this terminal, i.e., stop the client process.
1048 Sent when the user presses C-z."
1049 (server-log (concat "Received " string) proc)
1050 ;; First things first: let's check the authentication
1051 (unless (process-get proc :authenticated)
1052 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
1053 (equal (match-string 1 string) (process-get proc :auth-key)))
1054 (progn
1055 (setq string (substring string (match-end 0)))
1056 (process-put proc :authenticated t)
1057 (server-log "Authentication successful" proc))
1058 (server-log "Authentication failed" proc)
1059 (server-send-string
1060 proc (concat "-error " (server-quote-arg "Authentication failed")))
1061 ;; Before calling `delete-process', give emacsclient time to
1062 ;; receive the error string and shut down on its own.
1063 (sit-for 1)
1064 (delete-process proc)
1065 ;; We return immediately.
1066 (cl-return-from server-process-filter)))
1067 (let ((prev (process-get proc 'previous-string)))
1068 (when prev
1069 (setq string (concat prev string))
1070 (process-put proc 'previous-string nil)))
1071 (condition-case err
1072 (progn
1073 (server-add-client proc)
1074 ;; Send our pid
1075 (server-send-string proc (concat "-emacs-pid "
1076 (number-to-string (emacs-pid)) "\n"))
1077 (if (not (string-match "\n" string))
1078 ;; Save for later any partial line that remains.
1079 (when (> (length string) 0)
1080 (process-put proc 'previous-string string))
1082 ;; In earlier versions of server.el (where we used an `emacsserver'
1083 ;; process), there could be multiple lines. Nowadays this is not
1084 ;; supported any more.
1085 (cl-assert (eq (match-end 0) (length string)))
1086 (let ((request (substring string 0 (match-beginning 0)))
1087 (coding-system (or file-name-coding-system
1088 default-file-name-coding-system))
1089 nowait ; t if emacsclient does not want to wait for us.
1090 frame ; Frame opened for the client (if any).
1091 display ; Open frame on this display.
1092 parent-id ; Window ID for XEmbed
1093 dontkill ; t if client should not be killed.
1094 commands
1096 use-current-frame
1097 frame-parameters ;parameters for newly created frame
1098 tty-name ; nil, `window-system', or the tty name.
1099 tty-type ; string.
1100 files
1101 filepos
1102 args-left
1103 create-frame-func)
1104 ;; Remove this line from STRING.
1105 (setq string (substring string (match-end 0)))
1106 (setq args-left
1107 (mapcar 'server-unquote-arg (split-string request " " t)))
1108 (while args-left
1109 (pcase (pop args-left)
1110 ;; -version CLIENT-VERSION: obsolete at birth.
1111 (`"-version" (pop args-left))
1113 ;; -nowait: Emacsclient won't wait for a result.
1114 (`"-nowait" (setq nowait t))
1116 ;; -current-frame: Don't create frames.
1117 (`"-current-frame" (setq use-current-frame t))
1119 ;; -frame-parameters: Set frame parameters
1120 (`"-frame-parameters"
1121 (let ((alist (pop args-left)))
1122 (if coding-system
1123 (setq alist (decode-coding-string alist coding-system)))
1124 (setq frame-parameters (car (read-from-string alist)))))
1126 ;; -display DISPLAY:
1127 ;; Open X frames on the given display instead of the default.
1128 (`"-display"
1129 (setq display (pop args-left))
1130 (if (zerop (length display)) (setq display nil)))
1132 ;; -parent-id ID:
1133 ;; Open X frame within window ID, via XEmbed.
1134 (`"-parent-id"
1135 (setq parent-id (pop args-left))
1136 (if (zerop (length parent-id)) (setq parent-id nil)))
1138 ;; -window-system: Open a new X frame.
1139 (`"-window-system"
1140 (if (fboundp 'x-create-frame)
1141 (setq dontkill t
1142 tty-name 'window-system)))
1144 ;; -resume: Resume a suspended tty frame.
1145 (`"-resume"
1146 (let ((terminal (process-get proc 'terminal)))
1147 (setq dontkill t)
1148 (push (lambda ()
1149 (when (eq (terminal-live-p terminal) t)
1150 (resume-tty terminal)))
1151 commands)))
1153 ;; -suspend: Suspend the client's frame. (In case we
1154 ;; get out of sync, and a C-z sends a SIGTSTP to
1155 ;; emacsclient.)
1156 (`"-suspend"
1157 (let ((terminal (process-get proc 'terminal)))
1158 (setq dontkill t)
1159 (push (lambda ()
1160 (when (eq (terminal-live-p terminal) t)
1161 (suspend-tty terminal)))
1162 commands)))
1164 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1165 ;; (The given comment appears in the server log.)
1166 (`"-ignore"
1167 (setq dontkill t)
1168 (pop args-left))
1170 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1171 ;; (But if we see -window-system later, use that.)
1172 (`"-tty"
1173 (setq tty-name (pop args-left)
1174 tty-type (pop args-left)
1175 dontkill (or dontkill
1176 (not use-current-frame)))
1177 ;; On Windows, emacsclient always asks for a tty
1178 ;; frame. If running a GUI server, force the frame
1179 ;; type to GUI. (Cygwin is perfectly happy with
1180 ;; multi-tty support, so don't override the user's
1181 ;; choice there.) In daemon mode on Windows, we can't
1182 ;; make tty frames, so force the frame type to GUI
1183 ;; there too.
1184 (when (and (eq system-type 'windows-nt)
1185 (or (daemonp)
1186 (eq window-system 'w32)))
1187 (push "-window-system" args-left)))
1189 ;; -position LINE[:COLUMN]: Set point to the given
1190 ;; position in the next file.
1191 (`"-position"
1192 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1193 (car args-left)))
1194 (error "Invalid -position command in client args"))
1195 (let ((arg (pop args-left)))
1196 (setq filepos
1197 (cons (string-to-number (match-string 1 arg))
1198 (string-to-number (or (match-string 2 arg)
1199 ""))))))
1201 ;; -file FILENAME: Load the given file.
1202 (`"-file"
1203 (let ((file (pop args-left)))
1204 (if coding-system
1205 (setq file (decode-coding-string file coding-system)))
1206 ;; Allow Cygwin's emacsclient to be used as a file
1207 ;; handler on MS-Windows, in which case FILENAME
1208 ;; might start with a drive letter.
1209 (when (and (fboundp 'cygwin-convert-file-name-from-windows)
1210 (string-match "\\`[A-Za-z]:" file))
1211 (setq file (cygwin-convert-file-name-from-windows file)))
1212 (setq file (expand-file-name file dir))
1213 (push (cons file filepos) files)
1214 (server-log (format "New file: %s %s"
1215 file (or filepos ""))
1216 proc))
1217 (setq filepos nil))
1219 ;; -eval EXPR: Evaluate a Lisp expression.
1220 (`"-eval"
1221 (if use-current-frame
1222 (setq use-current-frame 'always))
1223 (let ((expr (pop args-left)))
1224 (if coding-system
1225 (setq expr (decode-coding-string expr coding-system)))
1226 (push (lambda () (server-eval-and-print expr proc))
1227 commands)
1228 (setq filepos nil)))
1230 ;; -env NAME=VALUE: An environment variable.
1231 (`"-env"
1232 (let ((var (pop args-left)))
1233 ;; XXX Variables should be encoded as in getenv/setenv.
1234 (process-put proc 'env
1235 (cons var (process-get proc 'env)))))
1237 ;; -dir DIRNAME: The cwd of the emacsclient process.
1238 (`"-dir"
1239 (setq dir (pop args-left))
1240 (if coding-system
1241 (setq dir (decode-coding-string dir coding-system)))
1242 (setq dir (command-line-normalize-file-name dir))
1243 (process-put proc 'server-client-directory dir))
1245 ;; Unknown command.
1246 (arg (error "Unknown command: %s" arg))))
1248 ;; If both -no-wait and -tty are given with file or sexp
1249 ;; arguments, use an existing frame.
1250 (and nowait
1251 (not (eq tty-name 'window-system))
1252 (or files commands)
1253 (setq use-current-frame t))
1255 (setq create-frame-func
1256 (lambda ()
1257 (cond
1258 ((and use-current-frame
1259 (or (eq use-current-frame 'always)
1260 ;; We can't use the Emacs daemon's
1261 ;; terminal frame.
1262 (not (and (daemonp)
1263 (null (cdr (frame-list)))
1264 (eq (selected-frame)
1265 terminal-frame)))))
1266 (setq tty-name nil tty-type nil)
1267 (if display (server-select-display display)))
1268 ((or (and (eq system-type 'windows-nt)
1269 (daemonp)
1270 (setq display "w32"))
1271 (eq tty-name 'window-system))
1272 (server-create-window-system-frame display nowait proc
1273 parent-id
1274 frame-parameters))
1275 ;; When resuming on a tty, tty-name is nil.
1276 (tty-name
1277 (server-create-tty-frame tty-name tty-type proc)))))
1279 (process-put
1280 proc 'continuation
1281 (lambda ()
1282 (with-current-buffer (get-buffer-create server-buffer)
1283 ;; Use the same cwd as the emacsclient, if possible, so
1284 ;; relative file names work correctly, even in `eval'.
1285 (let ((default-directory
1286 (if (and dir (file-directory-p dir))
1287 dir default-directory)))
1288 (server-execute proc files nowait commands
1289 dontkill create-frame-func tty-name)))))
1291 (when (or frame files)
1292 (server-goto-toplevel proc))
1294 (server-execute-continuation proc))))
1295 ;; condition-case
1296 (error (server-return-error proc err))))
1298 (defun server-execute (proc files nowait commands dontkill create-frame-func tty-name)
1299 ;; This is run from timers and process-filters, i.e. "asynchronously".
1300 ;; But w.r.t the user, this is not really asynchronous since the timer
1301 ;; is run after 0s and the process-filter is run in response to the
1302 ;; user running `emacsclient'. So it is OK to override the
1303 ;; inhibit-quit flag, which is good since `commands' (as well as
1304 ;; find-file-noselect via the major-mode) can run arbitrary code,
1305 ;; including code that needs to wait.
1306 (with-local-quit
1307 (condition-case err
1308 (let* ((buffers (server-visit-files files proc nowait))
1309 ;; If we were told only to open a new client, obey
1310 ;; `initial-buffer-choice' if it specifies a file
1311 ;; or a function.
1312 (initial-buffer (unless (or files commands)
1313 (let ((buf
1314 (cond ((stringp initial-buffer-choice)
1315 (find-file-noselect initial-buffer-choice))
1316 ((functionp initial-buffer-choice)
1317 (funcall initial-buffer-choice)))))
1318 (if (buffer-live-p buf) buf (get-buffer-create "*scratch*")))))
1319 ;; Set current buffer so that newly created tty frames
1320 ;; show the correct buffer initially.
1321 (frame (with-current-buffer (or (car buffers)
1322 initial-buffer
1323 (current-buffer))
1324 (prog1
1325 (funcall create-frame-func)
1326 ;; Switch to initial buffer in case the frame was reused.
1327 (when initial-buffer
1328 (switch-to-buffer initial-buffer 'norecord))))))
1330 (mapc 'funcall (nreverse commands))
1332 ;; Delete the client if necessary.
1333 (cond
1334 (nowait
1335 ;; Client requested nowait; return immediately.
1336 (server-log "Close nowait client" proc)
1337 (server-delete-client proc))
1338 ((and (not dontkill) (null buffers))
1339 ;; This client is empty; get rid of it immediately.
1340 (server-log "Close empty client" proc)
1341 (server-delete-client proc)))
1342 (cond
1343 ((or isearch-mode (minibufferp))
1344 nil)
1345 ((and frame (null buffers))
1346 (run-hooks 'server-after-make-frame-hook)
1347 (message "%s" (substitute-command-keys
1348 "When done with this frame, type \\[delete-frame]")))
1349 ((not (null buffers))
1350 (run-hooks 'server-after-make-frame-hook)
1351 (server-switch-buffer (car buffers) nil (cdr (car files)))
1352 (run-hooks 'server-switch-hook)
1353 (unless nowait
1354 (message "%s" (substitute-command-keys
1355 "When done with a buffer, type \\[server-edit]")))))
1356 (when (and frame (null tty-name))
1357 (server-unselect-display frame)))
1358 ((quit error)
1359 (when (eq (car err) 'quit)
1360 (message "Quit emacsclient request"))
1361 (server-return-error proc err)))))
1363 (defun server-return-error (proc err)
1364 (ignore-errors
1365 (server-send-string
1366 proc (concat "-error " (server-quote-arg
1367 (error-message-string err))))
1368 (server-log (error-message-string err) proc)
1369 ;; Before calling `delete-process', give emacsclient time to
1370 ;; receive the error string and shut down on its own.
1371 (sit-for 5)
1372 (delete-process proc)))
1374 (defun server-goto-line-column (line-col)
1375 "Move point to the position indicated in LINE-COL.
1376 LINE-COL should be a pair (LINE . COL)."
1377 (when line-col
1378 (goto-char (point-min))
1379 (forward-line (1- (car line-col)))
1380 (let ((column-number (cdr line-col)))
1381 (when (> column-number 0)
1382 (move-to-column (1- column-number))))))
1384 (defun server-visit-files (files proc &optional nowait)
1385 "Find FILES and return a list of buffers created.
1386 FILES is an alist whose elements are (FILENAME . FILEPOS)
1387 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1388 PROC is the client that requested this operation.
1389 NOWAIT non-nil means this client is not waiting for the results,
1390 so don't mark these buffers specially, just visit them normally."
1391 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1392 (let ((last-nonmenu-event t) client-record)
1393 ;; Restore the current buffer afterward, but not using save-excursion,
1394 ;; because we don't want to save point in this buffer
1395 ;; if it happens to be one of those specified by the server.
1396 (save-current-buffer
1397 (dolist (file files)
1398 ;; If there is an existing buffer modified or the file is
1399 ;; modified, revert it. If there is an existing buffer with
1400 ;; deleted file, offer to write it.
1401 (let* ((minibuffer-auto-raise (or server-raise-frame
1402 minibuffer-auto-raise))
1403 (filen (car file))
1404 (obuf (get-file-buffer filen)))
1405 (add-to-history 'file-name-history filen)
1406 (if (null obuf)
1407 (progn
1408 (run-hooks 'pre-command-hook)
1409 (set-buffer (find-file-noselect filen)))
1410 (set-buffer obuf)
1411 ;; separately for each file, in sync with post-command hooks,
1412 ;; with the new buffer current:
1413 (run-hooks 'pre-command-hook)
1414 (cond ((file-exists-p filen)
1415 (when (not (verify-visited-file-modtime obuf))
1416 (revert-buffer t nil)))
1418 (when (y-or-n-p
1419 (concat "File no longer exists: " filen
1420 ", write buffer to file? "))
1421 (write-file filen))))
1422 (unless server-buffer-clients
1423 (setq server-existing-buffer t)))
1424 (server-goto-line-column (cdr file))
1425 (run-hooks 'server-visit-hook)
1426 ;; hooks may be specific to current buffer:
1427 (run-hooks 'post-command-hook))
1428 (unless nowait
1429 ;; When the buffer is killed, inform the clients.
1430 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1431 (push proc server-buffer-clients))
1432 (push (current-buffer) client-record)))
1433 (unless nowait
1434 (process-put proc 'buffers
1435 (nconc (process-get proc 'buffers) client-record)))
1436 client-record))
1438 (defvar server-kill-buffer-running nil
1439 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1441 (defun server-buffer-done (buffer &optional for-killing)
1442 "Mark BUFFER as \"done\" for its client(s).
1443 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1444 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1445 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1446 a temp file).
1447 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1448 (let ((next-buffer nil)
1449 (killed nil))
1450 (dolist (proc server-clients)
1451 (let ((buffers (process-get proc 'buffers)))
1452 (or next-buffer
1453 (setq next-buffer (nth 1 (memq buffer buffers))))
1454 (when buffers ; Ignore bufferless clients.
1455 (setq buffers (delq buffer buffers))
1456 ;; Delete all dead buffers from PROC.
1457 (dolist (b buffers)
1458 (and (bufferp b)
1459 (not (buffer-live-p b))
1460 (setq buffers (delq b buffers))))
1461 (process-put proc 'buffers buffers)
1462 ;; If client now has no pending buffers,
1463 ;; tell it that it is done, and forget it entirely.
1464 (unless buffers
1465 (server-log "Close" proc)
1466 (if for-killing
1467 ;; `server-delete-client' might delete the client's
1468 ;; frames, which might change the current buffer. We
1469 ;; don't want that (bug#640).
1470 (save-current-buffer
1471 (server-delete-client proc))
1472 (server-delete-client proc))))))
1473 (when (and (bufferp buffer) (buffer-name buffer))
1474 ;; We may or may not kill this buffer;
1475 ;; if we do, do not call server-buffer-done recursively
1476 ;; from kill-buffer-hook.
1477 (let ((server-kill-buffer-running t))
1478 (with-current-buffer buffer
1479 (setq server-buffer-clients nil)
1480 (run-hooks 'server-done-hook))
1481 ;; Notice whether server-done-hook killed the buffer.
1482 (if (null (buffer-name buffer))
1483 (setq killed t)
1484 ;; Don't bother killing or burying the buffer
1485 ;; when we are called from kill-buffer.
1486 (unless for-killing
1487 (when (and (not killed)
1488 server-kill-new-buffers
1489 (with-current-buffer buffer
1490 (not server-existing-buffer)))
1491 (setq killed t)
1492 (bury-buffer buffer)
1493 ;; Prevent kill-buffer from prompting (Bug#3696).
1494 (with-current-buffer buffer
1495 (set-buffer-modified-p nil))
1496 (kill-buffer buffer))
1497 (unless killed
1498 (if (server-temp-file-p buffer)
1499 (progn
1500 (with-current-buffer buffer
1501 (set-buffer-modified-p nil))
1502 (kill-buffer buffer)
1503 (setq killed t))
1504 (bury-buffer buffer)))))))
1505 (list next-buffer killed)))
1507 (defun server-temp-file-p (&optional buffer)
1508 "Return non-nil if BUFFER contains a file considered temporary.
1509 These are files whose names suggest they are repeatedly
1510 reused to pass information to another program.
1512 The variable `server-temp-file-regexp' controls which filenames
1513 are considered temporary."
1514 (and (buffer-file-name buffer)
1515 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1517 (defun server-done ()
1518 "Offer to save current buffer, mark it as \"done\" for clients.
1519 This kills or buries the buffer, then returns a list
1520 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1521 as a suggestion for what to select next, or nil.
1522 KILLED is t if we killed BUFFER, which happens if it was created
1523 specifically for the clients and did not exist before their request for it."
1524 (when server-buffer-clients
1525 (if (server-temp-file-p)
1526 ;; For a temp file, save, and do make a non-numeric backup
1527 ;; (unless make-backup-files is nil).
1528 (let ((version-control nil)
1529 (buffer-backed-up nil))
1530 (save-buffer))
1531 (when (and (buffer-modified-p)
1532 buffer-file-name
1533 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1534 (save-buffer)))
1535 (server-buffer-done (current-buffer))))
1537 (defun server-kill-emacs-query-function ()
1538 "Ask before exiting Emacs if it has live clients."
1539 (or (not (let (live-client)
1540 (dolist (proc server-clients)
1541 (when (memq t (mapcar 'buffer-live-p (process-get
1542 proc 'buffers)))
1543 (setq live-client t)))
1544 live-client))
1545 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1547 (defun server-kill-buffer ()
1548 "Remove the current buffer from its clients' buffer list.
1549 Designed to be added to `kill-buffer-hook'."
1550 ;; Prevent infinite recursion if user has made server-done-hook
1551 ;; call kill-buffer.
1552 (or server-kill-buffer-running
1553 (and server-buffer-clients
1554 (let ((server-kill-buffer-running t))
1555 (when server-process
1556 (server-buffer-done (current-buffer) t))))))
1558 (defun server-edit (&optional arg)
1559 "Switch to next server editing buffer; say \"Done\" for current buffer.
1560 If a server buffer is current, it is marked \"done\" and optionally saved.
1561 The buffer is also killed if it did not exist before the clients asked for it.
1562 When all of a client's buffers are marked as \"done\", the client is notified.
1564 Temporary files such as MH <draft> files are always saved and backed up,
1565 no questions asked. (The variable `make-backup-files', if nil, still
1566 inhibits a backup; you can set it locally in a particular buffer to
1567 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1568 which filenames are considered temporary.
1570 If invoked with a prefix argument, or if there is no server process running,
1571 starts server process and that is all. Invoked by \\[server-edit]."
1572 (interactive "P")
1573 (cond
1574 ((or arg
1575 (not server-process)
1576 (memq (process-status server-process) '(signal exit)))
1577 (server-mode 1))
1578 (server-clients (apply 'server-switch-buffer (server-done)))
1579 (t (message "No server editing buffers exist"))))
1581 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1582 "Switch to another buffer, preferably one that has a client.
1583 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1585 KILLED-ONE is t in a recursive call if we have already killed one
1586 temp-file server buffer. This means we should avoid the final
1587 \"switch to some other buffer\" since we've already effectively
1588 done that.
1590 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1591 visit NEXT-BUFFER in an existing window. If non-nil, it should
1592 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1593 (if (null next-buffer)
1594 (progn
1595 (let ((rest server-clients))
1596 (while (and rest (not next-buffer))
1597 (let ((proc (car rest)))
1598 ;; Only look at frameless clients, or those in the selected
1599 ;; frame.
1600 (when (or (not (process-get proc 'frame))
1601 (eq (process-get proc 'frame) (selected-frame)))
1602 (setq next-buffer (car (process-get proc 'buffers))))
1603 (setq rest (cdr rest)))))
1604 (and next-buffer (server-switch-buffer next-buffer killed-one))
1605 (unless (or next-buffer killed-one (window-dedicated-p))
1606 ;; (switch-to-buffer (other-buffer))
1607 (message "No server buffers remain to edit")))
1608 (if (not (buffer-live-p next-buffer))
1609 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1610 ;; and try the next surviving server buffer.
1611 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1612 ;; OK, we know next-buffer is live, let's display and select it.
1613 (if (functionp server-window)
1614 (funcall server-window next-buffer)
1615 (let ((win (get-buffer-window next-buffer 0)))
1616 (if (and win (not server-window))
1617 ;; The buffer is already displayed: just reuse the
1618 ;; window. If FILEPOS is non-nil, use it to replace the
1619 ;; window's own value of point.
1620 (progn
1621 (select-window win)
1622 (set-buffer next-buffer)
1623 (when filepos
1624 (server-goto-line-column filepos)))
1625 ;; Otherwise, let's find an appropriate window.
1626 (cond ((window-live-p server-window)
1627 (select-window server-window))
1628 ((framep server-window)
1629 (unless (frame-live-p server-window)
1630 (setq server-window (make-frame)))
1631 (select-window (frame-selected-window server-window))))
1632 (when (window-minibuffer-p)
1633 (select-window (next-window nil 'nomini 0)))
1634 ;; Move to a non-dedicated window, if we have one.
1635 (when (window-dedicated-p)
1636 (select-window
1637 (get-window-with-predicate
1638 (lambda (w)
1639 (and (not (window-dedicated-p w))
1640 (equal (frame-terminal (window-frame w))
1641 (frame-terminal))))
1642 'nomini 'visible (selected-window))))
1643 (condition-case nil
1644 (switch-to-buffer next-buffer)
1645 ;; After all the above, we might still have ended up with
1646 ;; a minibuffer/dedicated-window (if there's no other).
1647 (error (pop-to-buffer next-buffer)))))))
1648 (when server-raise-frame
1649 (select-frame-set-input-focus (window-frame)))))
1651 ;;;###autoload
1652 (defun server-save-buffers-kill-terminal (arg)
1653 ;; Called from save-buffers-kill-terminal in files.el.
1654 "Offer to save each buffer, then kill the current client.
1655 With ARG non-nil, silently save all file-visiting buffers, then kill.
1657 If emacsclient was started with a list of filenames to edit, then
1658 only these files will be asked to be saved."
1659 (let ((proc (frame-parameter nil 'client)))
1660 (cond ((eq proc 'nowait)
1661 ;; Nowait frames have no client buffer list.
1662 (if (cdr (frame-list))
1663 (progn (save-some-buffers arg)
1664 (delete-frame))
1665 ;; If we're the last frame standing, kill Emacs.
1666 (save-buffers-kill-emacs arg)))
1667 ((processp proc)
1668 (let ((buffers (process-get proc 'buffers)))
1669 ;; If client is bufferless, emulate a normal Emacs exit
1670 ;; and offer to save all buffers. Otherwise, offer to
1671 ;; save only the buffers belonging to the client.
1672 (save-some-buffers
1673 arg (if buffers
1674 (lambda () (memq (current-buffer) buffers))
1676 (server-delete-client proc)))
1677 (t (error "Invalid client frame")))))
1679 (define-key ctl-x-map "#" 'server-edit)
1681 (defun server-unload-function ()
1682 "Unload the Server library."
1683 (server-mode -1)
1684 (substitute-key-definition 'server-edit nil ctl-x-map)
1685 (save-current-buffer
1686 (dolist (buffer (buffer-list))
1687 (set-buffer buffer)
1688 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1689 ;; continue standard unloading
1690 nil)
1692 (defun server-eval-at (server form)
1693 "Contact the Emacs server named SERVER and evaluate FORM there.
1694 Returns the result of the evaluation, or signals an error if it
1695 cannot contact the specified server. For example:
1696 (server-eval-at \"server\" \\='(emacs-pid))
1697 returns the process ID of the Emacs instance running \"server\"."
1698 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
1699 (server-file (expand-file-name server server-dir))
1700 (coding-system-for-read 'binary)
1701 (coding-system-for-write 'binary)
1702 address port secret process)
1703 (unless (file-exists-p server-file)
1704 (error "No such server: %s" server))
1705 (with-temp-buffer
1706 (when server-use-tcp
1707 (let ((coding-system-for-read 'no-conversion))
1708 (insert-file-contents server-file)
1709 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1710 (error "Invalid auth file"))
1711 (setq address (match-string 1)
1712 port (string-to-number (match-string 2)))
1713 (forward-line 1)
1714 (setq secret (buffer-substring (point) (line-end-position)))
1715 (erase-buffer)))
1716 (unless (setq process (make-network-process
1717 :name "eval-at"
1718 :buffer (current-buffer)
1719 :host address
1720 :service (if server-use-tcp port server-file)
1721 :family (if server-use-tcp 'ipv4 'local)
1722 :noquery t))
1723 (error "Unable to contact the server"))
1724 (if server-use-tcp
1725 (process-send-string process (concat "-auth " secret "\n")))
1726 (process-send-string process
1727 (concat "-eval "
1728 (server-quote-arg (format "%S" form))
1729 "\n"))
1730 (while (memq (process-status process) '(open run))
1731 (accept-process-output process 0 10))
1732 (goto-char (point-min))
1733 ;; If the result is nil, there's nothing in the buffer. If the
1734 ;; result is non-nil, it's after "-print ".
1735 (let ((answer ""))
1736 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t)
1737 (setq answer
1738 (concat answer
1739 (buffer-substring (point)
1740 (progn (skip-chars-forward "^\n")
1741 (point))))))
1742 (if (not (equal answer ""))
1743 (read (decode-coding-string (server-unquote-arg answer)
1744 'emacs-internal)))))))
1747 (provide 'server)
1749 ;;; server.el ends here