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