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