Use with-selected-frame.
[bpt/emacs.git] / lisp / server.el
CommitLineData
55535639 1;;; server.el --- Lisp code for GNU Emacs running as server process
c88ab9ce 2
92c7831b 3;; Copyright (C) 1986,87,92,94,95,96,97,98,99,2000,01,02,03,2004
0f5f7c3e 4;; 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
EN
26;; along with GNU Emacs; see the file COPYING. If not, write to the
27;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
28;; Boston, MA 02111-1307, 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
b578f267 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
ab1c7f35 86(defcustom server-visit-hook nil
0c851d78 87 "*Hook run when visiting a file for the Emacs server."
ab1c7f35 88 :group 'server
0c851d78 89 :type 'hook)
ab1c7f35
RS
90
91(defcustom server-switch-hook nil
0c851d78 92 "*Hook run when switching to a buffer for the Emacs server."
ab1c7f35 93 :group 'server
0c851d78 94 :type 'hook)
ab1c7f35
RS
95
96(defcustom server-done-hook nil
0c851d78 97 "*Hook run when done editing a buffer for the Emacs server."
ab1c7f35 98 :group 'server
0c851d78 99 :type 'hook)
f9b3ef88 100
64f51134
JPW
101(defvar server-process nil
102 "The current server process.")
9ae0f972 103
104(defvar server-clients nil
105 "List of current server clients.
9002956f
KL
106Each element is (PROC PROPERTIES...) where PROC is a process object,
107and PROPERTIES is an association list of client properties.")
0a125897 108
9ae0f972 109(defvar server-buffer-clients nil
b5a9911c 110 "List of client ids for clients requesting editing of current buffer.")
faf931a8 111(make-variable-buffer-local 'server-buffer-clients)
9ae0f972 112;; Changing major modes should not erase this local.
113(put 'server-buffer-clients 'permanent-local t)
114
33186f32
DL
115(defcustom server-window nil
116 "*Specification of the window to use for selecting Emacs server buffers.
ec40ed9f 117If nil, use the selected window.
408784a7 118If it is a function, it should take one argument (a buffer) and
33186f32
DL
119display and select it. A common value is `pop-to-buffer'.
120If it is a window, use that.
121If it is a frame, use the frame's selected window.
122
123It is not meaningful to set this to a specific frame or window with Custom.
124Only programs can do so."
125 :group 'server
126 :version "21.4"
127 :type '(choice (const :tag "Use selected window"
128 :match (lambda (widget value)
129 (not (functionp value)))
130 nil)
131 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
132 (function :tag "Other function")))
ec40ed9f 133
ab1c7f35 134(defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
33186f32
DL
135 "*Regexp matching names of temporary files.
136These are deleted and reused after each edit by the programs that
137invoke the Emacs server."
ab1c7f35
RS
138 :group 'server
139 :type 'regexp)
9ae0f972 140
c6a117f0
GM
141(defcustom server-kill-new-buffers t
142 "*Whether to kill buffers when done with them.
143If non-nil, kill a buffer unless it already existed before editing
64f51134 144it with Emacs server. If nil, kill only buffers as specified by
c6a117f0
GM
145`server-temp-file-regexp'.
146Please note that only buffers are killed that still have a client,
147i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
148this way."
149 :group 'server
150 :type 'boolean
151 :version "21.1")
152
9ae0f972 153(or (assq 'server-buffer-clients minor-mode-alist)
154 (setq minor-mode-alist (cons '(server-buffer-clients " Server") minor-mode-alist)))
155
c6a117f0 156(defvar server-existing-buffer nil
ca0c7250 157 "Non-nil means the buffer existed before the server was asked to visit it.
4dd04714 158This means that the server should not kill the buffer when you say you
ca0c7250 159are done with it in the server.")
c6a117f0
GM
160(make-variable-buffer-local 'server-existing-buffer)
161
03ae35cf
SM
162(defvar server-name "server")
163
164(defvar server-socket-dir
165 (format "/tmp/emacs%d" (user-uid)))
0c851d78 166
9002956f
KL
167(defun server-client (proc)
168 "Return the Emacs client corresponding to PROC.
169PROC must be a process object.
170The car of the result is PROC; the cdr is an association list.
171See `server-client-get' and `server-client-set'."
172 (assq proc server-clients))
173
174(defun server-client-get (client property)
175 "Get the value of PROPERTY in CLIENT.
176CLIENT may be a process object, or a client returned by `server-client'.
177Return nil if CLIENT has no such property."
178 (or (listp client) (setq client (server-client client)))
179 (cdr (assq property (cdr client))))
180
181(defun server-client-set (client property value)
182 "Set the PROPERTY to VALUE in CLIENT, and return VALUE.
183CLIENT may be a process object, or a client returned by `server-client'."
184 (let (p proc)
185 (if (listp client)
186 (setq proc (car client))
187 (setq proc client
188 client (server-client client)))
189 (setq p (assq property client))
190 (cond
191 (p (setcdr p value))
192 (client (setcdr client (cons (cons property value) (cdr client))))
193 (t (setq server-clients
194 `((,proc (,property . ,value)) . ,server-clients))))
195 value))
196
197(defun server-clients-with (property value)
198 "Return a list of clients with PROPERTY set to VALUE."
199 (let (result)
200 (dolist (client server-clients result)
201 (when (equal value (server-client-get client property))
202 (setq result (cons (car client) result))))))
203
204(defun server-add-client (proc)
205 "Create a client for process PROC, if it doesn't already have one.
206New clients have no properties."
207 (unless (server-client proc)
208 (setq server-clients (cons (cons proc nil)
209 server-clients))))
210
de93c791
KL
211(defun server-delete-client (client &optional noframe)
212 "Delete CLIENT, including its buffers, displays and frames.
213If NOFRAME is non-nil, let the frames live. (To be used from
214`delete-frame-functions'."
9002956f
KL
215 ;; Force a new lookup of client (prevents infinite recursion).
216 (setq client (server-client
217 (if (listp client) (car client) client)))
218 (let ((proc (car client))
219 (buffers (server-client-get client 'buffers)))
220 (when client
221 (setq server-clients (delq client server-clients))
222
223 (dolist (buf buffers)
6ed9e43a
KL
224 (when (buffer-live-p buf)
225 (with-current-buffer buf
226 ;; Remove PROC from the clients of each buffer.
227 (setq server-buffer-clients (delq proc server-buffer-clients))
228 ;; Kill the buffer if necessary.
229 (when (and (null server-buffer-clients)
230 (or (and server-kill-new-buffers
231 (not server-existing-buffer))
232 (server-temp-file-p)))
233 (kill-buffer (current-buffer))))))
9002956f
KL
234
235 ;; Delete the client's tty.
236 (let ((tty (server-client-get client 'tty)))
6ed9e43a
KL
237 (when (and tty (server-tty-live-p tty))
238 (delete-tty tty)))
9002956f
KL
239
240 ;; Delete the client's frames.
de93c791
KL
241 (unless noframe
242 (dolist (frame (frame-list))
243 (if (and (frame-live-p frame)
244 (equal (car client) (frame-parameter frame 'client)))
245 (delete-frame frame))))
9002956f
KL
246
247 ;; Delete the client's process.
248 (if (eq (process-status (car client)) 'open)
249 (delete-process (car client)))
250
251 (server-log "Deleted" proc))))
252
8b3e840e 253(defun server-log (string &optional client)
33186f32 254 "If a *server* buffer exists, write STRING to it for logging purposes."
9ae0f972 255 (if (get-buffer "*server*")
8b3e840e 256 (with-current-buffer "*server*"
9ae0f972 257 (goto-char (point-max))
8b3e840e 258 (insert (current-time-string)
9002956f
KL
259 (cond
260 ((null client) " ")
261 ((listp client) (format " %s: " (car client)))
262 (t (format " %s: " client)))
8b3e840e 263 string)
74c20cd3 264 (or (bolp) (newline)))))
9ae0f972 265
4d553a13
KL
266(defun server-tty-live-p (tty)
267 "Return non-nil if the tty device named TTY has a live frame."
268 (let (result)
269 (dolist (frame (frame-list) result)
270 (when (and (eq (frame-live-p frame) t)
271 (equal (frame-tty-name frame) tty))
272 (setq result t)))))
273
9ae0f972 274(defun server-sentinel (proc msg)
9002956f
KL
275 "The process sentinel for Emacs server connections."
276 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
277 (server-delete-client proc))
0c851d78 278
4d553a13 279(defun server-handle-delete-tty (tty)
77134727 280 "Delete the client connection when the emacsclient terminal device is closed."
9002956f
KL
281 (dolist (proc (server-clients-with 'tty tty))
282 (server-log (format "server-handle-delete-tty, tty %s" tty) proc)
283 (server-delete-client proc)))
0b0d3e0b 284
77134727
KL
285(defun server-handle-delete-frame (frame)
286 "Delete the client connection when the emacsclient frame is deleted."
9002956f 287 (let ((proc (frame-parameter frame 'client)))
6ed9e43a
KL
288 (when (and proc (window-system frame))
289 ;; (Closing a terminal frame must not trigger a delete;
290 ;; we must wait for delete-tty-after-functions.)
9002956f 291 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
de93c791 292 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
9002956f
KL
293
294(defun server-handle-suspend-tty (tty)
295 "Notify the emacsclient process to suspend itself when its tty device is suspended."
296 (dolist (proc (server-clients-with 'tty tty))
297 (server-log (format "server-handle-suspend-tty, tty %s" tty) proc)
298 (process-send-string proc "-suspend \n")))
77134727 299
44a56b29
SM
300(defun server-select-display (display)
301 ;; If the current frame is on `display' we're all set.
302 (unless (equal (frame-parameter (selected-frame) 'display) display)
303 ;; Otherwise, look for an existing frame there and select it.
304 (dolist (frame (frame-list))
305 (when (equal (frame-parameter frame 'display) display)
306 (select-frame frame)))
307 ;; If there's no frame on that display yet, create a dummy one
308 ;; and select it.
309 (unless (equal (frame-parameter (selected-frame) 'display) display)
310 (select-frame
77134727 311 (make-frame-on-display display)))))
44a56b29
SM
312 ;; This frame is only there in place of an actual "current display"
313 ;; setting, so we want it to be as unobtrusive as possible. That's
314 ;; what the invisibility is for. The minibuffer setting is so that
315 ;; we don't end up displaying a buffer in it (which noone would
316 ;; notice).
77134727
KL
317 ;; XXX I have found this behaviour to be surprising and annoying. -- Lorentey
318 ;; '((visibility . nil) (minibuffer . only)))))))
44a56b29 319
0c851d78 320(defun server-unquote-arg (arg)
9002956f 321 "Remove &-quotation from ARG."
0c851d78
SM
322 (replace-regexp-in-string
323 "&." (lambda (s)
324 (case (aref s 1)
325 (?& "&")
326 (?- "-")
327 (?n "\n")
328 (t " ")))
329 arg t t))
9ae0f972 330
0b0d3e0b 331(defun server-quote-arg (arg)
9002956f 332 "In ARG, insert a & before each &, each space, each newline, and -.
0b0d3e0b
KL
333Change spaces to underscores, too, so that the return value never
334contains a space."
335 (replace-regexp-in-string
336 "[-&\n ]" (lambda (s)
337 (case (aref s 0)
338 (?& "&&")
339 (?- "&-")
340 (?\n "&n")
341 (?\s "&_")))
342 arg t t))
343
724629d2
SM
344(defun server-ensure-safe-dir (dir)
345 "Make sure DIR is a directory with no race-condition issues.
346Creates the directory if necessary and makes sure:
347- there's no symlink involved
348- it's owned by us
349- it's not readable/writable by anybody else."
350 (setq dir (directory-file-name dir))
351 (let ((attrs (file-attributes dir)))
352 (unless attrs
353 (letf (((default-file-modes) ?\700)) (make-directory dir))
354 (setq attrs (file-attributes dir)))
355 ;; Check that it's safe for use.
356 (unless (and (eq t (car attrs)) (eq (nth 2 attrs) (user-uid))
357 (zerop (logand ?\077 (file-modes dir))))
358 (error "The directory %s is unsafe" dir))))
359
7229064d 360;;;###autoload
9ae0f972 361(defun server-start (&optional leave-dead)
362 "Allow this Emacs process to be a server for client processes.
363This starts a server communications subprocess through which
364client \"editors\" can send your editing commands to this Emacs job.
42bbacdf 365To use the server, set up the program `emacsclient' in the
9ae0f972 366Emacs distribution as your standard \"editor\".
367
368Prefix arg means just kill any existing server communications subprocess."
369 (interactive "P")
724629d2 370 ;; Make sure there is a safe directory in which to place the socket.
03ae35cf 371 (server-ensure-safe-dir server-socket-dir)
9ae0f972 372 ;; kill it dead!
60f8ea53
JPW
373 (if server-process
374 (condition-case () (delete-process server-process) (error nil)))
c1148e39 375 ;; Delete the socket files made by previous server invocations.
03ae35cf
SM
376 (condition-case ()
377 (delete-file (expand-file-name server-name server-socket-dir))
378 (error nil))
c1148e39 379 ;; If this Emacs already had a server, clear out associated status.
9ae0f972 380 (while server-clients
9002956f 381 (server-delete-client (car server-clients)))
8b3e840e 382 (unless leave-dead
9ae0f972 383 (if server-process
384 (server-log (message "Restarting server")))
e5576936 385 (letf (((default-file-modes) ?\700))
9002956f
KL
386 (add-hook 'delete-tty-after-functions 'server-handle-delete-tty)
387 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
388 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
389 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
390 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
e5576936
SM
391 (setq server-process
392 (make-network-process
393 :name "server" :family 'local :server t :noquery t
03ae35cf 394 :service (expand-file-name server-name server-socket-dir)
e5576936
SM
395 :sentinel 'server-sentinel :filter 'server-process-filter
396 ;; We must receive file names without being decoded.
397 ;; Those are decoded by server-process-filter according
398 ;; to file-name-coding-system.
399 :coding 'raw-text)))))
33186f32
DL
400
401;;;###autoload
402(define-minor-mode server-mode
403 "Toggle Server mode.
404With ARG, turn Server mode on if ARG is positive, off otherwise.
405Server mode runs a process that accepts commands from the
406`emacsclient' program. See `server-start' and Info node `Emacs server'."
407 :global t
408 :group 'server
409 :version "21.4"
410 ;; Fixme: Should this check for an existing server socket and do
411 ;; nothing if there is one (for multiple Emacs sessions)?
412 (server-start (not server-mode)))
9ae0f972 413\f
9ae0f972 414(defun server-process-filter (proc string)
33186f32
DL
415 "Process a request from the server to edit some files.
416PROC is the server process. Format of STRING is \"PATH PATH PATH... \\n\"."
0c851d78 417 (server-log string proc)
3f7ef08e
SM
418 (let ((prev (process-get proc 'previous-string)))
419 (when prev
420 (setq string (concat prev string))
421 (process-put proc 'previous-string nil)))
a9298135 422 (condition-case err
0b0d3e0b 423 (progn
9002956f 424 (server-add-client proc)
0b0d3e0b
KL
425 ;; If the input is multiple lines,
426 ;; process each line individually.
427 (while (string-match "\n" string)
428 (let ((request (substring string 0 (match-beginning 0)))
429 (coding-system (and default-enable-multibyte-characters
430 (or file-name-coding-system
431 default-file-name-coding-system)))
9002956f
KL
432 (client (server-client proc))
433 nowait ; t if emacsclient does not want to wait for us.
434 frame ; The frame that was opened for the client (if any).
435 display ; Open the frame on this display.
0b0d3e0b 436 dontkill ; t if the client should not be killed.
0b0d3e0b
KL
437 (files nil)
438 (lineno 1)
439 (columnno 0))
440 ;; Remove this line from STRING.
441 (setq string (substring string (match-end 0)))
9002956f 442 (while (string-match " *[^ ]* " request)
0b0d3e0b
KL
443 (let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
444 (setq request (substring request (match-end 0)))
445 (cond
9002956f
KL
446 ;; -version CLIENT-VERSION:
447 ;; Check version numbers, signal an error if there is a mismatch.
448 ((and (equal "-version" arg)
449 (string-match "\\([0-9.]+\\) " request))
0b0d3e0b 450 (let* ((client-version (match-string 1 request))
9002956f
KL
451 (truncated-emacs-version
452 (substring emacs-version 0 (length client-version))))
0b0d3e0b
KL
453 (setq request (substring request (match-end 0)))
454 (if (equal client-version truncated-emacs-version)
455 (progn
456 (process-send-string proc "-good-version \n")
9002956f
KL
457 (server-client-set client 'version client-version))
458 (error (concat "Version mismatch: Emacs is "
459 truncated-emacs-version
460 ", emacsclient is " client-version)))))
0b0d3e0b 461
9002956f 462 ;; -nowait: Emacsclient won't wait for a result.
0b0d3e0b
KL
463 ((equal "-nowait" arg) (setq nowait t))
464
9002956f
KL
465 ;; -display DISPLAY:
466 ;; Open X frames on the given instead of the default.
0b0d3e0b
KL
467 ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
468 (setq display (match-string 1 request)
469 request (substring request (match-end 0))))
470
9002956f 471 ;; -window-system: Open a new X frame.
0b0d3e0b 472 ((equal "-window-system" arg)
9002956f 473 (unless (server-client-get client 'version)
a9298135 474 (error "Protocol error; make sure to use the correct version of emacsclient"))
9002956f
KL
475 (setq frame (make-frame-on-display
476 (or display
477 (frame-parameter nil 'display)
478 (getenv "DISPLAY")
54021676
KL
479 (error "Please specify display"))))
480 (modify-frame-parameters frame (list (cons 'client proc)))
9002956f
KL
481 (select-frame frame)
482 (server-client-set client 'frame frame)
483 (setq dontkill t))
484
485 ;; -resume: Resume a suspended tty frame.
0b0d3e0b 486 ((equal "-resume" arg)
9002956f 487 (let ((tty (server-client-get client 'tty)))
0b0d3e0b
KL
488 (setq dontkill t)
489 (when tty (resume-tty tty))))
490
9002956f
KL
491 ;; -suspend: Suspend the client's frame. (In case we
492 ;; get out of sync, and a C-z sends a SIGTSTP to
493 ;; emacsclient.)
0b0d3e0b 494 ((equal "-suspend" arg)
9002956f 495 (let ((tty (server-client-get client 'tty)))
0b0d3e0b
KL
496 (setq dontkill t)
497 (when tty (suspend-tty tty))))
498
9002956f
KL
499 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
500 ;; (The given comment appears in the server log.)
0b0d3e0b
KL
501 ((and (equal "-ignore" arg) (string-match "\\([^ ]*\\) " request))
502 (setq dontkill t
503 request (substring request (match-end 0))))
504
9002956f 505 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
0b0d3e0b
KL
506 ((and (equal "-tty" arg) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request))
507 (let ((tty (server-unquote-arg (match-string 1 request)))
508 (type (server-unquote-arg (match-string 2 request))))
509 (setq request (substring request (match-end 0)))
9002956f
KL
510 (unless (server-client-get client 'version)
511 (error "Protocol error; make sure you use the correct version of emacsclient"))
54021676
KL
512 (setq frame (make-frame-on-tty tty type))
513 (modify-frame-parameters frame (list (cons 'client proc)))
9002956f
KL
514 (select-frame frame)
515 (server-client-set client 'frame frame)
516 (server-client-set client 'tty (frame-tty-name frame))
517 ;; Reply with our pid.
518 (process-send-string proc (concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
519 (setq dontkill t)))
520
521 ;; -position LINE: Go to the given line in the next file.
0b0d3e0b
KL
522 ((and (equal "-position" arg) (string-match "\\(\\+[0-9]+\\) " request))
523 (setq request (substring request (match-end 0))
524 lineno (string-to-int (substring (match-string 1 request) 1))))
525
9002956f 526 ;; -position LINE:COLUMN: Set point to the given position in the next file.
0b0d3e0b
KL
527 ((and (equal "-position" arg) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request))
528 (setq request (substring request (match-end 0))
529 lineno (string-to-int (match-string 1 request))
530 columnno (string-to-int (match-string 2 request))))
531
9002956f 532 ;; -file FILENAME: Load the given file.
0b0d3e0b
KL
533 ((and (equal "-file" arg) (string-match "\\([^ ]+\\) " request))
534 (let ((file (server-unquote-arg (match-string 1 request))))
535 (setq request (substring request (match-end 0)))
536 (if coding-system
537 (setq file (decode-coding-string file coding-system)))
538 (setq file (command-line-normalize-file-name file))
539 (push (list file lineno columnno) files))
540 (setq lineno 1
541 columnno 0))
542
9002956f 543 ;; -eval EXPR: Evaluate a Lisp expression.
0b0d3e0b
KL
544 ((and (equal "-eval" arg) (string-match "\\([^ ]+\\) " request))
545 (let ((expr (server-unquote-arg (match-string 1 request))))
546 (setq request (substring request (match-end 0)))
547 (if coding-system
548 (setq expr (decode-coding-string expr coding-system)))
549 (let ((v (eval (car (read-from-string expr)))))
9002956f 550 (when (and (not frame) v)
a9298135
KL
551 (with-temp-buffer
552 (let ((standard-output (current-buffer)))
553 (pp v)
554 (process-send-string proc "-print ")
0b0d3e0b
KL
555 (process-send-string
556 proc (server-quote-arg
557 (buffer-substring-no-properties (point-min)
558 (point-max))))
559 (process-send-string proc "\n")))))
560 (setq lineno 1
561 columnno 0)))
562
9002956f
KL
563 ;; -env NAME VALUE: An environment variable.
564 ((and (equal "-env" arg) (string-match "\\([^ ]+\\) \\([^ ]+\\) " request))
565 (let ((name (server-unquote-arg (match-string 1 request)))
566 (value (server-unquote-arg (match-string 2 request))))
567 (when coding-system
568 (setq name (decode-coding-string name coding-system))
569 (setq value (decode-coding-string value coding-system)))
570 (setq request (substring request (match-end 0)))
571 (server-client-set
572 client 'environment
573 (cons (cons name value)
574 (server-client-get client 'environment)))))
575
0b0d3e0b
KL
576 ;; Unknown command.
577 (t (error "Unknown command: %s" arg)))))
578
a9298135
KL
579 (when files
580 (run-hooks 'pre-command-hook)
581 (server-visit-files files client nowait)
582 (run-hooks 'post-command-hook))
0b0d3e0b 583
0b0d3e0b
KL
584 ;; Delete the client if necessary.
585 (cond
0b0d3e0b 586 (nowait
9002956f
KL
587 ;; Client requested nowait; return immediately.
588 (server-log "Close nowait client" proc)
589 (server-delete-client proc))
590 ((and (not dontkill)
591 (null (server-client-get client 'buffers)))
592 ;; This client is empty; get rid of it immediately.
593 (server-log "Close empty client" proc)
594 (server-delete-client proc))
595 (t
596 (let ((buffers (server-client-get client 'buffers)))
597 (when buffers
598 ;; We visited some buffer for this client.
599 (cond
600 ((or isearch-mode (minibufferp))
601 nil)
602 ((and frame (null buffers))
603 (message (substitute-command-keys
604 "When done with this frame, type \\[delete-frame]")))
605 ((not (null buffers))
606 (server-switch-buffer (car buffers))
607 (run-hooks 'server-switch-hook)
608 (unless nowait
609 (message (substitute-command-keys
610 "When done with a buffer, type \\[server-edit]")))))))))))
0b0d3e0b 611
a9298135
KL
612 ;; Save for later any partial line that remains.
613 (when (> (length string) 0)
614 (process-put proc 'previous-string string)))
615 ;; condition-case
616 (error (ignore-errors
617 (process-send-string
0b0d3e0b 618 proc (concat "-error " (server-quote-arg (error-message-string err))))
a9298135
KL
619 (setq string "")
620 (server-log (error-message-string err) proc)
621 (delete-process proc)))))
9ae0f972 622
6b98185f
RS
623(defun server-goto-line-column (file-line-col)
624 (goto-line (nth 1 file-line-col))
625 (let ((column-number (nth 2 file-line-col)))
626 (if (> column-number 0)
627 (move-to-column (1- column-number)))))
628
dfa35e6b 629(defun server-visit-files (files client &optional nowait)
44a56b29 630 "Find FILES and return the list CLIENT with the buffers nconc'd.
8c493570 631FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
dfa35e6b
RS
632NOWAIT non-nil means this client is not waiting for the results,
633so don't mark these buffers specially, just visit them normally."
e82e73c2 634 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
44a56b29 635 (let ((last-nonmenu-event t) client-record)
3a0ce849
RS
636 ;; Restore the current buffer afterward, but not using save-excursion,
637 ;; because we don't want to save point in this buffer
638 ;; if it happens to be one of those specified by the server.
44a56b29
SM
639 (save-current-buffer
640 (dolist (file files)
641 ;; If there is an existing buffer modified or the file is
642 ;; modified, revert it. If there is an existing buffer with
643 ;; deleted file, offer to write it.
644 (let* ((filen (car file))
645 (obuf (get-file-buffer filen)))
646 (push filen file-name-history)
647 (if (and obuf (set-buffer obuf))
648 (progn
649 (cond ((file-exists-p filen)
650 (if (not (verify-visited-file-modtime obuf))
651 (revert-buffer t nil)))
652 (t
653 (if (y-or-n-p
9002956f 654 (concat "File no longer exists: " filen
44a56b29
SM
655 ", write buffer to file? "))
656 (write-file filen))))
657 (setq server-existing-buffer t)
658 (server-goto-line-column file))
659 (set-buffer (find-file-noselect filen))
660 (server-goto-line-column file)
661 (run-hooks 'server-visit-hook)))
662 (unless nowait
663 ;; When the buffer is killed, inform the clients.
664 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
665 (push (car client) server-buffer-clients))
666 (push (current-buffer) client-record)))
9002956f
KL
667 (server-client-set
668 client 'buffers
669 (nconc (server-client-get client 'buffers) client-record))))
9ae0f972 670\f
b392bac9 671(defun server-buffer-done (buffer &optional for-killing)
9ae0f972 672 "Mark BUFFER as \"done\" for its client(s).
9184aafb
RS
673This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
674NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
8b3e840e
SM
675or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
676a temp file).
677FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
0c851d78 678 (let ((next-buffer nil)
9002956f
KL
679 (killed nil))
680 (dolist (client server-clients)
681 (let ((buffers (server-client-get client 'buffers)))
8b3e840e 682 (or next-buffer
9002956f
KL
683 (setq next-buffer (nth 1 (memq buffer buffers))))
684 (when buffers ; Ignore bufferless clients.
685 (setq buffers (delq buffer buffers))
686 ;; Delete all dead buffers from CLIENT.
687 (dolist (b buffers)
688 (and (bufferp b)
689 (not (buffer-live-p b))
690 (setq buffers (delq b buffers))))
691 (server-client-set client 'buffers buffers)
692 ;; If client now has no pending buffers,
693 ;; tell it that it is done, and forget it entirely.
694 (unless buffers
695 (server-log "Close" client)
696 (server-delete-client client)))))
68469f74 697 (if (and (bufferp buffer) (buffer-name buffer))
599f9a5c
RS
698 ;; We may or may not kill this buffer;
699 ;; if we do, do not call server-buffer-done recursively
700 ;; from kill-buffer-hook.
701 (let ((server-kill-buffer-running t))
408784a7 702 (with-current-buffer buffer
f9b3ef88
RS
703 (setq server-buffer-clients nil)
704 (run-hooks 'server-done-hook))
599f9a5c
RS
705 ;; Notice whether server-done-hook killed the buffer.
706 (if (null (buffer-name buffer))
707 (setq killed t)
708 ;; Don't bother killing or burying the buffer
709 ;; when we are called from kill-buffer.
710 (unless for-killing
c6a117f0
GM
711 (when (and (not killed)
712 server-kill-new-buffers
4dd04714
RS
713 (with-current-buffer buffer
714 (not server-existing-buffer)))
c6a117f0 715 (setq killed t)
3d2a0e0b 716 (bury-buffer buffer)
c6a117f0
GM
717 (kill-buffer buffer))
718 (unless killed
719 (if (server-temp-file-p buffer)
720 (progn
721 (kill-buffer buffer)
722 (setq killed t))
723 (bury-buffer buffer)))))))
9184aafb 724 (list next-buffer killed)))
9ae0f972 725
408784a7 726(defun server-temp-file-p (&optional buffer)
9ae0f972 727 "Return non-nil if BUFFER contains a file considered temporary.
728These are files whose names suggest they are repeatedly
729reused to pass information to another program.
730
731The variable `server-temp-file-regexp' controls which filenames
732are considered temporary."
733 (and (buffer-file-name buffer)
734 (string-match server-temp-file-regexp (buffer-file-name buffer))))
735
736(defun server-done ()
cc9875f9 737 "Offer to save current buffer, mark it as \"done\" for clients.
ed9ae328
RS
738This kills or buries the buffer, then returns a list
739of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
740as a suggestion for what to select next, or nil.
741KILLED is t if we killed BUFFER, which happens if it was created
742specifically for the clients and did not exist before their request for it."
408784a7
SM
743 (when server-buffer-clients
744 (if (server-temp-file-p)
745 ;; For a temp file, save, and do make a non-numeric backup
746 ;; (unless make-backup-files is nil).
747 (let ((version-control nil)
748 (buffer-backed-up nil))
749 (save-buffer))
750 (if (and (buffer-modified-p)
751 buffer-file-name
752 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
753 (save-buffer)))
754 (server-buffer-done (current-buffer))))
faf931a8 755
71207de2
RS
756;; Ask before killing a server buffer.
757;; It was suggested to release its client instead,
758;; but I think that is dangerous--the client would proceed
759;; using whatever is on disk in that file. -- rms.
03d78665 760(defun server-kill-buffer-query-function ()
9002956f 761 "Ask before killing a server buffer."
03d78665 762 (or (not server-buffer-clients)
114a8b8c
KL
763 (let ((res t))
764 (dolist (proc server-buffer-clients res)
9002956f
KL
765 (let ((client (server-client proc)))
766 (when (and client (eq (process-status proc) 'open))
767 (setq res nil)))))
03d78665
RS
768 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
769 (buffer-name (current-buffer))))))
770
03d78665 771(defun server-kill-emacs-query-function ()
9002956f
KL
772 "Ask before exiting Emacs it has are live clients."
773 (or (not server-clients)
774 (let (live-client)
775 (dolist (client server-clients live-client)
776 (if (memq t (mapcar 'buffer-live-p (server-client-get
777 client 'buffers)))
778 (setq live-client t))))
779 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
b392bac9 780
fb873cfc 781(defvar server-kill-buffer-running nil
599f9a5c 782 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
fb873cfc 783
b392bac9 784(defun server-kill-buffer ()
fb873cfc
RS
785 ;; Prevent infinite recursion if user has made server-done-hook
786 ;; call kill-buffer.
787 (or server-kill-buffer-running
599f9a5c
RS
788 (and server-buffer-clients
789 (let ((server-kill-buffer-running t))
790 (when server-process
791 (server-buffer-done (current-buffer) t))))))
9ae0f972 792\f
793(defun server-edit (&optional arg)
794 "Switch to next server editing buffer; say \"Done\" for current buffer.
795If a server buffer is current, it is marked \"done\" and optionally saved.
ed9ae328 796The buffer is also killed if it did not exist before the clients asked for it.
9ae0f972 797When all of a client's buffers are marked as \"done\", the client is notified.
798
799Temporary files such as MH <draft> files are always saved and backed up,
991298c3
RS
800no questions asked. (The variable `make-backup-files', if nil, still
801inhibits a backup; you can set it locally in a particular buffer to
802prevent a backup for it.) The variable `server-temp-file-regexp' controls
9ae0f972 803which filenames are considered temporary.
804
64f51134 805If invoked with a prefix argument, or if there is no server process running,
9ae0f972 806starts server process and that is all. Invoked by \\[server-edit]."
9ae0f972 807 (interactive "P")
808 (if (or arg
809 (not server-process)
810 (memq (process-status server-process) '(signal exit)))
811 (server-start nil)
9184aafb 812 (apply 'server-switch-buffer (server-done))))
9ae0f972 813
98a4349c 814(defun server-switch-buffer (&optional next-buffer killed-one)
9ae0f972 815 "Switch to another buffer, preferably one that has a client.
816Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
9184aafb
RS
817 ;; KILLED-ONE is t in a recursive call
818 ;; if we have already killed one temp-file server buffer.
819 ;; This means we should avoid the final "switch to some other buffer"
820 ;; since we've already effectively done that.
ca0c7250 821 (if (null next-buffer)
9002956f
KL
822 (progn
823 (let ((rest server-clients))
824 (while (and rest (not next-buffer))
825 (let ((client (car rest)))
826 ;; Only look at frameless clients.
827 (when (not (server-client-get client 'frame))
828 (setq next-buffer (car (server-client-get client 'buffers))))
829 (setq rest (cdr rest)))))
830 (and next-buffer (server-switch-buffer next-buffer killed-one))
831 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
832 ;; (switch-to-buffer (other-buffer))
90ee5627 833 (message "No server buffers remain to edit")))
9002956f 834 (if (not (buffer-live-p next-buffer))
ca0c7250 835 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
9ae0f972 836 ;; and try the next surviving server buffer.
ca0c7250
SM
837 (apply 'server-switch-buffer (server-buffer-done next-buffer))
838 ;; OK, we know next-buffer is live, let's display and select it.
408784a7
SM
839 (if (functionp server-window)
840 (funcall server-window next-buffer)
841 (let ((win (get-buffer-window next-buffer 0)))
842 (if (and win (not server-window))
843 ;; The buffer is already displayed: just reuse the window.
844 (let ((frame (window-frame win)))
845 (if (eq (frame-visible-p frame) 'icon)
846 (raise-frame frame))
847 (select-window win)
848 (set-buffer next-buffer))
849 ;; Otherwise, let's find an appropriate window.
850 (cond ((and (windowp server-window)
851 (window-live-p server-window))
852 (select-window server-window))
853 ((framep server-window)
854 (if (not (frame-live-p server-window))
855 (setq server-window (make-frame)))
856 (select-window (frame-selected-window server-window))))
857 (if (window-minibuffer-p (selected-window))
858 (select-window (next-window nil 'nomini 0)))
859 ;; Move to a non-dedicated window, if we have one.
860 (when (window-dedicated-p (selected-window))
861 (select-window
862 (get-window-with-predicate
863 (lambda (w)
864 (and (not (window-dedicated-p w))
865 (equal (frame-parameter (window-frame w) 'display)
866 (frame-parameter (selected-frame) 'display))))
867 'nomini 'visible (selected-window))))
868 (condition-case nil
869 (switch-to-buffer next-buffer)
870 ;; After all the above, we might still have ended up with
871 ;; a minibuffer/dedicated-window (if there's no other).
872 (error (pop-to-buffer next-buffer)))))))))
9ae0f972 873
874(global-set-key "\C-x#" 'server-edit)
df4e8a11 875
35dfa9b6
KL
876;;;###autoload
877(defun server-getenv (variable &optional frame)
2cd1371d
KL
878 "Get the value of VARIABLE in the client environment of frame FRAME.
879VARIABLE should be a string. Value is nil if VARIABLE is undefined in
880the environment. Otherwise, value is a string.
881
882If FRAME is an emacsclient frame, then the variable is looked up
883in the environment of the emacsclient process; otherwise the
884function consults the environment of the Emacs process.
885
886If FRAME is nil or missing, then the selected frame is used."
887 (when (not frame) (setq frame (selected-frame)))
888 (let ((clients (server-clients-with 'frame frame)) env)
889 (if (null clients)
890 (getenv variable)
891 (setq env (server-client-get (car clients) 'environment))
892 (if (null env)
893 (getenv variable)
894 (assq variable env)))))
895
df4e8a11 896(defun server-unload-hook ()
33186f32 897 (server-start t)
9002956f
KL
898 (remove-hook 'delete-tty-after-functions 'server-handle-delete-tty)
899 (remove-hook 'suspend-tty-functions 'server-handle-suspend-tty)
900 (remove-hook 'delete-frame-functions 'server-handle-delete-frame)
df4e8a11
DL
901 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
902 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
903 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
16c15321
RM
904\f
905(provide 'server)
c88ab9ce 906
ab5796a9 907;;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
c88ab9ce 908;;; server.el ends here