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