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