Fix emacsclient to work with cygw32
[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 1116 (not use-current-frame)))
5e0944c6
DC
1117 ;; On Windows, emacsclient always asks for a tty
1118 ;; frame. If running a GUI server, force the frame
1119 ;; type to GUI. (Cygwin is perfectly happy with
1120 ;; multi-tty support, so don't override the user's
1121 ;; choice there.)
1122 (when (and (eq system-type 'windows-nt)
1123 (eq window-system 'w32))
520fca41 1124 (push "-window-system" args-left)))
59003be9
SM
1125
1126 ;; -position LINE[:COLUMN]: Set point to the given
1127 ;; position in the next file.
1128 (`"-position"
1129 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1130 (car args-left)))
1131 (error "Invalid -position command in client args"))
1132 (let ((arg (pop args-left)))
1133 (setq filepos
1134 (cons (string-to-number (match-string 1 arg))
1135 (string-to-number (or (match-string 2 arg)
1136 ""))))))
1137
1138 ;; -file FILENAME: Load the given file.
1139 (`"-file"
1140 (let ((file (pop args-left)))
1141 (if coding-system
1142 (setq file (decode-coding-string file coding-system)))
1143 (setq file (expand-file-name file dir))
1144 (push (cons file filepos) files)
1145 (server-log (format "New file: %s %s"
1146 file (or filepos "")) proc))
1147 (setq filepos nil))
1148
1149 ;; -eval EXPR: Evaluate a Lisp expression.
1150 (`"-eval"
1151 (if use-current-frame
1152 (setq use-current-frame 'always))
c530e1c2 1153 (let ((expr (pop args-left)))
59003be9
SM
1154 (if coding-system
1155 (setq expr (decode-coding-string expr coding-system)))
1156 (push (lambda () (server-eval-and-print expr proc))
1157 commands)
1158 (setq filepos nil)))
1159
1160 ;; -env NAME=VALUE: An environment variable.
1161 (`"-env"
1162 (let ((var (pop args-left)))
1163 ;; XXX Variables should be encoded as in getenv/setenv.
1164 (process-put proc 'env
1165 (cons var (process-get proc 'env)))))
1166
1167 ;; -dir DIRNAME: The cwd of the emacsclient process.
1168 (`"-dir"
1169 (setq dir (pop args-left))
1170 (if coding-system
1171 (setq dir (decode-coding-string dir coding-system)))
8c4f2952
JD
1172 (setq dir (command-line-normalize-file-name dir))
1173 (process-put proc 'server-client-directory dir))
59003be9
SM
1174
1175 ;; Unknown command.
1176 (arg (error "Unknown command: %s" arg))))
c48254fb 1177
9a864fa2
CY
1178 ;; If both -no-wait and -tty are given with file or sexp
1179 ;; arguments, use an existing frame.
1180 (and nowait
1181 (not (eq tty-name 'window-system))
1182 (or files commands)
1183 (setq use-current-frame t))
1184
cd9c54eb
CY
1185 (setq frame
1186 (cond
1187 ((and use-current-frame
1188 (or (eq use-current-frame 'always)
1189 ;; We can't use the Emacs daemon's
1190 ;; terminal frame.
d9bf544c 1191 (not (and (daemonp)
97e121cc 1192 (null (cdr (frame-list)))
cd9c54eb
CY
1193 (eq (selected-frame)
1194 terminal-frame)))))
d9bf544c 1195 (setq tty-name nil tty-type nil)
cd9c54eb
CY
1196 (if display (server-select-display display)))
1197 ((eq tty-name 'window-system)
0191e222 1198 (server-create-window-system-frame display nowait proc
18a4ce5e
AR
1199 parent-id
1200 frame-parameters))
650d0dbc
CY
1201 ;; When resuming on a tty, tty-name is nil.
1202 (tty-name
1203 (server-create-tty-frame tty-name tty-type proc))))
13ba3740 1204
28cbade4
SM
1205 (process-put
1206 proc 'continuation
94d11cb5
IK
1207 (lambda ()
1208 (with-current-buffer (get-buffer-create server-buffer)
1209 ;; Use the same cwd as the emacsclient, if possible, so
1210 ;; relative file names work correctly, even in `eval'.
1211 (let ((default-directory
1212 (if (and dir (file-directory-p dir))
1213 dir default-directory)))
1214 (server-execute proc files nowait commands
1215 dontkill frame tty-name)))))
13ba3740
SM
1216
1217 (when (or frame files)
1218 (server-goto-toplevel proc))
1219
1220 (server-execute-continuation proc))))
a9298135 1221 ;; condition-case
13ba3740
SM
1222 (error (server-return-error proc err))))
1223
1224(defun server-execute (proc files nowait commands dontkill frame tty-name)
7197f5de
SM
1225 ;; This is run from timers and process-filters, i.e. "asynchronously".
1226 ;; But w.r.t the user, this is not really asynchronous since the timer
1227 ;; is run after 0s and the process-filter is run in response to the
1228 ;; user running `emacsclient'. So it is OK to override the
1229 ;; inhibit-quit flag, which is good since `commands' (as well as
1230 ;; find-file-noselect via the major-mode) can run arbitrary code,
1231 ;; including code that needs to wait.
1232 (with-local-quit
1233 (condition-case err
de6ff46d 1234 (let ((buffers (server-visit-files files proc nowait)))
7197f5de
SM
1235 (mapc 'funcall (nreverse commands))
1236
de6ff46d
CY
1237 ;; If we were told only to open a new client, obey
1238 ;; `initial-buffer-choice' if it specifies a file.
1239 (unless (or files commands)
1240 (if (stringp initial-buffer-choice)
1241 (find-file initial-buffer-choice)
1242 (switch-to-buffer (get-buffer-create "*scratch*")
1243 'norecord)))
1244
7197f5de
SM
1245 ;; Delete the client if necessary.
1246 (cond
1247 (nowait
1248 ;; Client requested nowait; return immediately.
1249 (server-log "Close nowait client" proc)
1250 (server-delete-client proc))
1251 ((and (not dontkill) (null buffers))
1252 ;; This client is empty; get rid of it immediately.
1253 (server-log "Close empty client" proc)
1254 (server-delete-client proc)))
1255 (cond
1256 ((or isearch-mode (minibufferp))
1257 nil)
1258 ((and frame (null buffers))
13ba3740 1259 (message "%s" (substitute-command-keys
7197f5de
SM
1260 "When done with this frame, type \\[delete-frame]")))
1261 ((not (null buffers))
1262 (server-switch-buffer (car buffers) nil (cdr (car files)))
1263 (run-hooks 'server-switch-hook)
1264 (unless nowait
1265 (message "%s" (substitute-command-keys
1266 "When done with a buffer, type \\[server-edit]")))))
1267 (when (and frame (null tty-name))
1268 (server-unselect-display frame)))
b768cdcd
JB
1269 ((quit error)
1270 (when (eq (car err) 'quit)
1271 (message "Quit emacsclient request"))
1272 (server-return-error proc err)))))
13ba3740
SM
1273
1274(defun server-return-error (proc err)
1275 (ignore-errors
1276 (server-send-string
1277 proc (concat "-error " (server-quote-arg
1278 (error-message-string err))))
1279 (server-log (error-message-string err) proc)
2a847524
CY
1280 ;; Before calling `delete-process', give emacsclient time to
1281 ;; receive the error string and shut down on its own.
1282 (sit-for 5)
13ba3740 1283 (delete-process proc)))
9ae0f972 1284
656d4706
SM
1285(defun server-goto-line-column (line-col)
1286 "Move point to the position indicated in LINE-COL.
1287LINE-COL should be a pair (LINE . COL)."
1288 (when line-col
e6ce8c42
GM
1289 (goto-char (point-min))
1290 (forward-line (1- (car line-col)))
656d4706
SM
1291 (let ((column-number (cdr line-col)))
1292 (when (> column-number 0)
1293 (move-to-column (1- column-number))))))
6b98185f 1294
448f754f 1295(defun server-visit-files (files proc &optional nowait)
c5b0a355 1296 "Find FILES and return a list of buffers created.
656d4706
SM
1297FILES is an alist whose elements are (FILENAME . FILEPOS)
1298where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
448f754f 1299PROC is the client that requested this operation.
dfa35e6b
RS
1300NOWAIT non-nil means this client is not waiting for the results,
1301so don't mark these buffers specially, just visit them normally."
e82e73c2 1302 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
44a56b29 1303 (let ((last-nonmenu-event t) client-record)
3a0ce849
RS
1304 ;; Restore the current buffer afterward, but not using save-excursion,
1305 ;; because we don't want to save point in this buffer
1306 ;; if it happens to be one of those specified by the server.
44a56b29
SM
1307 (save-current-buffer
1308 (dolist (file files)
1309 ;; If there is an existing buffer modified or the file is
1310 ;; modified, revert it. If there is an existing buffer with
1311 ;; deleted file, offer to write it.
cd7320d4 1312 (let* ((minibuffer-auto-raise (or server-raise-frame
974b73e8 1313 minibuffer-auto-raise))
c2d0d432 1314 (filen (car file))
44a56b29 1315 (obuf (get-file-buffer filen)))
c398358a 1316 (add-to-history 'file-name-history filen)
656d4706 1317 (if (null obuf)
38dbc4d8 1318 (progn
56e6cc31 1319 (run-hooks 'pre-command-hook)
38dbc4d8 1320 (set-buffer (find-file-noselect filen)))
656d4706 1321 (set-buffer obuf)
38dbc4d8
DR
1322 ;; separately for each file, in sync with post-command hooks,
1323 ;; with the new buffer current:
56e6cc31 1324 (run-hooks 'pre-command-hook)
656d4706
SM
1325 (cond ((file-exists-p filen)
1326 (when (not (verify-visited-file-modtime obuf))
1327 (revert-buffer t nil)))
1328 (t
1329 (when (y-or-n-p
1330 (concat "File no longer exists: " filen
1331 ", write buffer to file? "))
1332 (write-file filen))))
1333 (unless server-buffer-clients
1334 (setq server-existing-buffer t)))
1335 (server-goto-line-column (cdr file))
38dbc4d8
DR
1336 (run-hooks 'server-visit-hook)
1337 ;; hooks may be specific to current buffer:
56e6cc31 1338 (run-hooks 'post-command-hook))
44a56b29
SM
1339 (unless nowait
1340 ;; When the buffer is killed, inform the clients.
1341 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
448f754f 1342 (push proc server-buffer-clients))
c5b0a355
KL
1343 (push (current-buffer) client-record)))
1344 (unless nowait
448f754f
SM
1345 (process-put proc 'buffers
1346 (nconc (process-get proc 'buffers) client-record)))
c5b0a355 1347 client-record))
d032d5e7
SM
1348
1349(defvar server-kill-buffer-running nil
1350 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1351
b392bac9 1352(defun server-buffer-done (buffer &optional for-killing)
9ae0f972 1353 "Mark BUFFER as \"done\" for its client(s).
9184aafb
RS
1354This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1355NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
8b3e840e
SM
1356or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1357a temp file).
1358FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
0c851d78 1359 (let ((next-buffer nil)
9002956f 1360 (killed nil))
448f754f
SM
1361 (dolist (proc server-clients)
1362 (let ((buffers (process-get proc 'buffers)))
8b3e840e 1363 (or next-buffer
9002956f
KL
1364 (setq next-buffer (nth 1 (memq buffer buffers))))
1365 (when buffers ; Ignore bufferless clients.
1366 (setq buffers (delq buffer buffers))
448f754f 1367 ;; Delete all dead buffers from PROC.
9002956f
KL
1368 (dolist (b buffers)
1369 (and (bufferp b)
1370 (not (buffer-live-p b))
1371 (setq buffers (delq b buffers))))
448f754f 1372 (process-put proc 'buffers buffers)
9002956f
KL
1373 ;; If client now has no pending buffers,
1374 ;; tell it that it is done, and forget it entirely.
1375 (unless buffers
448f754f 1376 (server-log "Close" proc)
737e5c83
CY
1377 (if for-killing
1378 ;; `server-delete-client' might delete the client's
1379 ;; frames, which might change the current buffer. We
1380 ;; don't want that (bug#640).
1381 (save-current-buffer
1382 (server-delete-client proc))
1383 (server-delete-client proc))))))
337e3c70
JB
1384 (when (and (bufferp buffer) (buffer-name buffer))
1385 ;; We may or may not kill this buffer;
1386 ;; if we do, do not call server-buffer-done recursively
1387 ;; from kill-buffer-hook.
1388 (let ((server-kill-buffer-running t))
1389 (with-current-buffer buffer
1390 (setq server-buffer-clients nil)
1391 (run-hooks 'server-done-hook))
1392 ;; Notice whether server-done-hook killed the buffer.
1393 (if (null (buffer-name buffer))
1394 (setq killed t)
1395 ;; Don't bother killing or burying the buffer
1396 ;; when we are called from kill-buffer.
1397 (unless for-killing
1398 (when (and (not killed)
1399 server-kill-new-buffers
1400 (with-current-buffer buffer
1401 (not server-existing-buffer)))
599f9a5c 1402 (setq killed t)
337e3c70 1403 (bury-buffer buffer)
2d25aa5a
CY
1404 ;; Prevent kill-buffer from prompting (Bug#3696).
1405 (with-current-buffer buffer
1406 (set-buffer-modified-p nil))
337e3c70
JB
1407 (kill-buffer buffer))
1408 (unless killed
1409 (if (server-temp-file-p buffer)
1410 (progn
2d25aa5a
CY
1411 (with-current-buffer buffer
1412 (set-buffer-modified-p nil))
337e3c70
JB
1413 (kill-buffer buffer)
1414 (setq killed t))
1415 (bury-buffer buffer)))))))
9184aafb 1416 (list next-buffer killed)))
9ae0f972 1417
408784a7 1418(defun server-temp-file-p (&optional buffer)
9ae0f972 1419 "Return non-nil if BUFFER contains a file considered temporary.
1420These are files whose names suggest they are repeatedly
1421reused to pass information to another program.
1422
1423The variable `server-temp-file-regexp' controls which filenames
1424are considered temporary."
1425 (and (buffer-file-name buffer)
a77ad240 1426 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
9ae0f972 1427
1428(defun server-done ()
cc9875f9 1429 "Offer to save current buffer, mark it as \"done\" for clients.
ed9ae328
RS
1430This kills or buries the buffer, then returns a list
1431of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1432as a suggestion for what to select next, or nil.
1433KILLED is t if we killed BUFFER, which happens if it was created
1434specifically for the clients and did not exist before their request for it."
408784a7
SM
1435 (when server-buffer-clients
1436 (if (server-temp-file-p)
1437 ;; For a temp file, save, and do make a non-numeric backup
1438 ;; (unless make-backup-files is nil).
1439 (let ((version-control nil)
1440 (buffer-backed-up nil))
1441 (save-buffer))
337e3c70
JB
1442 (when (and (buffer-modified-p)
1443 buffer-file-name
1444 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1445 (save-buffer)))
408784a7 1446 (server-buffer-done (current-buffer))))
faf931a8 1447
71207de2
RS
1448;; Ask before killing a server buffer.
1449;; It was suggested to release its client instead,
1450;; but I think that is dangerous--the client would proceed
1451;; using whatever is on disk in that file. -- rms.
03d78665 1452(defun server-kill-buffer-query-function ()
9002956f 1453 "Ask before killing a server buffer."
03d78665 1454 (or (not server-buffer-clients)
114a8b8c 1455 (let ((res t))
2403c841 1456 (dolist (proc server-buffer-clients)
448f754f
SM
1457 (when (and (memq proc server-clients)
1458 (eq (process-status proc) 'open))
2403c841
SM
1459 (setq res nil)))
1460 res)
03d78665
RS
1461 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1462 (buffer-name (current-buffer))))))
1463
03d78665 1464(defun server-kill-emacs-query-function ()
c48254fb 1465 "Ask before exiting Emacs if it has live clients."
9002956f
KL
1466 (or (not server-clients)
1467 (let (live-client)
2403c841 1468 (dolist (proc server-clients)
448f754f
SM
1469 (when (memq t (mapcar 'buffer-live-p (process-get
1470 proc 'buffers)))
2403c841
SM
1471 (setq live-client t)))
1472 live-client)
9002956f 1473 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
b392bac9 1474
b392bac9 1475(defun server-kill-buffer ()
6d3a46f7
KL
1476 "Remove the current buffer from its clients' buffer list.
1477Designed to be added to `kill-buffer-hook'."
fb873cfc
RS
1478 ;; Prevent infinite recursion if user has made server-done-hook
1479 ;; call kill-buffer.
1480 (or server-kill-buffer-running
599f9a5c
RS
1481 (and server-buffer-clients
1482 (let ((server-kill-buffer-running t))
1483 (when server-process
1484 (server-buffer-done (current-buffer) t))))))
9ae0f972 1485\f
1486(defun server-edit (&optional arg)
1487 "Switch to next server editing buffer; say \"Done\" for current buffer.
1488If a server buffer is current, it is marked \"done\" and optionally saved.
ed9ae328 1489The buffer is also killed if it did not exist before the clients asked for it.
9ae0f972 1490When all of a client's buffers are marked as \"done\", the client is notified.
1491
1492Temporary files such as MH <draft> files are always saved and backed up,
991298c3
RS
1493no questions asked. (The variable `make-backup-files', if nil, still
1494inhibits a backup; you can set it locally in a particular buffer to
1495prevent a backup for it.) The variable `server-temp-file-regexp' controls
9ae0f972 1496which filenames are considered temporary.
1497
64f51134 1498If invoked with a prefix argument, or if there is no server process running,
9ae0f972 1499starts server process and that is all. Invoked by \\[server-edit]."
9ae0f972 1500 (interactive "P")
6b519504 1501 (cond
94d11cb5
IK
1502 ((or arg
1503 (not server-process)
1504 (memq (process-status server-process) '(signal exit)))
1505 (server-mode 1))
1506 (server-clients (apply 'server-switch-buffer (server-done)))
1507 (t (message "No server editing buffers exist"))))
9ae0f972 1508
ee0aed46 1509(defun server-switch-buffer (&optional next-buffer killed-one filepos)
9ae0f972 1510 "Switch to another buffer, preferably one that has a client.
6d3a46f7
KL
1511Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1512
1513KILLED-ONE is t in a recursive call if we have already killed one
1514temp-file server buffer. This means we should avoid the final
1515\"switch to some other buffer\" since we've already effectively
ee0aed46
CY
1516done that.
1517
1518FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1519visit NEXT-BUFFER in an existing window. If non-nil, it should
1520be a cons cell (LINENUMBER . COLUMNNUMBER)."
ca0c7250 1521 (if (null next-buffer)
9002956f
KL
1522 (progn
1523 (let ((rest server-clients))
1524 (while (and rest (not next-buffer))
448f754f 1525 (let ((proc (car rest)))
a7ce6c7f
AS
1526 ;; Only look at frameless clients, or those in the selected
1527 ;; frame.
1528 (when (or (not (process-get proc 'frame))
1529 (eq (process-get proc 'frame) (selected-frame)))
448f754f 1530 (setq next-buffer (car (process-get proc 'buffers))))
9002956f
KL
1531 (setq rest (cdr rest)))))
1532 (and next-buffer (server-switch-buffer next-buffer killed-one))
1533 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1534 ;; (switch-to-buffer (other-buffer))
90ee5627 1535 (message "No server buffers remain to edit")))
9002956f 1536 (if (not (buffer-live-p next-buffer))
ca0c7250 1537 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
9ae0f972 1538 ;; and try the next surviving server buffer.
ca0c7250
SM
1539 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1540 ;; OK, we know next-buffer is live, let's display and select it.
408784a7
SM
1541 (if (functionp server-window)
1542 (funcall server-window next-buffer)
1543 (let ((win (get-buffer-window next-buffer 0)))
1544 (if (and win (not server-window))
ee0aed46
CY
1545 ;; The buffer is already displayed: just reuse the
1546 ;; window. If FILEPOS is non-nil, use it to replace the
1547 ;; window's own value of point.
90caccca
JB
1548 (progn
1549 (select-window win)
ee0aed46
CY
1550 (set-buffer next-buffer)
1551 (when filepos
1552 (server-goto-line-column filepos)))
408784a7 1553 ;; Otherwise, let's find an appropriate window.
60b4b298 1554 (cond ((window-live-p server-window)
408784a7
SM
1555 (select-window server-window))
1556 ((framep server-window)
337e3c70
JB
1557 (unless (frame-live-p server-window)
1558 (setq server-window (make-frame)))
408784a7 1559 (select-window (frame-selected-window server-window))))
337e3c70
JB
1560 (when (window-minibuffer-p (selected-window))
1561 (select-window (next-window nil 'nomini 0)))
408784a7
SM
1562 ;; Move to a non-dedicated window, if we have one.
1563 (when (window-dedicated-p (selected-window))
1564 (select-window
1565 (get-window-with-predicate
1566 (lambda (w)
1567 (and (not (window-dedicated-p w))
6ed8eeff
KL
1568 (equal (frame-terminal (window-frame w))
1569 (frame-terminal (selected-frame)))))
408784a7
SM
1570 'nomini 'visible (selected-window))))
1571 (condition-case nil
1572 (switch-to-buffer next-buffer)
1573 ;; After all the above, we might still have ended up with
1574 ;; a minibuffer/dedicated-window (if there's no other).
90caccca
JB
1575 (error (pop-to-buffer next-buffer)))))))
1576 (when server-raise-frame
1577 (select-frame-set-input-focus (window-frame (selected-window))))))
9ae0f972 1578
59e085e0 1579;;;###autoload
ac088d51 1580(defun server-save-buffers-kill-terminal (arg)
c61a4448 1581 ;; Called from save-buffers-kill-terminal in files.el.
ac088d51 1582 "Offer to save each buffer, then kill the current client.
a77ad240 1583With ARG non-nil, silently save all file-visiting buffers, then kill.
7540c1e0
KL
1584
1585If emacsclient was started with a list of filenames to edit, then
1586only these files will be asked to be saved."
ac088d51
CY
1587 (let ((proc (frame-parameter (selected-frame) 'client)))
1588 (cond ((eq proc 'nowait)
1589 ;; Nowait frames have no client buffer list.
1590 (if (cdr (frame-list))
1591 (progn (save-some-buffers arg)
1592 (delete-frame))
1593 ;; If we're the last frame standing, kill Emacs.
1594 (save-buffers-kill-emacs arg)))
1595 ((processp proc)
1596 (let ((buffers (process-get proc 'buffers)))
1597 ;; If client is bufferless, emulate a normal Emacs exit
1598 ;; and offer to save all buffers. Otherwise, offer to
1599 ;; save only the buffers belonging to the client.
1600 (save-some-buffers
1601 arg (if buffers
1602 (lambda () (memq (current-buffer) buffers))
1603 t))
1604 (server-delete-client proc)))
1605 (t (error "Invalid client frame")))))
b4ca0271 1606
772c5eb7 1607(define-key ctl-x-map "#" 'server-edit)
df4e8a11 1608
08446d5e 1609(defun server-unload-function ()
6d3a46f7 1610 "Unload the server library."
2e8457a0 1611 (server-mode -1)
a8e0c053 1612 (substitute-key-definition 'server-edit nil ctl-x-map)
08446d5e
JB
1613 (save-current-buffer
1614 (dolist (buffer (buffer-list))
1615 (set-buffer buffer)
1616 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1617 ;; continue standard unloading
1618 nil)
3bb38bc2 1619
e793a940 1620(defun server-eval-at (server form)
953cebf5
GM
1621 "Contact the Emacs server named SERVER and evaluate FORM there.
1622Returns the result of the evaluation, or signals an error if it
1623cannot contact the specified server. For example:
1624 \(server-eval-at \"server\" '(emacs-pid))
ad0bf5b6
AS
1625returns the process ID of the Emacs instance running \"server\"."
1626 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
1627 (server-file (expand-file-name server server-dir))
1628 (coding-system-for-read 'binary)
1629 (coding-system-for-write 'binary)
1630 address port secret process)
1631 (unless (file-exists-p server-file)
1632 (error "No such server: %s" server))
e793a940 1633 (with-temp-buffer
ad0bf5b6
AS
1634 (when server-use-tcp
1635 (let ((coding-system-for-read 'no-conversion))
1636 (insert-file-contents server-file)
1637 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1638 (error "Invalid auth file"))
1639 (setq address (match-string 1)
1640 port (string-to-number (match-string 2)))
1641 (forward-line 1)
1642 (setq secret (buffer-substring (point) (line-end-position)))
1643 (erase-buffer)))
1644 (unless (setq process (make-network-process
1645 :name "eval-at"
1646 :buffer (current-buffer)
1647 :host address
1648 :service (if server-use-tcp port server-file)
1649 :family (if server-use-tcp 'ipv4 'local)
1650 :noquery t))
1651 (error "Unable to contact the server"))
1652 (if server-use-tcp
1653 (process-send-string process (concat "-auth " secret "\n")))
1654 (process-send-string process
1655 (concat "-eval "
1656 (server-quote-arg (format "%S" form))
1657 "\n"))
e793a940
LMI
1658 (while (memq (process-status process) '(open run))
1659 (accept-process-output process 0 10))
1660 (goto-char (point-min))
1661 ;; If the result is nil, there's nothing in the buffer. If the
1662 ;; result is non-nil, it's after "-print ".
e29ab36b
AS
1663 (let ((answer ""))
1664 (while (re-search-forward "\n-print\\(-nonl\\)? " nil t)
1665 (setq answer
1666 (concat answer
1667 (buffer-substring (point)
1668 (progn (skip-chars-forward "^\n")
1669 (point))))))
1670 (if (not (equal answer ""))
ad0bf5b6
AS
1671 (read (decode-coding-string (server-unquote-arg answer)
1672 'emacs-internal)))))))
e793a940 1673
16c15321
RM
1674\f
1675(provide 'server)
c88ab9ce
ER
1676
1677;;; server.el ends here