Better seed support for (random).
[bpt/emacs.git] / lisp / server.el
CommitLineData
c530e1c2 1;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
c88ab9ce 2
acaf905b 3;; Copyright (C) 1986-1987, 1992, 1994-2012 Free Software Foundation, Inc.
6d74b528 4
630cc463 5;; Author: William Sommerfeld <wesommer@athena.mit.edu>
e4874521 6;; Maintainer: FSF
d7b4d18f 7;; Keywords: processes
630cc463 8
9ae0f972 9;; Changes by peck@sun.com and by rms.
35dfa9b6 10;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
9ae0f972 11
12;; This file is part of GNU Emacs.
13
eb3fa2cf 14;; GNU Emacs is free software: you can redistribute it and/or modify
9ae0f972 15;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
16;; the Free Software Foundation, either version 3 of the License, or
17;; (at your option) any later version.
9ae0f972 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
eb3fa2cf 25;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
9ae0f972 26
630cc463 27;;; Commentary:
9ae0f972 28
b578f267
EN
29;; This Lisp code is run in Emacs when it is to operate as
30;; a server for other processes.
9ae0f972 31
b578f267 32;; Load this library and do M-x server-edit to enable Emacs as a server.
44a56b29
SM
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))
9ae0f972 36
b578f267
EN
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.
9ae0f972 41
6d3a46f7 42;; Note that any number of clients may dispatch files to Emacs to be edited.
9ae0f972 43
b578f267 44;; When you finish editing a Server buffer, again call server-edit
64f51134
JPW
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
b578f267 47;; and exited with server-edit, the client "editor" will return
64f51134 48;; to the program that invoked it.
9ae0f972 49
b578f267
EN
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:
9ae0f972 54
b578f267
EN
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.
9ae0f972 57
b578f267
EN
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.
9ae0f972 60
b578f267
EN
61;; 3. When the program that wants to use "the editor" is running
62;; as a subprocess of Emacs.
9ae0f972 63
b578f267
EN
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.
9ae0f972 69
64f51134
JPW
70;; The buffer local variable "server-buffer-clients" lists
71;; the clients who are waiting for this buffer to be edited.
b578f267
EN
72;; The global variable "server-clients" lists all the waiting clients,
73;; and which files are yet to be edited for each.
630cc463 74
0acb1916
SM
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
630cc463 82;;; Code:
8b3e840e 83
a464a6c7 84(eval-when-compile (require 'cl-lib))
8b3e840e 85
ab1c7f35
RS
86(defgroup server nil
87 "Emacs running as a server process."
88 :group 'external)
89
337e3c70
JB
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")))
337e3c70
JB
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.
104If 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")
7d3e3843 110;;;###autoload
337e3c70
JB
111(put 'server-host 'risky-local-variable t)
112
c79b0b1c 113(defcustom server-port nil
7a1ff57f
CY
114 "The port number that the server process should listen on.
115This variable only takes effect when the Emacs server is using
116TCP instead of local sockets. A nil value means to use a random
117port number."
c79b0b1c 118 :group 'server
c79b0b1c
PO
119 :type '(choice
120 (string :tag "Port number")
121 (const :tag "Random" nil))
122 :version "24.1")
7d3e3843
GM
123;;;###autoload
124(put 'server-port 'risky-local-variable t)
c79b0b1c 125
d6c180c4 126(defcustom server-auth-dir (locate-user-emacs-file "server/")
3e70541a 127 "Directory for server authentication files.
953cebf5
GM
128We only use this if `server-use-tcp' is non-nil.
129Otherwise we use `server-socket-dir'.
3e70541a
JB
130
131NOTE: On FAT32 filesystems, directories are not secure;
132files can be read and modified by any user or process.
133It is strongly suggested to set `server-auth-dir' to a
134directory residing in a NTFS partition instead."
337e3c70
JB
135 :group 'server
136 :type 'directory
137 :version "22.1")
7d3e3843 138;;;###autoload
337e3c70
JB
139(put 'server-auth-dir 'risky-local-variable t)
140
29734c21
MN
141(defcustom server-auth-key nil
142 "Server authentication key.
143
3603c3b1
JB
144Normally, the authentication key is randomly generated when the
145server starts, which guarantees some level of security. It is
29734c21 146recommended to leave it that way. Using a long-lived shared key
3603c3b1 147will decrease security (especially since the key is transmitted as
29734c21
MN
148plain text).
149
150In some situations however, it can be difficult to share randomly
3603c3b1
JB
151generated passwords with remote hosts (eg. no shared directory),
152so you can set the key with this variable and then copy the
153server file to the remote host (with possible changes to IP
154address and/or port if that applies).
29734c21 155
3603c3b1
JB
156The key must consist of 64 ASCII printable characters except for
157space (this means characters from ! to ~; or from code 33 to 126).
29734c21
MN
158
159You can use \\[server-generate-key] to get a random authentication
160key."
161 :group 'server
162 :type '(choice
163 (const :tag "Random" nil)
164 (string :tag "Password"))
2a1e2476 165 :version "24.3")
29734c21 166
90caccca 167(defcustom server-raise-frame t
ff348fba 168 "If non-nil, raise frame when switching to a buffer."
90caccca
JB
169 :group 'server
170 :type 'boolean
171 :version "22.1")
172
ab1c7f35 173(defcustom server-visit-hook nil
ff348fba 174 "Hook run when visiting a file for the Emacs server."
ab1c7f35 175 :group 'server
0c851d78 176 :type 'hook)
ab1c7f35
RS
177
178(defcustom server-switch-hook nil
ff348fba 179 "Hook run when switching to a buffer for the Emacs server."
ab1c7f35 180 :group 'server
0c851d78 181 :type 'hook)
ab1c7f35
RS
182
183(defcustom server-done-hook nil
ff348fba 184 "Hook run when done editing a buffer for the Emacs server."
ab1c7f35 185 :group 'server
0c851d78 186 :type 'hook)
f9b3ef88 187
64f51134
JPW
188(defvar server-process nil
189 "The current server process.")
9ae0f972 190
191(defvar server-clients nil
192 "List of current server clients.
448f754f 193Each element is a process.")
0a125897 194
9ae0f972 195(defvar server-buffer-clients nil
5f3c1a63 196 "List of client processes requesting editing of current buffer.")
faf931a8 197(make-variable-buffer-local 'server-buffer-clients)
9ae0f972 198;; Changing major modes should not erase this local.
199(put 'server-buffer-clients 'permanent-local t)
200
33186f32 201(defcustom server-window nil
ff348fba 202 "Specification of the window to use for selecting Emacs server buffers.
ec40ed9f 203If nil, use the selected window.
408784a7 204If it is a function, it should take one argument (a buffer) and
33186f32
DL
205display and select it. A common value is `pop-to-buffer'.
206If it is a window, use that.
207If it is a frame, use the frame's selected window.
208
209It is not meaningful to set this to a specific frame or window with Custom.
210Only programs can do so."
211 :group 'server
bf247b6e 212 :version "22.1"
33186f32
DL
213 :type '(choice (const :tag "Use selected window"
214 :match (lambda (widget value)
215 (not (functionp value)))
216 nil)
ee9272ff 217 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
33186f32
DL
218 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
219 (function :tag "Other function")))
ec40ed9f 220
ab1c7f35 221(defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
ff348fba 222 "Regexp matching names of temporary files.
33186f32
DL
223These are deleted and reused after each edit by the programs that
224invoke the Emacs server."
ab1c7f35
RS
225 :group 'server
226 :type 'regexp)
9ae0f972 227
c6a117f0 228(defcustom server-kill-new-buffers t
ff348fba 229 "Whether to kill buffers when done with them.
c6a117f0 230If non-nil, kill a buffer unless it already existed before editing
f258b525 231it with the Emacs server. If nil, kill only buffers as specified by
c6a117f0 232`server-temp-file-regexp'.
f258b525 233Please note that only buffers that still have a client are killed,
a77ad240
JB
234i.e. buffers visited with \"emacsclient --no-wait\" are never killed
235in this way."
c6a117f0
GM
236 :group 'server
237 :type 'boolean
238 :version "21.1")
239
9ae0f972 240(or (assq 'server-buffer-clients minor-mode-alist)
b7621225 241 (push '(server-buffer-clients " Server") minor-mode-alist))
9ae0f972 242
c6a117f0 243(defvar server-existing-buffer nil
ca0c7250 244 "Non-nil means the buffer existed before the server was asked to visit it.
4dd04714 245This means that the server should not kill the buffer when you say you
ca0c7250 246are done with it in the server.")
c6a117f0
GM
247(make-variable-buffer-local 'server-existing-buffer)
248
77c4d024
CY
249(defcustom server-name "server"
250 "The name of the Emacs server, if this Emacs process creates one.
251The command `server-start' makes use of this. It should not be
252changed while a server is running."
253 :group 'server
254 :type 'string
255 :version "23.1")
03ae35cf 256
03542605
CY
257;; We do not use `temporary-file-directory' here, because emacsclient
258;; does not read the init file.
f77b11a0 259(defvar server-socket-dir
a77ad240
JB
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.
263If local sockets are not supported, this is nil.")
0c851d78 264
9002956f
KL
265(defun server-clients-with (property value)
266 "Return a list of clients with PROPERTY set to VALUE."
267 (let (result)
2403c841 268 (dolist (proc server-clients)
448f754f 269 (when (equal value (process-get proc property))
2403c841
SM
270 (push proc result)))
271 result))
9002956f
KL
272
273(defun server-add-client (proc)
274 "Create a client for process PROC, if it doesn't already have one.
275New clients have no properties."
448f754f 276 (add-to-list 'server-clients proc))
9002956f 277
59e085e0
KL
278(defmacro server-with-environment (env vars &rest body)
279 "Evaluate BODY with environment variables VARS set to those in ENV.
65f64034
KL
280The environment variables are then restored to their previous values.
281
59e085e0
KL
282VARS should be a list of strings.
283ENV should be in the same format as `process-environment'."
65f64034 284 (declare (indent 2))
13ba3740
SM
285 (let ((var (make-symbol "var"))
286 (value (make-symbol "value")))
287 `(let ((process-environment process-environment))
59e085e0 288 (dolist (,var ,vars)
e159b869 289 (let ((,value (getenv-internal ,var ,env)))
abab01f2
JB
290 (push (if (stringp ,value)
291 (concat ,var "=" ,value)
292 ,var)
13ba3740
SM
293 process-environment)))
294 (progn ,@body))))
65f64034 295
448f754f 296(defun server-delete-client (proc &optional noframe)
c48254fb 297 "Delete PROC, including its buffers, terminals and frames.
a77ad240
JB
298If NOFRAME is non-nil, let the frames live.
299Updates `server-clients'."
ff91dc79 300 (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
9002956f 301 ;; Force a new lookup of client (prevents infinite recursion).
448f754f
SM
302 (when (memq proc server-clients)
303 (let ((buffers (process-get proc 'buffers)))
9002956f 304
5f3c1a63 305 ;; Kill the client's buffers.
9002956f 306 (dolist (buf buffers)
6ed9e43a
KL
307 (when (buffer-live-p buf)
308 (with-current-buffer buf
6ed9e43a 309 ;; Kill the buffer if necessary.
5f3c1a63
KL
310 (when (and (equal server-buffer-clients
311 (list proc))
6ed9e43a
KL
312 (or (and server-kill-new-buffers
313 (not server-existing-buffer))
5f3c1a63
KL
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)))))))))
9002956f 324
160f0817
KL
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
448f754f 335 (setq server-clients (delq proc server-clients))
5f3c1a63 336
520fca41
JB
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))))
9002956f 344
9002956f 345 ;; Delete the client's process.
448f754f
SM
346 (if (eq (process-status proc) 'open)
347 (delete-process proc))
9002956f
KL
348
349 (server-log "Deleted" proc))))
350
88fd26a1 351(defvar server-log-time-function 'current-time-string
f03ea9d9 352 "Function to generate timestamps for `server-buffer'.")
88fd26a1 353
28cbade4
SM
354(defconst server-buffer " *server*"
355 "Buffer used internally by Emacs's server.
356One use is to log the I/O for debugging purposes (see `server-log'),
357the other is to provide a current buffer in which the process filter can
f03ea9d9 358safely let-bind buffer-local variables like `default-directory'.")
28cbade4
SM
359
360(defvar server-log nil
361 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
362
8b3e840e 363(defun server-log (string &optional client)
28cbade4 364 "If `server-log' is non-nil, log STRING to `server-buffer'.
c48254fb 365If CLIENT is non-nil, add a description of it to the logged message."
28cbade4
SM
366 (when server-log
367 (with-current-buffer (get-buffer-create server-buffer)
337e3c70 368 (goto-char (point-max))
88fd26a1 369 (insert (funcall server-log-time-function)
974b73e8 370 (cond
94d11cb5
IK
371 ((null client) " ")
372 ((listp client) (format " %s: " (car client)))
373 (t (format " %s: " client)))
337e3c70
JB
374 string)
375 (or (bolp) (newline)))))
9ae0f972 376
377(defun server-sentinel (proc msg)
9002956f 378 "The process sentinel for Emacs server connections."
cbfc02e4
RF
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))
757e1681 384 ;; Delete the associated connection file, if applicable.
c63a334e
JB
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)
84716442 390 (ignore-errors
94d11cb5 391 (delete-file (process-get proc :server-file))))
9002956f
KL
392 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
393 (server-delete-client proc))
0c851d78 394
e5248ac9
SM
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
13ba3740
SM
404(defun server-select-display (display)
405 ;; If the current frame is on `display' we're all set.
a77ad240 406 ;; Similarly if we are unable to open frames on other displays, there's
1a4a884c
SM
407 ;; nothing more we can do.
408 (unless (or (not (fboundp 'make-frame-on-display))
e5248ac9 409 (server--on-display-p (selected-frame) display))
13ba3740
SM
410 ;; Otherwise, look for an existing frame there and select it.
411 (dolist (frame (frame-list))
e5248ac9 412 (when (server--on-display-p frame display)
13ba3740
SM
413 (select-frame frame)))
414 ;; If there's no frame on that display yet, create and select one.
e5248ac9 415 (unless (server--on-display-p (selected-frame) display)
13ba3740
SM
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.
ff91dc79 421 `((server-dummy-buffer . ,buffer)
13ba3740
SM
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.
ffb6157e
MR
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)))
1dba6978
MR
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))
451077ad 447 (when (buffer-live-p buffer)
451077ad 448 (kill-buffer buffer)))))
13ba3740 449
77134727 450(defun server-handle-delete-frame (frame)
a77ad240
JB
451 "Delete the client connection when the emacsclient frame is deleted.
452\(To be used from `delete-frame-functions'.)"
9002956f 453 (let ((proc (frame-parameter frame 'client)))
e519a50b
KL
454 (when (and (frame-live-p frame)
455 proc
160f0817 456 ;; See if this is the last frame for this client.
d5381da2 457 (>= 1 (let ((frame-num 0))
94d11cb5
IK
458 (dolist (f (frame-list))
459 (when (eq proc (frame-parameter f 'client))
460 (setq frame-num (1+ frame-num))))
461 frame-num)))
9002956f 462 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
de93c791 463 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
9002956f 464
6ed8eeff 465(defun server-handle-suspend-tty (terminal)
d032d5e7 466 "Notify the client process that its tty device is suspended."
6ed8eeff 467 (dolist (proc (server-clients-with 'terminal terminal))
d032d5e7
SM
468 (server-log (format "server-handle-suspend-tty, terminal %s" terminal)
469 proc)
470 (condition-case nil
6afdd335 471 (server-send-string proc "-suspend \n")
44954c2f
SM
472 (file-error ;The pipe/socket was closed.
473 (ignore-errors (server-delete-client proc))))))
44a56b29 474
0c851d78 475(defun server-unquote-arg (arg)
6afdd335
KL
476 "Remove &-quotation from ARG.
477See `server-quote-arg' and `server-process-filter'."
0c851d78
SM
478 (replace-regexp-in-string
479 "&." (lambda (s)
a464a6c7 480 (pcase (aref s 1)
0c851d78
SM
481 (?& "&")
482 (?- "-")
483 (?n "\n")
a464a6c7 484 (_ " ")))
0c851d78 485 arg t t))
9ae0f972 486
0b0d3e0b 487(defun server-quote-arg (arg)
9002956f 488 "In ARG, insert a & before each &, each space, each newline, and -.
0b0d3e0b 489Change spaces to underscores, too, so that the return value never
6afdd335
KL
490contains a space.
491
492See `server-unquote-arg' and `server-process-filter'."
0b0d3e0b
KL
493 (replace-regexp-in-string
494 "[-&\n ]" (lambda (s)
a464a6c7 495 (pcase (aref s 0)
0b0d3e0b
KL
496 (?& "&&")
497 (?- "&-")
498 (?\n "&n")
499 (?\s "&_")))
500 arg t t))
501
6afdd335 502(defun server-send-string (proc string)
a77ad240 503 "A wrapper around `process-send-string' for logging."
6afdd335
KL
504 (server-log (concat "Sent " string) proc)
505 (process-send-string proc string))
506
724629d2
SM
507(defun server-ensure-safe-dir (dir)
508 "Make sure DIR is a directory with no race-condition issues.
509Creates 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))
d7554167 514 (let ((attrs (file-attributes dir 'integer)))
724629d2 515 (unless attrs
a464a6c7 516 (cl-letf (((default-file-modes) ?\700)) (make-directory dir t))
d7554167 517 (setq attrs (file-attributes dir 'integer)))
3e70541a 518
724629d2 519 ;; Check that it's safe for use.
3e70541a
JB
520 (let* ((uid (nth 2 attrs))
521 (w32 (eq system-type 'windows-nt))
197b6f3c
JB
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.
3e70541a
JB
528Directories on FAT32 filesystems are NOT secure against tampering.
529See variable `server-auth-dir' for details."
197b6f3c
JB
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)))))))
3e70541a
JB
543 (unless safe
544 (error "The directory `%s' is unsafe" dir)))))
724629d2 545
29734c21 546(defun server-generate-key ()
3603c3b1
JB
547 "Generate and return a random authentication key.
548The key is a 64-byte string of random chars in the range `!'..`~'.
549If called interactively, also inserts it into current buffer."
29734c21
MN
550 (interactive)
551 (let ((auth-key
a464a6c7
SM
552 (cl-loop repeat 64
553 collect (+ 33 (random 94)) into auth
554 finally return (concat auth))))
e6de100c 555 (if (called-interactively-p 'interactive)
29734c21
MN
556 (insert auth-key))
557 auth-key))
558
559(defun server-get-auth-key ()
3603c3b1 560 "Return server's authentication key.
29734c21 561
3603c3b1
JB
562If `server-auth-key' is nil, just call `server-generate-key'.
563Otherwise, if `server-auth-key' is a valid key, return it.
564If the key is not valid, signal an error."
29734c21 565 (if server-auth-key
3603c3b1 566 (if (string-match-p "^[!-~]\\{64\\}$" server-auth-key)
29734c21
MN
567 server-auth-key
568 (error "The key '%s' is invalid" server-auth-key))
569 (server-generate-key)))
570
7229064d 571;;;###autoload
381d186f 572(defun server-start (&optional leave-dead inhibit-prompt)
9ae0f972 573 "Allow this Emacs process to be a server for client processes.
3603c3b1
JB
574This starts a server communications subprocess through which client
575\"editors\" can send your editing commands to this Emacs job.
576To use the server, set up the program `emacsclient' in the Emacs
577distribution as your standard \"editor\".
9ae0f972 578
bd410bb0 579Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
c63a334e
JB
580kill any existing server communications subprocess.
581
381d186f
CY
582If a server is already running, restart it. If clients are
583running, ask the user for confirmation first, unless optional
584argument INHIBIT-PROMPT is non-nil.
585
c63a334e
JB
586To force-start a server, do \\[server-force-delete] and then
587\\[server-start]."
9ae0f972 588 (interactive "P")
97e121cc
CY
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.
381d186f
CY
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? "))))
c63a334e
JB
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
84716442 609 (ignore-errors
94d11cb5
IK
610 (let (delete-by-moving-to-trash)
611 (delete-file server-file)))
c63a334e 612 (setq server-mode nil) ;; already set by the minor mode code
c31ee003
CY
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
619server or call `M-x server-force-delete' to forcibly disconnect it.")
620 :warning)
35f372ca 621 (setq leave-dead t))
c63a334e
JB
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
35f372ca 628 (unless (eq t leave-dead) (server-log (message "Server stopped")))
c63a334e 629 (setq server-process nil))
974b73e8
KL
630 ;; Make sure there is a safe directory in which to place the socket.
631 (server-ensure-safe-dir server-dir)
974b73e8
KL
632 (when server-process
633 (server-log (message "Restarting server")))
a464a6c7 634 (cl-letf (((default-file-modes) ?\700))
e4019195 635 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
974b73e8 636 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
a464a6c7
SM
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)
381d186f 641 (add-hook 'kill-emacs-hook 'server-force-stop) ;Cleanup upon exit.
974b73e8
KL
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
1b0a6c68
SM
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
28cbade4 654 ;; The other args depend on the kind of socket used.
974b73e8 655 (if server-use-tcp
d5b8058f 656 (list :family 'ipv4 ;; We're not ready for IPv6 yet
c79b0b1c 657 :service (or server-port t)
ba3033ee 658 :host (or server-host 'local)
974b73e8
KL
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"))
c63a334e 664 (process-put server-process :server-file server-file)
974b73e8 665 (when server-use-tcp
29734c21 666 (let ((auth-key (server-get-auth-key)))
974b73e8
KL
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))
a16f5f64 673 " " (number-to-string (emacs-pid)) ; Kept for compatibility
974b73e8 674 "\n" auth-key)))))))))
33186f32 675
381d186f
CY
676(defun server-force-stop ()
677 "Kill all connections to the current server.
678This function is meant to be called from `kill-emacs-hook'."
bf6442c3 679 (server-start t t))
381d186f 680
c63a334e
JB
681;;;###autoload
682(defun server-force-delete (&optional name)
683 "Unconditionally delete connection file for server NAME.
684If server is running, it is first stopped.
685NAME 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
84716442 695 (let (delete-by-moving-to-trash)
c63a334e
JB
696 (delete-file file)
697 (message "Connection file %S deleted" file))
698 (file-error
699 (message "No connection file %S" file)))))
700
44954c2f 701(defun server-running-p (&optional name)
c63a334e
JB
702 "Test whether server NAME is running.
703
704Return 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."
44954c2f
SM
709 (unless name (setq name server-name))
710 (condition-case nil
c63a334e
JB
711 (if server-use-tcp
712 (with-temp-buffer
713 (insert-file-contents-literally (expand-file-name name server-auth-dir))
d9569a55 714 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
c63a334e 715 (assq 'comm
a20878b6 716 (process-attributes
c63a334e
JB
717 (string-to-number (match-string 1))))
718 t)
719 :other))
44954c2f
SM
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
33186f32
DL
727;;;###autoload
728(define-minor-mode server-mode
729 "Toggle Server mode.
06e21633
CY
730With a prefix argument ARG, enable Server mode if ARG is
731positive, and disable it otherwise. If called from Lisp, enable
732Server mode if ARG is omitted or nil.
733
33186f32 734Server mode runs a process that accepts commands from the
06e21633
CY
735`emacsclient' program. See Info node `Emacs server' and
736`server-start' for details."
33186f32
DL
737 :global t
738 :group 'server
bf247b6e 739 :version "22.1"
33186f32
DL
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)))
9ae0f972 743\f
13ba3740
SM
744(defun server-eval-and-print (expr proc)
745 "Eval EXPR and send the result back to client PROC."
28109f49
SM
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))))))
56e6cc31 754 (when proc
13ba3740
SM
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))))
e29ab36b
AS
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.
767QTEXT must be already quoted.
768This 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"))))
13ba3740
SM
783
784(defun server-create-tty-frame (tty type proc)
f79b43b2
DN
785 (unless tty
786 (error "Invalid terminal device"))
787 (unless type
788 (error "Invalid terminal type"))
4419b755 789 (add-to-list 'frame-inherited-parameters 'client)
13ba3740
SM
790 (let ((frame
791 (server-with-environment (process-get proc 'env)
94d11cb5
IK
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)))))))
052056a9 817
e159b869
SM
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)))
13ba3740 822 (select-frame frame)
448f754f 823 (process-put proc 'frame frame)
448f754f 824 (process-put proc 'terminal (frame-terminal frame))
13ba3740
SM
825 frame))
826
18a4ce5e
AR
827(defun server-create-window-system-frame (display nowait proc parent-id
828 &optional parameters)
4419b755 829 (add-to-list 'frame-inherited-parameters 'client)
e159b869 830 (if (not (fboundp 'make-frame-on-display))
13ba3740
SM
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))
4419b755 842 ;; This is a leftover, see above.
18a4ce5e
AR
843 (environment . ,(process-get proc 'env))
844 ,@parameters))
0191e222
CY
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))
13ba3740 853 (server-log (format "%s created" frame) proc)
13ba3740 854 (select-frame frame)
448f754f
SM
855 (process-put proc 'frame frame)
856 (process-put proc 'terminal (frame-terminal frame))
13ba3740
SM
857 frame)))
858
13ba3740
SM
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.
94d11cb5 875 (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
13ba3740
SM
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
a464a6c7 890(cl-defun server-process-filter (proc string)
33186f32 891 "Process a request from the server to edit some files.
6afdd335 892PROC is the server process. STRING consists of a sequence of
909049cb
JB
893commands prefixed by a dash. Some commands have arguments;
894these are &-quoted and need to be decoded by `server-unquote-arg'.
895The filter parses and executes these commands.
6afdd335
KL
896
897To illustrate the protocol, here is an example command that
898emacsclient sends to create a new X frame (note that the whole
899sequence is sent on a single line):
900
909049cb
JB
901 -env HOME=/home/lorentey
902 -env DISPLAY=:0.0
6afdd335
KL
903 ... lots of other -env commands
904 -display :0.0
905 -window-system
906
6afdd335
KL
907The following commands are accepted by the server:
908
974b73e8
KL
909`-auth AUTH-STRING'
910 Authenticate the client using the secret authentication string
a38daa0a 911 AUTH-STRING.
974b73e8 912
59e085e0 913`-env NAME=VALUE'
6afdd335
KL
914 An environment variable on the client side.
915
2828d5f9
KL
916`-dir DIRNAME'
917 The current working directory of the client process.
918
92071250
KL
919`-current-frame'
920 Forbid the creation of new frames.
921
18a4ce5e
AR
922`-frame-parameters ALIST'
923 Set the parameters of the created frame.
924
6afdd335
KL
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
6afdd335
KL
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
2828d5f9 954`-resume'
c48254fb 955 Resume this tty frame. The client sends this string when it
2828d5f9
KL
956 gets the SIGCONT signal and it is the foreground process on its
957 controlling tty.
958
6afdd335 959`-ignore COMMENT'
909049cb
JB
960 Do nothing, but put the comment in the server log.
961 Useful for debugging.
6afdd335
KL
962
963
964The following commands are accepted by the client:
965
6afdd335
KL
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'
c48254fb
JB
971 Signals that the server does not support creating X frames;
972 the client must try again with a tty frame.
6afdd335
KL
973
974`-print STRING'
975 Print STRING on stdout. Used to send values
976 returned by -eval.
977
e29ab36b
AS
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
6afdd335 983`-error DESCRIPTION'
2b7ba565 984 Signal an error and delete process PROC.
6afdd335
KL
985
986`-suspend'
c48254fb
JB
987 Suspend this terminal, i.e., stop the client process.
988 Sent when the user presses C-z."
6afdd335 989 (server-log (concat "Received " string) proc)
337e3c70
JB
990 ;; First things first: let's check the authentication
991 (unless (process-get proc :authenticated)
38b9f0f3 992 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
974b73e8
KL
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))
337e3c70 998 (server-log "Authentication failed" proc)
974b73e8
KL
999 (server-send-string
1000 proc (concat "-error " (server-quote-arg "Authentication failed")))
2a847524
CY
1001 ;; Before calling `delete-process', give emacsclient time to
1002 ;; receive the error string and shut down on its own.
1003 (sit-for 1)
337e3c70 1004 (delete-process proc)
a464a6c7
SM
1005 ;; We return immediately.
1006 (cl-return-from server-process-filter)))
3f7ef08e
SM
1007 (let ((prev (process-get proc 'previous-string)))
1008 (when prev
1009 (setq string (concat prev string))
1010 (process-put proc 'previous-string nil)))
a9298135 1011 (condition-case err
0b0d3e0b 1012 (progn
9002956f 1013 (server-add-client proc)
968ef9b4
JB
1014 ;; Send our pid
1015 (server-send-string proc (concat "-emacs-pid "
1016 (number-to-string (emacs-pid)) "\n"))
13ba3740
SM
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))
c48254fb 1021
13ba3740
SM
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.
a464a6c7 1025 (cl-assert (eq (match-end 0) (length string)))
0b0d3e0b 1026 (let ((request (substring string 0 (match-beginning 0)))
597e2240 1027 (coding-system (and (default-value 'enable-multibyte-characters)
0b0d3e0b
KL
1028 (or file-name-coding-system
1029 default-file-name-coding-system)))
0191e222
CY
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.
650d0dbc 1035 commands
2828d5f9 1036 dir
cd9c54eb 1037 use-current-frame
18a4ce5e 1038 frame-parameters ;parameters for newly created frame
0191e222
CY
1039 tty-name ; nil, `window-system', or the tty name.
1040 tty-type ; string.
650d0dbc
CY
1041 files
1042 filepos
59003be9 1043 args-left)
0b0d3e0b
KL
1044 ;; Remove this line from STRING.
1045 (setq string (substring string (match-end 0)))
59003be9 1046 (setq args-left
bfb74e75 1047 (mapcar 'server-unquote-arg (split-string request " " t)))
59003be9
SM
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
18a4ce5e
AR
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
59003be9
SM
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"
2d0e8e61
CY
1080 (if (fboundp 'x-create-frame)
1081 (setq dontkill t
1082 tty-name 'window-system)))
59003be9
SM
1083
1084 ;; -resume: Resume a suspended tty frame.
1085 (`"-resume"
c530e1c2 1086 (let ((terminal (process-get proc 'terminal)))
59003be9
SM
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"
c530e1c2 1097 (let ((terminal (process-get proc 'terminal)))
59003be9
SM
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
2d0e8e61
CY
1110 ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
1111 ;; (But if we see -window-system later, use that.)
59003be9
SM
1112 (`"-tty"
1113 (setq tty-name (pop args-left)
1114 tty-type (pop args-left)
1115 dontkill (or dontkill
520fca41
JB
1116 (not use-current-frame)))
1117 ;; On Windows, emacsclient always asks for a tty frame.
1118 ;; If running a GUI server, force the frame type to GUI.
1119 (when (eq window-system 'w32)
1120 (push "-window-system" args-left)))
59003be9
SM
1121
1122 ;; -position LINE[:COLUMN]: Set point to the given
1123 ;; position in the next file.
1124 (`"-position"
1125 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1126 (car args-left)))
1127 (error "Invalid -position command in client args"))
1128 (let ((arg (pop args-left)))
1129 (setq filepos
1130 (cons (string-to-number (match-string 1 arg))
1131 (string-to-number (or (match-string 2 arg)
1132 ""))))))
1133
1134 ;; -file FILENAME: Load the given file.
1135 (`"-file"
1136 (let ((file (pop args-left)))
1137 (if coding-system
1138 (setq file (decode-coding-string file coding-system)))
1139 (setq file (expand-file-name file dir))
1140 (push (cons file filepos) files)
1141 (server-log (format "New file: %s %s"
1142 file (or filepos "")) proc))
1143 (setq filepos nil))
1144
1145 ;; -eval EXPR: Evaluate a Lisp expression.
1146 (`"-eval"
1147 (if use-current-frame
1148 (setq use-current-frame 'always))
c530e1c2 1149 (let ((expr (pop args-left)))
59003be9
SM
1150 (if coding-system
1151 (setq expr (decode-coding-string expr coding-system)))
1152 (push (lambda () (server-eval-and-print expr proc))
1153 commands)
1154 (setq filepos nil)))
1155
1156 ;; -env NAME=VALUE: An environment variable.
1157 (`"-env"
1158 (let ((var (pop args-left)))
1159 ;; XXX Variables should be encoded as in getenv/setenv.
1160 (process-put proc 'env
1161 (cons var (process-get proc 'env)))))
1162
1163 ;; -dir DIRNAME: The cwd of the emacsclient process.
1164 (`"-dir"
1165 (setq dir (pop args-left))
1166 (if coding-system
1167 (setq dir (decode-coding-string dir coding-system)))
8c4f2952
JD
1168 (setq dir (command-line-normalize-file-name dir))
1169 (process-put proc 'server-client-directory dir))
59003be9
SM
1170
1171 ;; Unknown command.
1172 (arg (error "Unknown command: %s" arg))))
c48254fb 1173
9a864fa2
CY
1174 ;; If both -no-wait and -tty are given with file or sexp
1175 ;; arguments, use an existing frame.
1176 (and nowait
1177 (not (eq tty-name 'window-system))
1178 (or files commands)
1179 (setq use-current-frame t))
1180
cd9c54eb
CY
1181 (setq frame
1182 (cond
1183 ((and use-current-frame
1184 (or (eq use-current-frame 'always)
1185 ;; We can't use the Emacs daemon's
1186 ;; terminal frame.
d9bf544c 1187 (not (and (daemonp)
97e121cc 1188 (null (cdr (frame-list)))
cd9c54eb
CY
1189 (eq (selected-frame)
1190 terminal-frame)))))
d9bf544c 1191 (setq tty-name nil tty-type nil)
cd9c54eb
CY
1192 (if display (server-select-display display)))
1193 ((eq tty-name 'window-system)
0191e222 1194 (server-create-window-system-frame display nowait proc
18a4ce5e
AR
1195 parent-id
1196 frame-parameters))
650d0dbc
CY
1197 ;; When resuming on a tty, tty-name is nil.
1198 (tty-name
1199 (server-create-tty-frame tty-name tty-type proc))))
13ba3740 1200
28cbade4
SM
1201 (process-put
1202 proc 'continuation
94d11cb5
IK
1203 (lambda ()
1204 (with-current-buffer (get-buffer-create server-buffer)
1205 ;; Use the same cwd as the emacsclient, if possible, so
1206 ;; relative file names work correctly, even in `eval'.
1207 (let ((default-directory
1208 (if (and dir (file-directory-p dir))
1209 dir default-directory)))
1210 (server-execute proc files nowait commands
1211 dontkill frame tty-name)))))
13ba3740
SM
1212
1213 (when (or frame files)
1214 (server-goto-toplevel proc))
1215
1216 (server-execute-continuation proc))))
a9298135 1217 ;; condition-case
13ba3740
SM
1218 (error (server-return-error proc err))))
1219
1220(defun server-execute (proc files nowait commands dontkill frame tty-name)
7197f5de
SM
1221 ;; This is run from timers and process-filters, i.e. "asynchronously".
1222 ;; But w.r.t the user, this is not really asynchronous since the timer
1223 ;; is run after 0s and the process-filter is run in response to the
1224 ;; user running `emacsclient'. So it is OK to override the
1225 ;; inhibit-quit flag, which is good since `commands' (as well as
1226 ;; find-file-noselect via the major-mode) can run arbitrary code,
1227 ;; including code that needs to wait.
1228 (with-local-quit
1229 (condition-case err
de6ff46d 1230 (let ((buffers (server-visit-files files proc nowait)))
7197f5de
SM
1231 (mapc 'funcall (nreverse commands))
1232
de6ff46d
CY
1233 ;; If we were told only to open a new client, obey
1234 ;; `initial-buffer-choice' if it specifies a file.
1235 (unless (or files commands)
1236 (if (stringp initial-buffer-choice)
1237 (find-file initial-buffer-choice)
1238 (switch-to-buffer (get-buffer-create "*scratch*")
1239 'norecord)))
1240
7197f5de
SM
1241 ;; Delete the client if necessary.
1242 (cond
1243 (nowait
1244 ;; Client requested nowait; return immediately.
1245 (server-log "Close nowait client" proc)
1246 (server-delete-client proc))
1247 ((and (not dontkill) (null buffers))
1248 ;; This client is empty; get rid of it immediately.
1249 (server-log "Close empty client" proc)
1250 (server-delete-client proc)))
1251 (cond
1252 ((or isearch-mode (minibufferp))
1253 nil)
1254 ((and frame (null buffers))
13ba3740 1255 (message "%s" (substitute-command-keys
7197f5de
SM
1256 "When done with this frame, type \\[delete-frame]")))
1257 ((not (null buffers))
1258 (server-switch-buffer (car buffers) nil (cdr (car files)))
1259 (run-hooks 'server-switch-hook)
1260 (unless nowait
1261 (message "%s" (substitute-command-keys
1262 "When done with a buffer, type \\[server-edit]")))))
1263 (when (and frame (null tty-name))
1264 (server-unselect-display frame)))
b768cdcd
JB
1265 ((quit error)
1266 (when (eq (car err) 'quit)
1267 (message "Quit emacsclient request"))
1268 (server-return-error proc err)))))
13ba3740
SM
1269
1270(defun server-return-error (proc err)
1271 (ignore-errors
1272 (server-send-string
1273 proc (concat "-error " (server-quote-arg
1274 (error-message-string err))))
1275 (server-log (error-message-string err) proc)
2a847524
CY
1276 ;; Before calling `delete-process', give emacsclient time to
1277 ;; receive the error string and shut down on its own.
1278 (sit-for 5)
13ba3740 1279 (delete-process proc)))
9ae0f972 1280
656d4706
SM
1281(defun server-goto-line-column (line-col)
1282 "Move point to the position indicated in LINE-COL.
1283LINE-COL should be a pair (LINE . COL)."
1284 (when line-col
e6ce8c42
GM
1285 (goto-char (point-min))
1286 (forward-line (1- (car line-col)))
656d4706
SM
1287 (let ((column-number (cdr line-col)))
1288 (when (> column-number 0)
1289 (move-to-column (1- column-number))))))
6b98185f 1290
448f754f 1291(defun server-visit-files (files proc &optional nowait)
c5b0a355 1292 "Find FILES and return a list of buffers created.
656d4706
SM
1293FILES is an alist whose elements are (FILENAME . FILEPOS)
1294where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
448f754f 1295PROC is the client that requested this operation.
dfa35e6b
RS
1296NOWAIT non-nil means this client is not waiting for the results,
1297so don't mark these buffers specially, just visit them normally."
e82e73c2 1298 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
44a56b29 1299 (let ((last-nonmenu-event t) client-record)
3a0ce849
RS
1300 ;; Restore the current buffer afterward, but not using save-excursion,
1301 ;; because we don't want to save point in this buffer
1302 ;; if it happens to be one of those specified by the server.
44a56b29
SM
1303 (save-current-buffer
1304 (dolist (file files)
1305 ;; If there is an existing buffer modified or the file is
1306 ;; modified, revert it. If there is an existing buffer with
1307 ;; deleted file, offer to write it.
cd7320d4 1308 (let* ((minibuffer-auto-raise (or server-raise-frame
974b73e8 1309 minibuffer-auto-raise))
c2d0d432 1310 (filen (car file))
44a56b29 1311 (obuf (get-file-buffer filen)))
c398358a 1312 (add-to-history 'file-name-history filen)
656d4706 1313 (if (null obuf)
38dbc4d8 1314 (progn
56e6cc31 1315 (run-hooks 'pre-command-hook)
38dbc4d8 1316 (set-buffer (find-file-noselect filen)))
656d4706 1317 (set-buffer obuf)
38dbc4d8
DR
1318 ;; separately for each file, in sync with post-command hooks,
1319 ;; with the new buffer current:
56e6cc31 1320 (run-hooks 'pre-command-hook)
656d4706
SM
1321 (cond ((file-exists-p filen)
1322 (when (not (verify-visited-file-modtime obuf))
1323 (revert-buffer t nil)))
1324 (t
1325 (when (y-or-n-p
1326 (concat "File no longer exists: " filen
1327 ", write buffer to file? "))
1328 (write-file filen))))
1329 (unless server-buffer-clients
1330 (setq server-existing-buffer t)))
1331 (server-goto-line-column (cdr file))
38dbc4d8
DR
1332 (run-hooks 'server-visit-hook)
1333 ;; hooks may be specific to current buffer:
56e6cc31 1334 (run-hooks 'post-command-hook))
44a56b29
SM
1335 (unless nowait
1336 ;; When the buffer is killed, inform the clients.
1337 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
448f754f 1338 (push proc server-buffer-clients))
c5b0a355
KL
1339 (push (current-buffer) client-record)))
1340 (unless nowait
448f754f
SM
1341 (process-put proc 'buffers
1342 (nconc (process-get proc 'buffers) client-record)))
c5b0a355 1343 client-record))
d032d5e7
SM
1344
1345(defvar server-kill-buffer-running nil
1346 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1347
b392bac9 1348(defun server-buffer-done (buffer &optional for-killing)
9ae0f972 1349 "Mark BUFFER as \"done\" for its client(s).
9184aafb
RS
1350This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1351NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
8b3e840e
SM
1352or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1353a temp file).
1354FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
0c851d78 1355 (let ((next-buffer nil)
9002956f 1356 (killed nil))
448f754f
SM
1357 (dolist (proc server-clients)
1358 (let ((buffers (process-get proc 'buffers)))
8b3e840e 1359 (or next-buffer
9002956f
KL
1360 (setq next-buffer (nth 1 (memq buffer buffers))))
1361 (when buffers ; Ignore bufferless clients.
1362 (setq buffers (delq buffer buffers))
448f754f 1363 ;; Delete all dead buffers from PROC.
9002956f
KL
1364 (dolist (b buffers)
1365 (and (bufferp b)
1366 (not (buffer-live-p b))
1367 (setq buffers (delq b buffers))))
448f754f 1368 (process-put proc 'buffers buffers)
9002956f
KL
1369 ;; If client now has no pending buffers,
1370 ;; tell it that it is done, and forget it entirely.
1371 (unless buffers
448f754f 1372 (server-log "Close" proc)
737e5c83
CY
1373 (if for-killing
1374 ;; `server-delete-client' might delete the client's
1375 ;; frames, which might change the current buffer. We
1376 ;; don't want that (bug#640).
1377 (save-current-buffer
1378 (server-delete-client proc))
1379 (server-delete-client proc))))))
337e3c70
JB
1380 (when (and (bufferp buffer) (buffer-name buffer))
1381 ;; We may or may not kill this buffer;
1382 ;; if we do, do not call server-buffer-done recursively
1383 ;; from kill-buffer-hook.
1384 (let ((server-kill-buffer-running t))
1385 (with-current-buffer buffer
1386 (setq server-buffer-clients nil)
1387 (run-hooks 'server-done-hook))
1388 ;; Notice whether server-done-hook killed the buffer.
1389 (if (null (buffer-name buffer))
1390 (setq killed t)
1391 ;; Don't bother killing or burying the buffer
1392 ;; when we are called from kill-buffer.
1393 (unless for-killing
1394 (when (and (not killed)
1395 server-kill-new-buffers
1396 (with-current-buffer buffer
1397 (not server-existing-buffer)))
599f9a5c 1398 (setq killed t)
337e3c70 1399 (bury-buffer buffer)
2d25aa5a
CY
1400 ;; Prevent kill-buffer from prompting (Bug#3696).
1401 (with-current-buffer buffer
1402 (set-buffer-modified-p nil))
337e3c70
JB
1403 (kill-buffer buffer))
1404 (unless killed
1405 (if (server-temp-file-p buffer)
1406 (progn
2d25aa5a
CY
1407 (with-current-buffer buffer
1408 (set-buffer-modified-p nil))
337e3c70
JB
1409 (kill-buffer buffer)
1410 (setq killed t))
1411 (bury-buffer buffer)))))))
9184aafb 1412 (list next-buffer killed)))
9ae0f972 1413
408784a7 1414(defun server-temp-file-p (&optional buffer)
9ae0f972 1415 "Return non-nil if BUFFER contains a file considered temporary.
1416These are files whose names suggest they are repeatedly
1417reused to pass information to another program.
1418
1419The variable `server-temp-file-regexp' controls which filenames
1420are considered temporary."
1421 (and (buffer-file-name buffer)
a77ad240 1422 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
9ae0f972 1423
1424(defun server-done ()
cc9875f9 1425 "Offer to save current buffer, mark it as \"done\" for clients.
ed9ae328
RS
1426This kills or buries the buffer, then returns a list
1427of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1428as a suggestion for what to select next, or nil.
1429KILLED is t if we killed BUFFER, which happens if it was created
1430specifically for the clients and did not exist before their request for it."
408784a7
SM
1431 (when server-buffer-clients
1432 (if (server-temp-file-p)
1433 ;; For a temp file, save, and do make a non-numeric backup
1434 ;; (unless make-backup-files is nil).
1435 (let ((version-control nil)
1436 (buffer-backed-up nil))
1437 (save-buffer))
337e3c70
JB
1438 (when (and (buffer-modified-p)
1439 buffer-file-name
1440 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1441 (save-buffer)))
408784a7 1442 (server-buffer-done (current-buffer))))
faf931a8 1443
71207de2
RS
1444;; Ask before killing a server buffer.
1445;; It was suggested to release its client instead,
1446;; but I think that is dangerous--the client would proceed
1447;; using whatever is on disk in that file. -- rms.
03d78665 1448(defun server-kill-buffer-query-function ()
9002956f 1449 "Ask before killing a server buffer."
03d78665 1450 (or (not server-buffer-clients)
114a8b8c 1451 (let ((res t))
2403c841 1452 (dolist (proc server-buffer-clients)
448f754f
SM
1453 (when (and (memq proc server-clients)
1454 (eq (process-status proc) 'open))
2403c841
SM
1455 (setq res nil)))
1456 res)
03d78665
RS
1457 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1458 (buffer-name (current-buffer))))))
1459
03d78665 1460(defun server-kill-emacs-query-function ()
c48254fb 1461 "Ask before exiting Emacs if it has live clients."
9002956f
KL
1462 (or (not server-clients)
1463 (let (live-client)
2403c841 1464 (dolist (proc server-clients)
448f754f
SM
1465 (when (memq t (mapcar 'buffer-live-p (process-get
1466 proc 'buffers)))
2403c841
SM
1467 (setq live-client t)))
1468 live-client)
9002956f 1469 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
b392bac9 1470
b392bac9 1471(defun server-kill-buffer ()
6d3a46f7
KL
1472 "Remove the current buffer from its clients' buffer list.
1473Designed to be added to `kill-buffer-hook'."
fb873cfc
RS
1474 ;; Prevent infinite recursion if user has made server-done-hook
1475 ;; call kill-buffer.
1476 (or server-kill-buffer-running
599f9a5c
RS
1477 (and server-buffer-clients
1478 (let ((server-kill-buffer-running t))
1479 (when server-process
1480 (server-buffer-done (current-buffer) t))))))
9ae0f972 1481\f
1482(defun server-edit (&optional arg)
1483 "Switch to next server editing buffer; say \"Done\" for current buffer.
1484If a server buffer is current, it is marked \"done\" and optionally saved.
ed9ae328 1485The buffer is also killed if it did not exist before the clients asked for it.
9ae0f972 1486When all of a client's buffers are marked as \"done\", the client is notified.
1487
1488Temporary files such as MH <draft> files are always saved and backed up,
991298c3
RS
1489no questions asked. (The variable `make-backup-files', if nil, still
1490inhibits a backup; you can set it locally in a particular buffer to
1491prevent a backup for it.) The variable `server-temp-file-regexp' controls
9ae0f972 1492which filenames are considered temporary.
1493
64f51134 1494If invoked with a prefix argument, or if there is no server process running,
9ae0f972 1495starts server process and that is all. Invoked by \\[server-edit]."
9ae0f972 1496 (interactive "P")
6b519504 1497 (cond
94d11cb5
IK
1498 ((or arg
1499 (not server-process)
1500 (memq (process-status server-process) '(signal exit)))
1501 (server-mode 1))
1502 (server-clients (apply 'server-switch-buffer (server-done)))
1503 (t (message "No server editing buffers exist"))))
9ae0f972 1504
ee0aed46 1505(defun server-switch-buffer (&optional next-buffer killed-one filepos)
9ae0f972 1506 "Switch to another buffer, preferably one that has a client.
6d3a46f7
KL
1507Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1508
1509KILLED-ONE is t in a recursive call if we have already killed one
1510temp-file server buffer. This means we should avoid the final
1511\"switch to some other buffer\" since we've already effectively
ee0aed46
CY
1512done that.
1513
1514FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1515visit NEXT-BUFFER in an existing window. If non-nil, it should
1516be a cons cell (LINENUMBER . COLUMNNUMBER)."
ca0c7250 1517 (if (null next-buffer)
9002956f
KL
1518 (progn
1519 (let ((rest server-clients))
1520 (while (and rest (not next-buffer))
448f754f 1521 (let ((proc (car rest)))
a7ce6c7f
AS
1522 ;; Only look at frameless clients, or those in the selected
1523 ;; frame.
1524 (when (or (not (process-get proc 'frame))
1525 (eq (process-get proc 'frame) (selected-frame)))
448f754f 1526 (setq next-buffer (car (process-get proc 'buffers))))
9002956f
KL
1527 (setq rest (cdr rest)))))
1528 (and next-buffer (server-switch-buffer next-buffer killed-one))
1529 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1530 ;; (switch-to-buffer (other-buffer))
90ee5627 1531 (message "No server buffers remain to edit")))
9002956f 1532 (if (not (buffer-live-p next-buffer))
ca0c7250 1533 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
9ae0f972 1534 ;; and try the next surviving server buffer.
ca0c7250
SM
1535 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1536 ;; OK, we know next-buffer is live, let's display and select it.
408784a7
SM
1537 (if (functionp server-window)
1538 (funcall server-window next-buffer)
1539 (let ((win (get-buffer-window next-buffer 0)))
1540 (if (and win (not server-window))
ee0aed46
CY
1541 ;; The buffer is already displayed: just reuse the
1542 ;; window. If FILEPOS is non-nil, use it to replace the
1543 ;; window's own value of point.
90caccca
JB
1544 (progn
1545 (select-window win)
ee0aed46
CY
1546 (set-buffer next-buffer)
1547 (when filepos
1548 (server-goto-line-column filepos)))
408784a7 1549 ;; Otherwise, let's find an appropriate window.
60b4b298 1550 (cond ((window-live-p server-window)
408784a7
SM
1551 (select-window server-window))
1552 ((framep server-window)
337e3c70
JB
1553 (unless (frame-live-p server-window)
1554 (setq server-window (make-frame)))
408784a7 1555 (select-window (frame-selected-window server-window))))
337e3c70
JB
1556 (when (window-minibuffer-p (selected-window))
1557 (select-window (next-window nil 'nomini 0)))
408784a7
SM
1558 ;; Move to a non-dedicated window, if we have one.
1559 (when (window-dedicated-p (selected-window))
1560 (select-window
1561 (get-window-with-predicate
1562 (lambda (w)
1563 (and (not (window-dedicated-p w))
6ed8eeff
KL
1564 (equal (frame-terminal (window-frame w))
1565 (frame-terminal (selected-frame)))))
408784a7
SM
1566 'nomini 'visible (selected-window))))
1567 (condition-case nil
1568 (switch-to-buffer next-buffer)
1569 ;; After all the above, we might still have ended up with
1570 ;; a minibuffer/dedicated-window (if there's no other).
90caccca
JB
1571 (error (pop-to-buffer next-buffer)))))))
1572 (when server-raise-frame
1573 (select-frame-set-input-focus (window-frame (selected-window))))))
9ae0f972 1574
59e085e0 1575;;;###autoload
ac088d51 1576(defun server-save-buffers-kill-terminal (arg)
c61a4448 1577 ;; Called from save-buffers-kill-terminal in files.el.
ac088d51 1578 "Offer to save each buffer, then kill the current client.
a77ad240 1579With ARG non-nil, silently save all file-visiting buffers, then kill.
7540c1e0
KL
1580
1581If emacsclient was started with a list of filenames to edit, then
1582only these files will be asked to be saved."
ac088d51
CY
1583 (let ((proc (frame-parameter (selected-frame) 'client)))
1584 (cond ((eq proc 'nowait)
1585 ;; Nowait frames have no client buffer list.
1586 (if (cdr (frame-list))
1587 (progn (save-some-buffers arg)
1588 (delete-frame))
1589 ;; If we're the last frame standing, kill Emacs.
1590 (save-buffers-kill-emacs arg)))
1591 ((processp proc)
1592 (let ((buffers (process-get proc 'buffers)))
1593 ;; If client is bufferless, emulate a normal Emacs exit
1594 ;; and offer to save all buffers. Otherwise, offer to
1595 ;; save only the buffers belonging to the client.
1596 (save-some-buffers
1597 arg (if buffers
1598 (lambda () (memq (current-buffer) buffers))
1599 t))
1600 (server-delete-client proc)))
1601 (t (error "Invalid client frame")))))
b4ca0271 1602
772c5eb7 1603(define-key ctl-x-map "#" 'server-edit)
df4e8a11 1604
08446d5e 1605(defun server-unload-function ()
6d3a46f7 1606 "Unload the server library."
2e8457a0 1607 (server-mode -1)
a8e0c053 1608 (substitute-key-definition 'server-edit nil ctl-x-map)
08446d5e
JB
1609 (save-current-buffer
1610 (dolist (buffer (buffer-list))
1611 (set-buffer buffer)
1612 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1613 ;; continue standard unloading
1614 nil)
3bb38bc2 1615
e793a940 1616(defun server-eval-at (server form)
953cebf5
GM
1617 "Contact the Emacs server named SERVER and evaluate FORM there.
1618Returns the result of the evaluation, or signals an error if it
1619cannot contact the specified server. For example:
1620 \(server-eval-at \"server\" '(emacs-pid))
ad0bf5b6
AS
1621returns the process ID of the Emacs instance running \"server\"."
1622 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
1623 (server-file (expand-file-name server server-dir))
1624 (coding-system-for-read 'binary)
1625 (coding-system-for-write 'binary)
1626 address port secret process)
1627 (unless (file-exists-p server-file)
1628 (error "No such server: %s" server))
e793a940 1629 (with-temp-buffer
ad0bf5b6
AS
1630 (when server-use-tcp
1631 (let ((coding-system-for-read 'no-conversion))
1632 (insert-file-contents server-file)
1633 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1634 (error "Invalid auth file"))
1635 (setq address (match-string 1)
1636 port (string-to-number (match-string 2)))
1637 (forward-line 1)
1638 (setq secret (buffer-substring (point) (line-end-position)))
1639 (erase-buffer)))
1640 (unless (setq process (make-network-process
1641 :name "eval-at"
1642 :buffer (current-buffer)
1643 :host address
1644 :service (if server-use-tcp port server-file)
1645 :family (if server-use-tcp 'ipv4 'local)
1646 :noquery t))
1647 (error "Unable to contact the server"))
1648 (if server-use-tcp
1649 (process-send-string process (concat "-auth " secret "\n")))
1650 (process-send-string process
1651 (concat "-eval "
1652 (server-quote-arg (format "%S" form))
1653 "\n"))
e793a940
LMI
1654 (while (memq (process-status process) '(open run))
1655 (accept-process-output process 0 10))
1656 (goto-char (point-min))
1657 ;; If the result is nil, there's nothing in the buffer. If the
1658 ;; result is non-nil, it's after "-print ".
e29ab36b
AS
1659 (let ((answer ""))
1660 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t)
1661 (setq answer
1662 (concat answer
1663 (buffer-substring (point)
1664 (progn (skip-chars-forward "^\n")
1665 (point))))))
1666 (if (not (equal answer ""))
ad0bf5b6
AS
1667 (read (decode-coding-string (server-unquote-arg answer)
1668 'emacs-internal)))))))
e793a940 1669
16c15321
RM
1670\f
1671(provide 'server)
c88ab9ce
ER
1672
1673;;; server.el ends here