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