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