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