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