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