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