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