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