Merged from emacs@sv.gnu.org
[bpt/emacs.git] / lisp / server.el
CommitLineData
55535639 1;;; server.el --- Lisp code for GNU Emacs running as server process
c88ab9ce 2
0d30b337 3;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
da6657b7 4;; 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
6d74b528 5
630cc463 6;; Author: William Sommerfeld <wesommer@athena.mit.edu>
e4874521 7;; Maintainer: FSF
d7b4d18f 8;; Keywords: processes
630cc463 9
9ae0f972 10;; Changes by peck@sun.com and by rms.
35dfa9b6 11;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
9ae0f972 12
13;; This file is part of GNU Emacs.
14
15;; GNU Emacs is free software; you can redistribute it and/or modify
16;; it under the terms of the GNU General Public License as published by
e5167999 17;; the Free Software Foundation; either version 2, or (at your option)
9ae0f972 18;; any later version.
19
20;; GNU Emacs is distributed in the hope that it will be useful,
21;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23;; GNU General Public License for more details.
24
25;; You should have received a copy of the GNU General Public License
b578f267 26;; along with GNU Emacs; see the file COPYING. If not, write to the
086add15
LK
27;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28;; Boston, MA 02110-1301, USA.
9ae0f972 29
630cc463 30;;; Commentary:
9ae0f972 31
b578f267
EN
32;; This Lisp code is run in Emacs when it is to operate as
33;; a server for other processes.
9ae0f972 34
b578f267 35;; Load this library and do M-x server-edit to enable Emacs as a server.
44a56b29
SM
36;; Emacs opens up a socket for communication with clients. If there are no
37;; client buffers to edit, server-edit acts like (switch-to-buffer
38;; (other-buffer))
9ae0f972 39
b578f267
EN
40;; When some other program runs "the editor" to edit a file,
41;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
42;; This program transmits the file names to Emacs through
43;; the server subprocess, and Emacs visits them and lets you edit them.
9ae0f972 44
6d3a46f7 45;; Note that any number of clients may dispatch files to Emacs to be edited.
9ae0f972 46
b578f267 47;; When you finish editing a Server buffer, again call server-edit
64f51134
JPW
48;; to mark that buffer as done for the client and switch to the next
49;; Server buffer. When all the buffers for a client have been edited
b578f267 50;; and exited with server-edit, the client "editor" will return
64f51134 51;; to the program that invoked it.
9ae0f972 52
b578f267
EN
53;; Your editing commands and Emacs's display output go to and from
54;; the terminal in the usual way. Thus, server operation is possible
55;; only when Emacs can talk to the terminal at the time you invoke
56;; the client. This is possible in four cases:
9ae0f972 57
b578f267
EN
58;; 1. On a window system, where Emacs runs in one window and the
59;; program that wants to use "the editor" runs in another.
9ae0f972 60
b578f267
EN
61;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
62;; program that wants to use "the editor" runs on another.
9ae0f972 63
b578f267
EN
64;; 3. When the program that wants to use "the editor" is running
65;; as a subprocess of Emacs.
9ae0f972 66
b578f267
EN
67;; 4. On a system with job control, when Emacs is suspended, the program
68;; that wants to use "the editor" will stop and display
69;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
70;; brought into the foreground for editing. When done editing, Emacs is
71;; suspended again, and the client program is brought into the foreground.
9ae0f972 72
64f51134
JPW
73;; The buffer local variable "server-buffer-clients" lists
74;; the clients who are waiting for this buffer to be edited.
b578f267
EN
75;; The global variable "server-clients" lists all the waiting clients,
76;; and which files are yet to be edited for each.
630cc463
ER
77
78;;; Code:
8b3e840e
SM
79
80(eval-when-compile (require 'cl))
81
ab1c7f35
RS
82(defgroup server nil
83 "Emacs running as a server process."
84 :group 'external)
85
337e3c70
JB
86(defcustom server-use-tcp nil
87 "If non-nil, use TCP sockets instead of local sockets."
88 :set #'(lambda (sym val)
89 (unless (featurep 'make-network-process '(:family local))
90 (setq val t)
91 (unless load-in-progress
92 (message "Local sockets unsupported, using TCP sockets")))
93 (when val (random t))
94 (set-default sym val))
95 :group 'server
96 :type 'boolean
97 :version "22.1")
98
99(defcustom server-host nil
100 "The name or IP address to use as host address of the server process.
101If set, the server accepts remote connections; otherwise it is local."
102 :group 'server
103 :type '(choice
104 (string :tag "Name or IP address")
105 (const :tag "Local" nil))
106 :version "22.1")
107(put 'server-host 'risky-local-variable t)
108
109(defcustom server-auth-dir "~/.emacs.d/server/"
110 "Directory for server authentication files."
111 :group 'server
112 :type 'directory
113 :version "22.1")
114(put 'server-auth-dir 'risky-local-variable t)
115
90caccca 116(defcustom server-raise-frame t
ff348fba 117 "If non-nil, raise frame when switching to a buffer."
90caccca
JB
118 :group 'server
119 :type 'boolean
120 :version "22.1")
121
ab1c7f35 122(defcustom server-visit-hook nil
ff348fba 123 "Hook run when visiting a file for the Emacs server."
ab1c7f35 124 :group 'server
0c851d78 125 :type 'hook)
ab1c7f35
RS
126
127(defcustom server-switch-hook nil
ff348fba 128 "Hook run when switching to a buffer for the Emacs server."
ab1c7f35 129 :group 'server
0c851d78 130 :type 'hook)
ab1c7f35
RS
131
132(defcustom server-done-hook nil
ff348fba 133 "Hook run when done editing a buffer for the Emacs server."
ab1c7f35 134 :group 'server
0c851d78 135 :type 'hook)
f9b3ef88 136
64f51134
JPW
137(defvar server-process nil
138 "The current server process.")
9ae0f972 139
140(defvar server-clients nil
141 "List of current server clients.
9002956f
KL
142Each element is (PROC PROPERTIES...) where PROC is a process object,
143and PROPERTIES is an association list of client properties.")
0a125897 144
9ae0f972 145(defvar server-buffer-clients nil
5f3c1a63 146 "List of client processes requesting editing of current buffer.")
faf931a8 147(make-variable-buffer-local 'server-buffer-clients)
9ae0f972 148;; Changing major modes should not erase this local.
149(put 'server-buffer-clients 'permanent-local t)
150
33186f32 151(defcustom server-window nil
ff348fba 152 "Specification of the window to use for selecting Emacs server buffers.
ec40ed9f 153If nil, use the selected window.
408784a7 154If it is a function, it should take one argument (a buffer) and
33186f32
DL
155display and select it. A common value is `pop-to-buffer'.
156If it is a window, use that.
157If it is a frame, use the frame's selected window.
158
159It is not meaningful to set this to a specific frame or window with Custom.
160Only programs can do so."
161 :group 'server
bf247b6e 162 :version "22.1"
33186f32
DL
163 :type '(choice (const :tag "Use selected window"
164 :match (lambda (widget value)
165 (not (functionp value)))
166 nil)
167 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
168 (function :tag "Other function")))
ec40ed9f 169
ab1c7f35 170(defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
ff348fba 171 "Regexp matching names of temporary files.
33186f32
DL
172These are deleted and reused after each edit by the programs that
173invoke the Emacs server."
ab1c7f35
RS
174 :group 'server
175 :type 'regexp)
9ae0f972 176
c6a117f0 177(defcustom server-kill-new-buffers t
ff348fba 178 "Whether to kill buffers when done with them.
c6a117f0 179If non-nil, kill a buffer unless it already existed before editing
64f51134 180it with Emacs server. If nil, kill only buffers as specified by
c6a117f0
GM
181`server-temp-file-regexp'.
182Please note that only buffers are killed that still have a client,
183i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
184this way."
185 :group 'server
186 :type 'boolean
187 :version "21.1")
188
9ae0f972 189(or (assq 'server-buffer-clients minor-mode-alist)
b7621225 190 (push '(server-buffer-clients " Server") minor-mode-alist))
9ae0f972 191
c6a117f0 192(defvar server-existing-buffer nil
ca0c7250 193 "Non-nil means the buffer existed before the server was asked to visit it.
4dd04714 194This means that the server should not kill the buffer when you say you
ca0c7250 195are done with it in the server.")
c6a117f0
GM
196(make-variable-buffer-local 'server-existing-buffer)
197
03ae35cf
SM
198(defvar server-name "server")
199
fc0dcdef
KL
200(defvar server-socket-dir nil
201 "The directory in which to place the server socket.
202Initialized by `server-start'.")
0c851d78 203
9002956f
KL
204(defun server-client (proc)
205 "Return the Emacs client corresponding to PROC.
206PROC must be a process object.
207The car of the result is PROC; the cdr is an association list.
208See `server-client-get' and `server-client-set'."
209 (assq proc server-clients))
210
211(defun server-client-get (client property)
212 "Get the value of PROPERTY in CLIENT.
213CLIENT may be a process object, or a client returned by `server-client'.
214Return nil if CLIENT has no such property."
215 (or (listp client) (setq client (server-client client)))
216 (cdr (assq property (cdr client))))
217
218(defun server-client-set (client property value)
219 "Set the PROPERTY to VALUE in CLIENT, and return VALUE.
220CLIENT may be a process object, or a client returned by `server-client'."
221 (let (p proc)
222 (if (listp client)
223 (setq proc (car client))
224 (setq proc client
225 client (server-client client)))
226 (setq p (assq property client))
227 (cond
228 (p (setcdr p value))
229 (client (setcdr client (cons (cons property value) (cdr client))))
230 (t (setq server-clients
231 `((,proc (,property . ,value)) . ,server-clients))))
232 value))
233
234(defun server-clients-with (property value)
235 "Return a list of clients with PROPERTY set to VALUE."
236 (let (result)
237 (dolist (client server-clients result)
238 (when (equal value (server-client-get client property))
239 (setq result (cons (car client) result))))))
240
241(defun server-add-client (proc)
242 "Create a client for process PROC, if it doesn't already have one.
243New clients have no properties."
244 (unless (server-client proc)
245 (setq server-clients (cons (cons proc nil)
246 server-clients))))
247
59e085e0
KL
248(defun server-getenv-from (env variable)
249 "Get the value of VARIABLE in ENV.
250VARIABLE should be a string. Value is nil if VARIABLE is
251undefined in ENV. Otherwise, value is a string.
252
253ENV should be in the same format as `process-environment'."
254 (let (entry result)
255 (while (and env (null result))
256 (setq entry (car env)
257 env (cdr env))
258 (if (and (> (length entry) (length variable))
259 (eq ?= (aref entry (length variable)))
260 (equal variable (substring entry 0 (length variable))))
261 (setq result (substring entry (+ (length variable) 1)))))
262 result))
263
264(defmacro server-with-environment (env vars &rest body)
265 "Evaluate BODY with environment variables VARS set to those in ENV.
65f64034
KL
266The environment variables are then restored to their previous values.
267
59e085e0
KL
268VARS should be a list of strings.
269ENV should be in the same format as `process-environment'."
65f64034
KL
270 (declare (indent 2))
271 (let ((oldvalues (make-symbol "oldvalues"))
272 (var (make-symbol "var"))
273 (value (make-symbol "value"))
274 (pair (make-symbol "pair")))
275 `(let (,oldvalues)
59e085e0
KL
276 (dolist (,var ,vars)
277 (let ((,value (server-getenv-from ,env ,var)))
65f64034
KL
278 (setq ,oldvalues (cons (cons ,var (getenv ,var)) ,oldvalues))
279 (setenv ,var ,value)))
280 (unwind-protect
281 (progn ,@body)
282 (dolist (,pair ,oldvalues)
283 (setenv (car ,pair) (cdr ,pair)))))))
284
de93c791 285(defun server-delete-client (client &optional noframe)
6ed8eeff 286 "Delete CLIENT, including its buffers, terminals and frames.
de93c791 287If NOFRAME is non-nil, let the frames live. (To be used from
5f3c1a63
KL
288`delete-frame-functions'.)"
289 (server-log (concat "server-delete-client" (if noframe " noframe"))
290 client)
9002956f
KL
291 ;; Force a new lookup of client (prevents infinite recursion).
292 (setq client (server-client
293 (if (listp client) (car client) client)))
294 (let ((proc (car client))
295 (buffers (server-client-get client 'buffers)))
296 (when client
9002956f 297
5f3c1a63 298 ;; Kill the client's buffers.
9002956f 299 (dolist (buf buffers)
6ed9e43a
KL
300 (when (buffer-live-p buf)
301 (with-current-buffer buf
6ed9e43a 302 ;; Kill the buffer if necessary.
5f3c1a63
KL
303 (when (and (equal server-buffer-clients
304 (list proc))
6ed9e43a
KL
305 (or (and server-kill-new-buffers
306 (not server-existing-buffer))
5f3c1a63
KL
307 (server-temp-file-p))
308 (not (buffer-modified-p)))
309 (let (flag)
310 (unwind-protect
311 (progn (setq server-buffer-clients nil)
312 (kill-buffer (current-buffer))
313 (setq flag t))
314 (unless flag
315 ;; Restore clients if user pressed C-g in `kill-buffer'.
316 (setq server-buffer-clients (list proc)))))))))
9002956f 317
160f0817
KL
318 ;; Delete the client's frames.
319 (unless noframe
320 (dolist (frame (frame-list))
321 (when (and (frame-live-p frame)
322 (equal proc (frame-parameter frame 'client)))
323 ;; Prevent `server-handle-delete-frame' from calling us
324 ;; recursively.
325 (set-frame-parameter frame 'client nil)
326 (delete-frame frame))))
327
5f3c1a63
KL
328 (setq server-clients (delq client server-clients))
329
9002956f 330 ;; Delete the client's tty.
6ed8eeff
KL
331 (let ((terminal (server-client-get client 'terminal)))
332 (when (eq (terminal-live-p terminal) t)
333 (delete-terminal terminal)))
9002956f 334
9002956f
KL
335 ;; Delete the client's process.
336 (if (eq (process-status (car client)) 'open)
337 (delete-process (car client)))
338
339 (server-log "Deleted" proc))))
340
8b3e840e 341(defun server-log (string &optional client)
6d3a46f7
KL
342 "If a *server* buffer exists, write STRING to it for logging purposes.
343If CLIENT is non-nil, add a description of it to the logged
344message."
337e3c70
JB
345 (when (get-buffer "*server*")
346 (with-current-buffer "*server*"
347 (goto-char (point-max))
348 (insert (current-time-string)
974b73e8
KL
349 (cond
350 ((null client) " ")
351 ((listp client) (format " %s: " (car client)))
352 (t (format " %s: " client)))
337e3c70
JB
353 string)
354 (or (bolp) (newline)))))
9ae0f972 355
356(defun server-sentinel (proc msg)
9002956f 357 "The process sentinel for Emacs server connections."
cbfc02e4
RF
358 ;; If this is a new client process, set the query-on-exit flag to nil
359 ;; for this process (it isn't inherited from the server process).
360 (when (and (eq (process-status proc) 'open)
361 (process-query-on-exit-flag proc))
362 (set-process-query-on-exit-flag proc nil))
757e1681
SM
363 ;; Delete the associated connection file, if applicable.
364 ;; This is actually problematic: the file may have been overwritten by
365 ;; another Emacs server in the mean time, so it's not ours any more.
366 ;; (and (process-contact proc :server)
367 ;; (eq (process-status proc) 'closed)
368 ;; (ignore-errors (delete-file (process-get proc :server-file))))
9002956f
KL
369 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
370 (server-delete-client proc))
0c851d78 371
77134727
KL
372(defun server-handle-delete-frame (frame)
373 "Delete the client connection when the emacsclient frame is deleted."
9002956f 374 (let ((proc (frame-parameter frame 'client)))
e519a50b
KL
375 (when (and (frame-live-p frame)
376 proc
160f0817 377 ;; See if this is the last frame for this client.
d5381da2 378 (>= 1 (let ((frame-num 0))
aabf0cb9 379 (dolist (f (frame-list))
160f0817
KL
380 (when (eq proc (frame-parameter f 'client))
381 (setq frame-num (1+ frame-num))))
382 frame-num)))
9002956f 383 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
de93c791 384 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
9002956f 385
6ed8eeff 386(defun server-handle-suspend-tty (terminal)
9002956f 387 "Notify the emacsclient process to suspend itself when its tty device is suspended."
6ed8eeff
KL
388 (dolist (proc (server-clients-with 'terminal terminal))
389 (server-log (format "server-handle-suspend-tty, terminal %s" terminal) proc)
6d3a46f7 390 (condition-case err
6afdd335 391 (server-send-string proc "-suspend \n")
6d3a46f7 392 (file-error (condition-case nil (server-delete-client proc) (error nil))))))
44a56b29 393
0c851d78 394(defun server-unquote-arg (arg)
6afdd335
KL
395 "Remove &-quotation from ARG.
396See `server-quote-arg' and `server-process-filter'."
0c851d78
SM
397 (replace-regexp-in-string
398 "&." (lambda (s)
399 (case (aref s 1)
400 (?& "&")
401 (?- "-")
402 (?n "\n")
403 (t " ")))
404 arg t t))
9ae0f972 405
0b0d3e0b 406(defun server-quote-arg (arg)
9002956f 407 "In ARG, insert a & before each &, each space, each newline, and -.
0b0d3e0b 408Change spaces to underscores, too, so that the return value never
6afdd335
KL
409contains a space.
410
411See `server-unquote-arg' and `server-process-filter'."
0b0d3e0b
KL
412 (replace-regexp-in-string
413 "[-&\n ]" (lambda (s)
414 (case (aref s 0)
415 (?& "&&")
416 (?- "&-")
417 (?\n "&n")
418 (?\s "&_")))
419 arg t t))
420
6afdd335
KL
421(defun server-send-string (proc string)
422 "A wrapper around `proc-send-string' for logging."
423 (server-log (concat "Sent " string) proc)
424 (process-send-string proc string))
425
724629d2
SM
426(defun server-ensure-safe-dir (dir)
427 "Make sure DIR is a directory with no race-condition issues.
428Creates the directory if necessary and makes sure:
429- there's no symlink involved
430- it's owned by us
431- it's not readable/writable by anybody else."
432 (setq dir (directory-file-name dir))
433 (let ((attrs (file-attributes dir)))
434 (unless attrs
337e3c70 435 (letf (((default-file-modes) ?\700)) (make-directory dir t))
724629d2
SM
436 (setq attrs (file-attributes dir)))
437 ;; Check that it's safe for use.
da6657b7 438 (unless (and (eq t (car attrs)) (eql (nth 2 attrs) (user-uid))
337e3c70
JB
439 (or (eq system-type 'windows-nt)
440 (zerop (logand ?\077 (file-modes dir)))))
724629d2
SM
441 (error "The directory %s is unsafe" dir))))
442
7229064d 443;;;###autoload
9ae0f972 444(defun server-start (&optional leave-dead)
445 "Allow this Emacs process to be a server for client processes.
446This starts a server communications subprocess through which
6d3a46f7
KL
447client \"editors\" can send your editing commands to this Emacs
448job. To use the server, set up the program `emacsclient' in the
9ae0f972 449Emacs distribution as your standard \"editor\".
450
6d3a46f7
KL
451Prefix arg LEAVE-DEAD means just kill any existing server
452communications subprocess."
9ae0f972 453 (interactive "P")
d6b4b3cf
KL
454 (when (or
455 (not server-clients)
456 (yes-or-no-p
457 "The current server still has clients; delete them? "))
458 ;; It is safe to get the user id now.
459 (setq server-socket-dir (or server-socket-dir
460 (format "/tmp/emacs%d" (user-uid))))
974b73e8
KL
461 (when server-process
462 ;; kill it dead!
463 (ignore-errors (delete-process server-process)))
d6b4b3cf
KL
464 ;; Delete the socket files made by previous server invocations.
465 (condition-case ()
466 (delete-file (expand-file-name server-name server-socket-dir))
467 (error nil))
468 ;; If this Emacs already had a server, clear out associated status.
469 (while server-clients
470 (server-delete-client (car server-clients)))
9f97e26d 471 ;; Now any previous server is properly stopped.
d6b4b3cf
KL
472 (if leave-dead
473 (progn
474 (server-log (message "Server stopped"))
475 (setq server-process nil))
974b73e8
KL
476 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
477 (server-file (expand-file-name server-name server-dir)))
478 ;; Make sure there is a safe directory in which to place the socket.
479 (server-ensure-safe-dir server-dir)
480 ;; Remove any leftover socket or authentication file.
481 (ignore-errors (delete-file server-file))
482 (when server-process
483 (server-log (message "Restarting server")))
484 (letf (((default-file-modes) ?\700))
485 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
486 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
487 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
488 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
489 (setq server-process
490 (apply #'make-network-process
491 :name server-name
492 :server t
493 :noquery t
494 :sentinel 'server-sentinel
495 :filter 'server-process-filter
496 ;; We must receive file names without being decoded.
497 ;; Those are decoded by server-process-filter according
498 ;; to file-name-coding-system.
499 :coding 'raw-text
500 ;; The rest of the args depends on the kind of socket used.
501 (if server-use-tcp
502 (list :family nil
503 :service t
504 :host (or server-host 'local)
505 :plist '(:authenticated nil))
506 (list :family 'local
507 :service server-file
508 :plist '(:authenticated t)))))
509 (unless server-process (error "Could not start server process"))
510 (when server-use-tcp
511 (let ((auth-key
512 (loop
513 ;; The auth key is a 64-byte string of random chars in the
514 ;; range `!'..`~'.
515 for i below 64
516 collect (+ 33 (random 94)) into auth
517 finally return (concat auth))))
518 (process-put server-process :auth-key auth-key)
519 (with-temp-file server-file
520 (set-buffer-multibyte nil)
521 (setq buffer-file-coding-system 'no-conversion)
522 (insert (format-network-address
523 (process-contact server-process :local))
524 " " (int-to-string (emacs-pid))
525 "\n" auth-key)))))))))
33186f32
DL
526
527;;;###autoload
528(define-minor-mode server-mode
529 "Toggle Server mode.
530With ARG, turn Server mode on if ARG is positive, off otherwise.
531Server mode runs a process that accepts commands from the
532`emacsclient' program. See `server-start' and Info node `Emacs server'."
533 :global t
534 :group 'server
bf247b6e 535 :version "22.1"
33186f32
DL
536 ;; Fixme: Should this check for an existing server socket and do
537 ;; nothing if there is one (for multiple Emacs sessions)?
538 (server-start (not server-mode)))
9ae0f972 539\f
337e3c70 540(defun* server-process-filter (proc string)
33186f32 541 "Process a request from the server to edit some files.
6afdd335
KL
542PROC is the server process. STRING consists of a sequence of
543commands prefixed by a dash. Some commands have arguments; these
544are &-quoted and need to be decoded by `server-unquote-arg'. The
545filter parses and executes these commands.
546
547To illustrate the protocol, here is an example command that
548emacsclient sends to create a new X frame (note that the whole
549sequence is sent on a single line):
550
551 -version 21.3.50 xterm
552 -env HOME /home/lorentey
553 -env DISPLAY :0.0
554 ... lots of other -env commands
555 -display :0.0
556 -window-system
557
558The server normally sends back the single command `-good-version'
559as a response.
560
561The following commands are accepted by the server:
562
974b73e8
KL
563`-auth AUTH-STRING'
564 Authenticate the client using the secret authentication string
565 AUTH_STRING.
566
6afdd335
KL
567`-version CLIENT-VERSION'
568 Check version numbers between server and client, and signal an
569 error if there is a mismatch. The server replies with
570 `-good-version' to confirm the match.
571
59e085e0 572`-env NAME=VALUE'
6afdd335
KL
573 An environment variable on the client side.
574
2828d5f9
KL
575`-dir DIRNAME'
576 The current working directory of the client process.
577
92071250
KL
578`-current-frame'
579 Forbid the creation of new frames.
580
6afdd335
KL
581`-nowait'
582 Request that the next frame created should not be
583 associated with this client.
584
585`-display DISPLAY'
586 Set the display name to open X frames on.
587
588`-position LINE[:COLUMN]'
589 Go to the given line and column number
590 in the next file opened.
591
592`-file FILENAME'
593 Load the given file in the current frame.
594
595`-eval EXPR'
596 Evaluate EXPR as a Lisp expression and return the
597 result in -print commands.
598
599`-window-system'
600 Open a new X frame.
601
602`-tty DEVICENAME TYPE'
603 Open a new tty frame at the client.
604
6afdd335
KL
605`-suspend'
606 Suspend this tty frame. The client sends this string in
607 response to SIGTSTP and SIGTTOU. The server must cease all I/O
608 on this tty until it gets a -resume command.
609
2828d5f9
KL
610`-resume'
611 Resume this tty frame. The client sends this string when it
612 gets the SIGCONT signal and it is the foreground process on its
613 controlling tty.
614
6afdd335
KL
615`-ignore COMMENT'
616 Do nothing, but put the comment in the server
617 log. Useful for debugging.
618
619
620The following commands are accepted by the client:
621
622`-good-version'
623 Signals a version match between the client and the server.
624
625`-emacs-pid PID'
626 Describes the process id of the Emacs process;
627 used to forward window change signals to it.
628
629`-window-system-unsupported'
630 Signals that the server does not
631 support creating X frames; the client must try again with a tty
632 frame.
633
634`-print STRING'
635 Print STRING on stdout. Used to send values
636 returned by -eval.
637
638`-error DESCRIPTION'
639 Signal an error (but continue processing).
640
641`-suspend'
642 Suspend this terminal, i.e., stop the client process. Sent
643 when the user presses C-z."
644 (server-log (concat "Received " string) proc)
337e3c70
JB
645 ;; First things first: let's check the authentication
646 (unless (process-get proc :authenticated)
647 (if (and (string-match "-auth \\(.*?\\)\n" string)
974b73e8
KL
648 (equal (match-string 1 string) (process-get proc :auth-key)))
649 (progn
650 (setq string (substring string (match-end 0)))
651 (process-put proc :authenticated t)
652 (server-log "Authentication successful" proc))
337e3c70 653 (server-log "Authentication failed" proc)
974b73e8
KL
654 (server-send-string
655 proc (concat "-error " (server-quote-arg "Authentication failed")))
337e3c70
JB
656 (delete-process proc)
657 ;; We return immediately
658 (return-from server-process-filter)))
ff348fba
SM
659 (when (> (recursion-depth) 0)
660 ;; We're inside a minibuffer already, so if the emacs-client is trying
661 ;; to open a frame on a new display, we might end up with an unusable
662 ;; frame because input from that display will be blocked (until exiting
663 ;; the minibuffer). Better exit this minibuffer right away.
664 ;; Similarly with recursive-edits such as the splash screen.
665 (process-put proc :previous-string string)
666 (run-with-timer 0 nil (lexical-let ((proc proc))
974b73e8 667 (lambda () (server-process-filter proc ""))))
ff348fba 668 (top-level))
3f7ef08e
SM
669 (let ((prev (process-get proc 'previous-string)))
670 (when prev
671 (setq string (concat prev string))
672 (process-put proc 'previous-string nil)))
a9298135 673 (condition-case err
0b0d3e0b 674 (progn
9002956f 675 (server-add-client proc)
0b0d3e0b
KL
676 ;; If the input is multiple lines,
677 ;; process each line individually.
678 (while (string-match "\n" string)
679 (let ((request (substring string 0 (match-beginning 0)))
680 (coding-system (and default-enable-multibyte-characters
681 (or file-name-coding-system
682 default-file-name-coding-system)))
9002956f 683 (client (server-client proc))
92071250 684 current-frame
9002956f
KL
685 nowait ; t if emacsclient does not want to wait for us.
686 frame ; The frame that was opened for the client (if any).
59e085e0 687 display ; Open the frame on this display.
0b0d3e0b 688 dontkill ; t if the client should not be killed.
59e085e0 689 env
2828d5f9 690 dir
0b0d3e0b
KL
691 (files nil)
692 (lineno 1)
693 (columnno 0))
694 ;; Remove this line from STRING.
695 (setq string (substring string (match-end 0)))
9002956f 696 (while (string-match " *[^ ]* " request)
0b0d3e0b
KL
697 (let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
698 (setq request (substring request (match-end 0)))
699 (cond
9002956f
KL
700 ;; -version CLIENT-VERSION:
701 ;; Check version numbers, signal an error if there is a mismatch.
702 ((and (equal "-version" arg)
703 (string-match "\\([0-9.]+\\) " request))
0b0d3e0b 704 (let* ((client-version (match-string 1 request))
9002956f
KL
705 (truncated-emacs-version
706 (substring emacs-version 0 (length client-version))))
0b0d3e0b
KL
707 (setq request (substring request (match-end 0)))
708 (if (equal client-version truncated-emacs-version)
709 (progn
6afdd335 710 (server-send-string proc "-good-version \n")
9002956f
KL
711 (server-client-set client 'version client-version))
712 (error (concat "Version mismatch: Emacs is "
713 truncated-emacs-version
714 ", emacsclient is " client-version)))))
0b0d3e0b 715
9002956f 716 ;; -nowait: Emacsclient won't wait for a result.
0b0d3e0b
KL
717 ((equal "-nowait" arg) (setq nowait t))
718
92071250
KL
719 ;; -current-frame: Don't create frames.
720 ((equal "-current-frame" arg) (setq current-frame t))
721
9002956f 722 ;; -display DISPLAY:
59e085e0 723 ;; Open X frames on the given display instead of the default.
0b0d3e0b
KL
724 ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
725 (setq display (match-string 1 request)
726 request (substring request (match-end 0))))
727
9002956f 728 ;; -window-system: Open a new X frame.
0b0d3e0b 729 ((equal "-window-system" arg)
9002956f 730 (unless (server-client-get client 'version)
a9298135 731 (error "Protocol error; make sure to use the correct version of emacsclient"))
92071250
KL
732 (unless current-frame
733 (if (fboundp 'x-create-frame)
734 (let ((params (if nowait
62c5106c
KL
735 ;; Flag frame as client-created, but use a dummy client.
736 ;; This will prevent the frame from being deleted when
737 ;; emacsclient quits while also preventing
6ed8eeff 738 ;; `server-save-buffers-kill-terminal' from unexpectedly
62c5106c 739 ;; killing emacs on that frame.
da8e8fc1
KL
740 (list (cons 'client 'nowait) (cons 'environment env))
741 (list (cons 'client proc) (cons 'environment env)))))
92071250
KL
742 (setq frame (make-frame-on-display
743 (or display
f105f403 744 (frame-parameter nil 'display)
92071250
KL
745 (getenv "DISPLAY")
746 (error "Please specify display"))
747 params))
748 (server-log (format "%s created" frame) proc)
749 ;; XXX We need to ensure the parameters are
750 ;; really set because Emacs forgets unhandled
751 ;; initialization parameters for X frames at
752 ;; the moment.
753 (modify-frame-parameters frame params)
754 (select-frame frame)
755 (server-client-set client 'frame frame)
6ed8eeff 756 (server-client-set client 'terminal (frame-terminal frame))
8573f9ad
KL
757
758 ;; Display *scratch* by default.
759 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
2828d5f9 760 (if dir (setq default-directory dir))
8573f9ad 761
92071250
KL
762 (setq dontkill t))
763 ;; This emacs does not support X.
764 (server-log "Window system unsupported" proc)
765 (server-send-string proc "-window-system-unsupported \n")
766 (setq dontkill t))))
9002956f
KL
767
768 ;; -resume: Resume a suspended tty frame.
0b0d3e0b 769 ((equal "-resume" arg)
6ed8eeff 770 (let ((terminal (server-client-get client 'terminal)))
0b0d3e0b 771 (setq dontkill t)
6ed8eeff
KL
772 (when (eq (terminal-live-p terminal) t)
773 (resume-tty terminal))))
0b0d3e0b 774
9002956f
KL
775 ;; -suspend: Suspend the client's frame. (In case we
776 ;; get out of sync, and a C-z sends a SIGTSTP to
777 ;; emacsclient.)
0b0d3e0b 778 ((equal "-suspend" arg)
6ed8eeff 779 (let ((terminal (server-client-get client 'terminal)))
0b0d3e0b 780 (setq dontkill t)
6ed8eeff
KL
781 (when (eq (terminal-live-p terminal) t)
782 (suspend-tty terminal))))
0b0d3e0b 783
9002956f
KL
784 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
785 ;; (The given comment appears in the server log.)
0b0d3e0b
KL
786 ((and (equal "-ignore" arg) (string-match "\\([^ ]*\\) " request))
787 (setq dontkill t
788 request (substring request (match-end 0))))
789
9002956f 790 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
0b0d3e0b
KL
791 ((and (equal "-tty" arg) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request))
792 (let ((tty (server-unquote-arg (match-string 1 request)))
793 (type (server-unquote-arg (match-string 2 request))))
794 (setq request (substring request (match-end 0)))
9002956f
KL
795 (unless (server-client-get client 'version)
796 (error "Protocol error; make sure you use the correct version of emacsclient"))
92071250 797 (unless current-frame
59e085e0
KL
798 (server-with-environment env
799 '("LANG" "LC_CTYPE" "LC_ALL"
800 ;; For tgetent(3); list according to ncurses(3).
801 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
802 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
803 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
804 "TERMINFO_DIRS" "TERMPATH")
92071250
KL
805 (setq frame (make-frame-on-tty tty type
806 ;; Ignore nowait here; we always need to clean
807 ;; up opened ttys when the client dies.
da8e8fc1
KL
808 `((client . ,proc)
809 (environment . ,env)))))
92071250
KL
810 (select-frame frame)
811 (server-client-set client 'frame frame)
6ed8eeff
KL
812 (server-client-set client 'tty (terminal-name frame))
813 (server-client-set client 'terminal (frame-terminal frame))
92071250 814
8573f9ad
KL
815 ;; Display *scratch* by default.
816 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
2828d5f9 817 (if dir (setq default-directory dir))
8573f9ad 818
92071250
KL
819 ;; Reply with our pid.
820 (server-send-string proc (concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
821 (setq dontkill t))))
9002956f
KL
822
823 ;; -position LINE: Go to the given line in the next file.
0b0d3e0b 824 ((and (equal "-position" arg) (string-match "\\(\\+[0-9]+\\) " request))
80a426c2
KL
825 (setq lineno (string-to-number (substring (match-string 1 request) 1))
826 request (substring request (match-end 0))))
0b0d3e0b 827
9002956f 828 ;; -position LINE:COLUMN: Set point to the given position in the next file.
0b0d3e0b 829 ((and (equal "-position" arg) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request))
b4bb3cbc
KL
830 (setq lineno (string-to-number (match-string 1 request))
831 columnno (string-to-number (match-string 2 request))
4e15f072 832 request (substring request (match-end 0))))
0b0d3e0b 833
9002956f 834 ;; -file FILENAME: Load the given file.
0b0d3e0b
KL
835 ((and (equal "-file" arg) (string-match "\\([^ ]+\\) " request))
836 (let ((file (server-unquote-arg (match-string 1 request))))
837 (setq request (substring request (match-end 0)))
838 (if coding-system
839 (setq file (decode-coding-string file coding-system)))
840 (setq file (command-line-normalize-file-name file))
80a426c2
KL
841 (push (list file lineno columnno) files)
842 (server-log (format "New file: %s (%d:%d)" file lineno columnno) proc))
0b0d3e0b
KL
843 (setq lineno 1
844 columnno 0))
845
9002956f 846 ;; -eval EXPR: Evaluate a Lisp expression.
0b0d3e0b
KL
847 ((and (equal "-eval" arg) (string-match "\\([^ ]+\\) " request))
848 (let ((expr (server-unquote-arg (match-string 1 request))))
849 (setq request (substring request (match-end 0)))
850 (if coding-system
851 (setq expr (decode-coding-string expr coding-system)))
852 (let ((v (eval (car (read-from-string expr)))))
9002956f 853 (when (and (not frame) v)
a9298135
KL
854 (with-temp-buffer
855 (let ((standard-output (current-buffer)))
856 (pp v)
6afdd335
KL
857 (server-send-string
858 proc (format "-print %s\n"
859 (server-quote-arg
860 (buffer-substring-no-properties (point-min)
861 (point-max)))))))))
0b0d3e0b
KL
862 (setq lineno 1
863 columnno 0)))
864
59e085e0
KL
865 ;; -env NAME=VALUE: An environment variable.
866 ((and (equal "-env" arg) (string-match "\\([^ ]+\\) " request))
867 (let ((var (server-unquote-arg (match-string 1 request))))
da8e8fc1 868 ;; XXX Variables should be encoded as in getenv/setenv.
9002956f 869 (setq request (substring request (match-end 0)))
59e085e0 870 (setq env (cons var env))))
9002956f 871
2828d5f9
KL
872 ;; -dir DIRNAME: The cwd of the emacsclient process.
873 ((and (equal "-dir" arg) (string-match "\\([^ ]+\\) " request))
874 (setq dir (server-unquote-arg (match-string 1 request)))
875 (setq request (substring request (match-end 0)))
876 (if coding-system
877 (setq dir (decode-coding-string dir coding-system)))
878 (setq dir (command-line-normalize-file-name dir)))
879
0b0d3e0b
KL
880 ;; Unknown command.
881 (t (error "Unknown command: %s" arg)))))
882
c5b0a355
KL
883 (let (buffers)
884 (when files
885 (run-hooks 'pre-command-hook)
886 (setq buffers (server-visit-files files client nowait))
887 (run-hooks 'post-command-hook))
888
fe74bf60
KL
889 (when frame
890 (with-selected-frame frame
b3e6f69c 891 (display-startup-echo-area-message)
fe74bf60 892 (unless inhibit-splash-screen
b3e6f69c
KL
893 (condition-case err
894 ;; This looks scary because `fancy-splash-screens'
895 ;; will call `recursive-edit' from a process filter.
896 ;; However, that should be safe to do now.
12b6af5c 897 (display-splash-screen t)
b3e6f69c
KL
898 ;; `recursive-edit' will throw an error if Emacs is
899 ;; already doing a recursive edit elsewhere. Catch it
900 ;; here so that we can finish normally.
901 (error nil)))))
c2844302 902
c5b0a355
KL
903 ;; Delete the client if necessary.
904 (cond
905 (nowait
906 ;; Client requested nowait; return immediately.
907 (server-log "Close nowait client" proc)
908 (server-delete-client proc))
909 ((and (not dontkill) (null buffers))
910 ;; This client is empty; get rid of it immediately.
911 (server-log "Close empty client" proc)
912 (server-delete-client proc)))
913 (cond
914 ((or isearch-mode (minibufferp))
915 nil)
916 ((and frame (null buffers))
0ff21b4e
KL
917 (message "%s" (substitute-command-keys
918 "When done with this frame, type \\[delete-frame]")))
c5b0a355
KL
919 ((not (null buffers))
920 (server-switch-buffer (car buffers))
921 (run-hooks 'server-switch-hook)
922 (unless nowait
0ff21b4e
KL
923 (message "%s" (substitute-command-keys
924 "When done with a buffer, type \\[server-edit]"))))))))
0b0d3e0b 925
a9298135
KL
926 ;; Save for later any partial line that remains.
927 (when (> (length string) 0)
928 (process-put proc 'previous-string string)))
929 ;; condition-case
930 (error (ignore-errors
6afdd335 931 (server-send-string
0b0d3e0b 932 proc (concat "-error " (server-quote-arg (error-message-string err))))
a9298135
KL
933 (setq string "")
934 (server-log (error-message-string err) proc)
935 (delete-process proc)))))
9ae0f972 936
6b98185f 937(defun server-goto-line-column (file-line-col)
6d3a46f7
KL
938 "Move point to the position indicated in FILE-LINE-COL.
939FILE-LINE-COL should be a three-element list as described in
940`server-visit-files'."
6b98185f
RS
941 (goto-line (nth 1 file-line-col))
942 (let ((column-number (nth 2 file-line-col)))
943 (if (> column-number 0)
944 (move-to-column (1- column-number)))))
945
dfa35e6b 946(defun server-visit-files (files client &optional nowait)
c5b0a355 947 "Find FILES and return a list of buffers created.
8c493570 948FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
6d3a46f7 949CLIENT is the client that requested this operation.
dfa35e6b
RS
950NOWAIT non-nil means this client is not waiting for the results,
951so don't mark these buffers specially, just visit them normally."
e82e73c2 952 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
44a56b29 953 (let ((last-nonmenu-event t) client-record)
3a0ce849
RS
954 ;; Restore the current buffer afterward, but not using save-excursion,
955 ;; because we don't want to save point in this buffer
956 ;; if it happens to be one of those specified by the server.
44a56b29
SM
957 (save-current-buffer
958 (dolist (file files)
959 ;; If there is an existing buffer modified or the file is
960 ;; modified, revert it. If there is an existing buffer with
961 ;; deleted file, offer to write it.
cd7320d4 962 (let* ((minibuffer-auto-raise (or server-raise-frame
974b73e8 963 minibuffer-auto-raise))
c2d0d432 964 (filen (car file))
44a56b29 965 (obuf (get-file-buffer filen)))
c398358a 966 (add-to-history 'file-name-history filen)
44a56b29
SM
967 (if (and obuf (set-buffer obuf))
968 (progn
969 (cond ((file-exists-p filen)
95eefb35 970 (when (not (verify-visited-file-modtime obuf))
974b73e8 971 (revert-buffer t nil)))
44a56b29 972 (t
95eefb35 973 (when (y-or-n-p
974b73e8
KL
974 (concat "File no longer exists: " filen
975 ", write buffer to file? "))
976 (write-file filen))))
5f3c1a63
KL
977 (unless server-buffer-clients
978 (setq server-existing-buffer t))
44a56b29
SM
979 (server-goto-line-column file))
980 (set-buffer (find-file-noselect filen))
981 (server-goto-line-column file)
982 (run-hooks 'server-visit-hook)))
983 (unless nowait
984 ;; When the buffer is killed, inform the clients.
985 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
c5b0a355
KL
986 (push (car client) server-buffer-clients))
987 (push (current-buffer) client-record)))
988 (unless nowait
989 (server-client-set
990 client 'buffers
991 (nconc (server-client-get client 'buffers) client-record)))
992 client-record))
9ae0f972 993\f
b392bac9 994(defun server-buffer-done (buffer &optional for-killing)
9ae0f972 995 "Mark BUFFER as \"done\" for its client(s).
9184aafb
RS
996This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
997NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
8b3e840e
SM
998or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
999a temp file).
1000FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
0c851d78 1001 (let ((next-buffer nil)
9002956f
KL
1002 (killed nil))
1003 (dolist (client server-clients)
1004 (let ((buffers (server-client-get client 'buffers)))
8b3e840e 1005 (or next-buffer
9002956f
KL
1006 (setq next-buffer (nth 1 (memq buffer buffers))))
1007 (when buffers ; Ignore bufferless clients.
1008 (setq buffers (delq buffer buffers))
1009 ;; Delete all dead buffers from CLIENT.
1010 (dolist (b buffers)
1011 (and (bufferp b)
1012 (not (buffer-live-p b))
1013 (setq buffers (delq b buffers))))
1014 (server-client-set client 'buffers buffers)
1015 ;; If client now has no pending buffers,
1016 ;; tell it that it is done, and forget it entirely.
1017 (unless buffers
1018 (server-log "Close" client)
1019 (server-delete-client client)))))
337e3c70
JB
1020 (when (and (bufferp buffer) (buffer-name buffer))
1021 ;; We may or may not kill this buffer;
1022 ;; if we do, do not call server-buffer-done recursively
1023 ;; from kill-buffer-hook.
1024 (let ((server-kill-buffer-running t))
1025 (with-current-buffer buffer
1026 (setq server-buffer-clients nil)
1027 (run-hooks 'server-done-hook))
1028 ;; Notice whether server-done-hook killed the buffer.
1029 (if (null (buffer-name buffer))
1030 (setq killed t)
1031 ;; Don't bother killing or burying the buffer
1032 ;; when we are called from kill-buffer.
1033 (unless for-killing
1034 (when (and (not killed)
1035 server-kill-new-buffers
1036 (with-current-buffer buffer
1037 (not server-existing-buffer)))
599f9a5c 1038 (setq killed t)
337e3c70
JB
1039 (bury-buffer buffer)
1040 (kill-buffer buffer))
1041 (unless killed
1042 (if (server-temp-file-p buffer)
1043 (progn
1044 (kill-buffer buffer)
1045 (setq killed t))
1046 (bury-buffer buffer)))))))
9184aafb 1047 (list next-buffer killed)))
9ae0f972 1048
408784a7 1049(defun server-temp-file-p (&optional buffer)
9ae0f972 1050 "Return non-nil if BUFFER contains a file considered temporary.
1051These are files whose names suggest they are repeatedly
1052reused to pass information to another program.
1053
1054The variable `server-temp-file-regexp' controls which filenames
1055are considered temporary."
1056 (and (buffer-file-name buffer)
1057 (string-match server-temp-file-regexp (buffer-file-name buffer))))
1058
1059(defun server-done ()
cc9875f9 1060 "Offer to save current buffer, mark it as \"done\" for clients.
ed9ae328
RS
1061This kills or buries the buffer, then returns a list
1062of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1063as a suggestion for what to select next, or nil.
1064KILLED is t if we killed BUFFER, which happens if it was created
1065specifically for the clients and did not exist before their request for it."
408784a7
SM
1066 (when server-buffer-clients
1067 (if (server-temp-file-p)
1068 ;; For a temp file, save, and do make a non-numeric backup
1069 ;; (unless make-backup-files is nil).
1070 (let ((version-control nil)
1071 (buffer-backed-up nil))
1072 (save-buffer))
337e3c70
JB
1073 (when (and (buffer-modified-p)
1074 buffer-file-name
1075 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1076 (save-buffer)))
408784a7 1077 (server-buffer-done (current-buffer))))
faf931a8 1078
71207de2
RS
1079;; Ask before killing a server buffer.
1080;; It was suggested to release its client instead,
1081;; but I think that is dangerous--the client would proceed
1082;; using whatever is on disk in that file. -- rms.
03d78665 1083(defun server-kill-buffer-query-function ()
9002956f 1084 "Ask before killing a server buffer."
03d78665 1085 (or (not server-buffer-clients)
114a8b8c
KL
1086 (let ((res t))
1087 (dolist (proc server-buffer-clients res)
9002956f
KL
1088 (let ((client (server-client proc)))
1089 (when (and client (eq (process-status proc) 'open))
1090 (setq res nil)))))
03d78665
RS
1091 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1092 (buffer-name (current-buffer))))))
1093
03d78665 1094(defun server-kill-emacs-query-function ()
7540c1e0 1095 "Ask before exiting Emacs it has live clients."
9002956f
KL
1096 (or (not server-clients)
1097 (let (live-client)
1098 (dolist (client server-clients live-client)
974b73e8
KL
1099 (when (memq t (mapcar 'buffer-live-p (server-client-get
1100 client 'buffers)))
1101 (setq live-client t))))
9002956f 1102 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
b392bac9 1103
fb873cfc 1104(defvar server-kill-buffer-running nil
599f9a5c 1105 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
fb873cfc 1106
b392bac9 1107(defun server-kill-buffer ()
6d3a46f7
KL
1108 "Remove the current buffer from its clients' buffer list.
1109Designed to be added to `kill-buffer-hook'."
fb873cfc
RS
1110 ;; Prevent infinite recursion if user has made server-done-hook
1111 ;; call kill-buffer.
1112 (or server-kill-buffer-running
599f9a5c
RS
1113 (and server-buffer-clients
1114 (let ((server-kill-buffer-running t))
1115 (when server-process
1116 (server-buffer-done (current-buffer) t))))))
9ae0f972 1117\f
1118(defun server-edit (&optional arg)
1119 "Switch to next server editing buffer; say \"Done\" for current buffer.
1120If a server buffer is current, it is marked \"done\" and optionally saved.
ed9ae328 1121The buffer is also killed if it did not exist before the clients asked for it.
9ae0f972 1122When all of a client's buffers are marked as \"done\", the client is notified.
1123
1124Temporary files such as MH <draft> files are always saved and backed up,
991298c3
RS
1125no questions asked. (The variable `make-backup-files', if nil, still
1126inhibits a backup; you can set it locally in a particular buffer to
1127prevent a backup for it.) The variable `server-temp-file-regexp' controls
9ae0f972 1128which filenames are considered temporary.
1129
64f51134 1130If invoked with a prefix argument, or if there is no server process running,
9ae0f972 1131starts server process and that is all. Invoked by \\[server-edit]."
9ae0f972 1132 (interactive "P")
6b519504 1133 (cond
95eefb35
JB
1134 ((or arg
1135 (not server-process)
1136 (memq (process-status server-process) '(signal exit)))
1137 (server-mode 1))
1138 (server-clients (apply 'server-switch-buffer (server-done)))
1139 (t (message "No server editing buffers exist"))))
9ae0f972 1140
98a4349c 1141(defun server-switch-buffer (&optional next-buffer killed-one)
9ae0f972 1142 "Switch to another buffer, preferably one that has a client.
6d3a46f7
KL
1143Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1144
1145KILLED-ONE is t in a recursive call if we have already killed one
1146temp-file server buffer. This means we should avoid the final
1147\"switch to some other buffer\" since we've already effectively
1148done that."
ca0c7250 1149 (if (null next-buffer)
9002956f
KL
1150 (progn
1151 (let ((rest server-clients))
1152 (while (and rest (not next-buffer))
1153 (let ((client (car rest)))
1154 ;; Only look at frameless clients.
1155 (when (not (server-client-get client 'frame))
1156 (setq next-buffer (car (server-client-get client 'buffers))))
1157 (setq rest (cdr rest)))))
1158 (and next-buffer (server-switch-buffer next-buffer killed-one))
1159 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1160 ;; (switch-to-buffer (other-buffer))
90ee5627 1161 (message "No server buffers remain to edit")))
9002956f 1162 (if (not (buffer-live-p next-buffer))
ca0c7250 1163 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
9ae0f972 1164 ;; and try the next surviving server buffer.
ca0c7250
SM
1165 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1166 ;; OK, we know next-buffer is live, let's display and select it.
408784a7
SM
1167 (if (functionp server-window)
1168 (funcall server-window next-buffer)
1169 (let ((win (get-buffer-window next-buffer 0)))
1170 (if (and win (not server-window))
1171 ;; The buffer is already displayed: just reuse the window.
90caccca
JB
1172 (progn
1173 (select-window win)
1174 (set-buffer next-buffer))
408784a7
SM
1175 ;; Otherwise, let's find an appropriate window.
1176 (cond ((and (windowp server-window)
1177 (window-live-p server-window))
1178 (select-window server-window))
1179 ((framep server-window)
337e3c70
JB
1180 (unless (frame-live-p server-window)
1181 (setq server-window (make-frame)))
408784a7 1182 (select-window (frame-selected-window server-window))))
337e3c70
JB
1183 (when (window-minibuffer-p (selected-window))
1184 (select-window (next-window nil 'nomini 0)))
408784a7
SM
1185 ;; Move to a non-dedicated window, if we have one.
1186 (when (window-dedicated-p (selected-window))
1187 (select-window
1188 (get-window-with-predicate
1189 (lambda (w)
1190 (and (not (window-dedicated-p w))
6ed8eeff
KL
1191 (equal (frame-terminal (window-frame w))
1192 (frame-terminal (selected-frame)))))
408784a7
SM
1193 'nomini 'visible (selected-window))))
1194 (condition-case nil
1195 (switch-to-buffer next-buffer)
1196 ;; After all the above, we might still have ended up with
1197 ;; a minibuffer/dedicated-window (if there's no other).
90caccca
JB
1198 (error (pop-to-buffer next-buffer)))))))
1199 (when server-raise-frame
1200 (select-frame-set-input-focus (window-frame (selected-window))))))
9ae0f972 1201
59e085e0 1202;;;###autoload
6ed8eeff 1203(defun server-save-buffers-kill-terminal (proc &optional arg)
59e085e0 1204 "Offer to save each buffer, then kill PROC.
b4ca0271 1205
7540c1e0
KL
1206With prefix arg, silently save all file-visiting buffers, then kill.
1207
1208If emacsclient was started with a list of filenames to edit, then
1209only these files will be asked to be saved."
59e085e0
KL
1210 (let ((buffers (server-client-get proc 'buffers)))
1211 ;; If client is bufferless, emulate a normal Emacs session
1212 ;; exit and offer to save all buffers. Otherwise, offer to
1213 ;; save only the buffers belonging to the client.
1214 (save-some-buffers arg
1215 (if buffers
1216 (lambda () (memq (current-buffer) buffers))
1217 t))
1218 (server-delete-client proc)))
b4ca0271 1219
772c5eb7 1220(define-key ctl-x-map "#" 'server-edit)
df4e8a11
DL
1221
1222(defun server-unload-hook ()
6d3a46f7 1223 "Unload the server library."
2e8457a0 1224 (server-mode -1)
9002956f
KL
1225 (remove-hook 'suspend-tty-functions 'server-handle-suspend-tty)
1226 (remove-hook 'delete-frame-functions 'server-handle-delete-frame)
df4e8a11
DL
1227 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
1228 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
1229 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
3bb38bc2 1230
2e8457a0 1231(add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
3bb38bc2 1232(add-hook 'server-unload-hook 'server-unload-hook)
16c15321
RM
1233\f
1234(provide 'server)
c88ab9ce 1235
2e8457a0 1236;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
c88ab9ce 1237;;; server.el ends here