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