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