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