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