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