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