(hs-already-hidden-p): Move to end of line so hidden blocks will be
[bpt/emacs.git] / lisp / server.el
CommitLineData
55535639 1;;; server.el --- Lisp code for GNU Emacs running as server process
c88ab9ce 2
0d30b337 3;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
aaef169d 4;; 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
6d74b528 5
630cc463 6;; Author: William Sommerfeld <wesommer@athena.mit.edu>
e4874521 7;; Maintainer: FSF
d7b4d18f 8;; Keywords: processes
630cc463 9
9ae0f972 10;; Changes by peck@sun.com and by rms.
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
e5167999 16;; the Free Software Foundation; either version 2, or (at your option)
9ae0f972 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
b578f267 25;; along with GNU Emacs; see the file COPYING. If not, write to the
086add15
LK
26;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27;; Boston, MA 02110-1301, USA.
9ae0f972 28
630cc463 29;;; Commentary:
9ae0f972 30
b578f267
EN
31;; This Lisp code is run in Emacs when it is to operate as
32;; a server for other processes.
9ae0f972 33
b578f267 34;; Load this library and do M-x server-edit to enable Emacs as a server.
44a56b29
SM
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))
9ae0f972 38
b578f267
EN
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.
9ae0f972 43
b578f267 44;; Note that any number of clients may dispatch files to emacs to be edited.
9ae0f972 45
b578f267 46;; When you finish editing a Server buffer, again call server-edit
64f51134
JPW
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
b578f267 49;; and exited with server-edit, the client "editor" will return
64f51134 50;; to the program that invoked it.
9ae0f972 51
b578f267
EN
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:
9ae0f972 56
b578f267
EN
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.
9ae0f972 59
b578f267
EN
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.
9ae0f972 62
b578f267
EN
63;; 3. When the program that wants to use "the editor" is running
64;; as a subprocess of Emacs.
9ae0f972 65
b578f267
EN
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.
9ae0f972 71
64f51134
JPW
72;; The buffer local variable "server-buffer-clients" lists
73;; the clients who are waiting for this buffer to be edited.
b578f267
EN
74;; The global variable "server-clients" lists all the waiting clients,
75;; and which files are yet to be edited for each.
630cc463
ER
76
77;;; Code:
8b3e840e
SM
78
79(eval-when-compile (require 'cl))
80
ab1c7f35
RS
81(defgroup server nil
82 "Emacs running as a server process."
83 :group 'external)
84
337e3c70
JB
85(defcustom server-use-tcp nil
86 "If non-nil, use TCP sockets instead of local sockets."
87 :set #'(lambda (sym val)
88 (unless (featurep 'make-network-process '(:family local))
89 (setq val t)
90 (unless load-in-progress
91 (message "Local sockets unsupported, using TCP sockets")))
92 (when val (random t))
93 (set-default sym val))
94 :group 'server
95 :type 'boolean
96 :version "22.1")
97
98(defcustom server-host nil
99 "The name or IP address to use as host address of the server process.
100If set, the server accepts remote connections; otherwise it is local."
101 :group 'server
102 :type '(choice
103 (string :tag "Name or IP address")
104 (const :tag "Local" nil))
105 :version "22.1")
106(put 'server-host 'risky-local-variable t)
107
108(defcustom server-auth-dir "~/.emacs.d/server/"
109 "Directory for server authentication files."
110 :group 'server
111 :type 'directory
112 :version "22.1")
113(put 'server-auth-dir 'risky-local-variable t)
114
90caccca
JB
115(defcustom server-raise-frame t
116 "*If non-nil, raise frame when switching to a buffer."
117 :group 'server
118 :type 'boolean
119 :version "22.1")
120
ab1c7f35 121(defcustom server-visit-hook nil
0c851d78 122 "*Hook run when visiting a file for the Emacs server."
ab1c7f35 123 :group 'server
0c851d78 124 :type 'hook)
ab1c7f35
RS
125
126(defcustom server-switch-hook nil
0c851d78 127 "*Hook run when switching to a buffer for the Emacs server."
ab1c7f35 128 :group 'server
0c851d78 129 :type 'hook)
ab1c7f35
RS
130
131(defcustom server-done-hook nil
0c851d78 132 "*Hook run when done editing a buffer for the Emacs server."
ab1c7f35 133 :group 'server
0c851d78 134 :type 'hook)
f9b3ef88 135
64f51134
JPW
136(defvar server-process nil
137 "The current server process.")
9ae0f972 138
139(defvar server-clients nil
140 "List of current server clients.
e82e73c2 141Each element is (CLIENTID BUFFERS...) where CLIENTID is a string
9ae0f972 142that can be given to the server process to identify a client.
143When a buffer is marked as \"done\", it is removed from this list.")
144
145(defvar server-buffer-clients nil
b5a9911c 146 "List of client ids for clients requesting editing of current buffer.")
faf931a8 147(make-variable-buffer-local 'server-buffer-clients)
9ae0f972 148;; Changing major modes should not erase this local.
149(put 'server-buffer-clients 'permanent-local t)
150
33186f32
DL
151(defcustom server-window nil
152 "*Specification of the window to use for selecting Emacs server buffers.
ec40ed9f 153If nil, use the selected window.
408784a7 154If it is a function, it should take one argument (a buffer) and
33186f32
DL
155display and select it. A common value is `pop-to-buffer'.
156If it is a window, use that.
157If it is a frame, use the frame's selected window.
158
159It is not meaningful to set this to a specific frame or window with Custom.
160Only programs can do so."
161 :group 'server
bf247b6e 162 :version "22.1"
33186f32
DL
163 :type '(choice (const :tag "Use selected window"
164 :match (lambda (widget value)
165 (not (functionp value)))
166 nil)
167 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
168 (function :tag "Other function")))
ec40ed9f 169
ab1c7f35 170(defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
33186f32
DL
171 "*Regexp matching names of temporary files.
172These are deleted and reused after each edit by the programs that
173invoke the Emacs server."
ab1c7f35
RS
174 :group 'server
175 :type 'regexp)
9ae0f972 176
c6a117f0
GM
177(defcustom server-kill-new-buffers t
178 "*Whether to kill buffers when done with them.
179If non-nil, kill a buffer unless it already existed before editing
64f51134 180it with Emacs server. If nil, kill only buffers as specified by
c6a117f0
GM
181`server-temp-file-regexp'.
182Please note that only buffers are killed that still have a client,
183i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
184this way."
185 :group 'server
186 :type 'boolean
187 :version "21.1")
188
9ae0f972 189(or (assq 'server-buffer-clients minor-mode-alist)
b7621225 190 (push '(server-buffer-clients " Server") minor-mode-alist))
9ae0f972 191
c6a117f0 192(defvar server-existing-buffer nil
ca0c7250 193 "Non-nil means the buffer existed before the server was asked to visit it.
4dd04714 194This means that the server should not kill the buffer when you say you
ca0c7250 195are done with it in the server.")
c6a117f0
GM
196(make-variable-buffer-local 'server-existing-buffer)
197
03ae35cf
SM
198(defvar server-name "server")
199
200(defvar server-socket-dir
201 (format "/tmp/emacs%d" (user-uid)))
0c851d78 202
8b3e840e 203(defun server-log (string &optional client)
33186f32 204 "If a *server* buffer exists, write STRING to it for logging purposes."
337e3c70
JB
205 (when (get-buffer "*server*")
206 (with-current-buffer "*server*"
207 (goto-char (point-max))
208 (insert (current-time-string)
209 (if client (format " %s:" client) " ")
210 string)
211 (or (bolp) (newline)))))
9ae0f972 212
213(defun server-sentinel (proc msg)
408784a7 214 (let ((client (assq proc server-clients)))
0c851d78 215 ;; Remove PROC from the list of clients.
408784a7
SM
216 (when client
217 (setq server-clients (delq client server-clients))
218 (dolist (buf (cdr client))
219 (with-current-buffer buf
220 ;; Remove PROC from the clients of each buffer.
221 (setq server-buffer-clients (delq proc server-buffer-clients))
222 ;; Kill the buffer if necessary.
223 (when (and (null server-buffer-clients)
224 (or (and server-kill-new-buffers
225 (not server-existing-buffer))
226 (server-temp-file-p)))
227 (kill-buffer (current-buffer)))))))
cbfc02e4
RF
228 ;; If this is a new client process, set the query-on-exit flag to nil
229 ;; for this process (it isn't inherited from the server process).
230 (when (and (eq (process-status proc) 'open)
231 (process-query-on-exit-flag proc))
232 (set-process-query-on-exit-flag proc nil))
757e1681
SM
233 ;; Delete the associated connection file, if applicable.
234 ;; This is actually problematic: the file may have been overwritten by
235 ;; another Emacs server in the mean time, so it's not ours any more.
236 ;; (and (process-contact proc :server)
237 ;; (eq (process-status proc) 'closed)
238 ;; (ignore-errors (delete-file (process-get proc :server-file))))
0c851d78
SM
239 (server-log (format "Status changed to %s" (process-status proc)) proc))
240
44a56b29
SM
241(defun server-select-display (display)
242 ;; If the current frame is on `display' we're all set.
243 (unless (equal (frame-parameter (selected-frame) 'display) display)
244 ;; Otherwise, look for an existing frame there and select it.
245 (dolist (frame (frame-list))
246 (when (equal (frame-parameter frame 'display) display)
247 (select-frame frame)))
30088515 248 ;; If there's no frame on that display yet, create and select one.
44a56b29 249 (unless (equal (frame-parameter (selected-frame) 'display) display)
7acc677b
SM
250 (let* ((buffer (generate-new-buffer " *server-dummy*"))
251 (frame (make-frame-on-display
252 display
253 ;; Make it display (and remember) some dummy buffer, so
254 ;; we can detect later if the frame is in use or not.
255 `((server-dummmy-buffer . ,buffer)
256 ;; This frame may be deleted later (see
257 ;; server-unselect-display) so we want it to be as
258 ;; unobtrusive as possible.
259 (visibility . nil)))))
260 (select-frame frame)
261 (set-window-buffer (selected-window) buffer)))))
262
263(defun server-unselect-display (frame)
264 ;; If the temporary frame is in use (displays something real), make it
265 ;; visible. If not (which can happen if the user's customizations call
266 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
267 ;; the last real frame is deleted.
268 (if (and (eq (frame-first-window frame)
269 (next-window (frame-first-window frame) 'nomini))
270 (eq (window-buffer (frame-first-window frame))
271 (frame-parameter frame 'server-dummy-buffer)))
272 ;; The temp frame still only shows one buffer, and that is the
273 ;; internal temp buffer.
274 (delete-frame frame)
275 (set-frame-parameter frame 'visibility t))
276 (kill-buffer (frame-parameter frame 'server-dummy-buffer))
277 (set-frame-parameter frame 'server-dummy-buffer nil))
44a56b29 278
0c851d78
SM
279(defun server-unquote-arg (arg)
280 (replace-regexp-in-string
281 "&." (lambda (s)
282 (case (aref s 1)
283 (?& "&")
284 (?- "-")
285 (?n "\n")
286 (t " ")))
287 arg t t))
9ae0f972 288
724629d2
SM
289(defun server-ensure-safe-dir (dir)
290 "Make sure DIR is a directory with no race-condition issues.
291Creates the directory if necessary and makes sure:
292- there's no symlink involved
293- it's owned by us
294- it's not readable/writable by anybody else."
295 (setq dir (directory-file-name dir))
296 (let ((attrs (file-attributes dir)))
297 (unless attrs
337e3c70 298 (letf (((default-file-modes) ?\700)) (make-directory dir t))
724629d2
SM
299 (setq attrs (file-attributes dir)))
300 ;; Check that it's safe for use.
301 (unless (and (eq t (car attrs)) (eq (nth 2 attrs) (user-uid))
337e3c70
JB
302 (or (eq system-type 'windows-nt)
303 (zerop (logand ?\077 (file-modes dir)))))
724629d2
SM
304 (error "The directory %s is unsafe" dir))))
305
7229064d 306;;;###autoload
9ae0f972 307(defun server-start (&optional leave-dead)
308 "Allow this Emacs process to be a server for client processes.
309This starts a server communications subprocess through which
310client \"editors\" can send your editing commands to this Emacs job.
42bbacdf 311To use the server, set up the program `emacsclient' in the
9ae0f972 312Emacs distribution as your standard \"editor\".
313
314Prefix arg means just kill any existing server communications subprocess."
315 (interactive "P")
337e3c70 316 (when server-process
b7621225 317 ;; kill it dead!
757e1681 318 (ignore-errors (delete-process server-process)))
c1148e39 319 ;; If this Emacs already had a server, clear out associated status.
9ae0f972 320 (while server-clients
321 (let ((buffer (nth 1 (car server-clients))))
322 (server-buffer-done buffer)))
2e8457a0 323 ;; Now any previous server is properly stopped.
8b3e840e 324 (unless leave-dead
757e1681
SM
325 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
326 (server-file (expand-file-name server-name server-dir)))
327 ;; Make sure there is a safe directory in which to place the socket.
328 (server-ensure-safe-dir server-dir)
329 ;; Remove any leftover socket or authentication file.
330 (ignore-errors (delete-file server-file))
331 (when server-process
332 (server-log (message "Restarting server")))
333 (letf (((default-file-modes) ?\700))
334 (setq server-process
335 (apply #'make-network-process
336 :name server-name
337 :server t
338 :noquery t
339 :sentinel 'server-sentinel
340 :filter 'server-process-filter
341 ;; We must receive file names without being decoded.
342 ;; Those are decoded by server-process-filter according
343 ;; to file-name-coding-system.
344 :coding 'raw-text
345 ;; The rest of the args depends on the kind of socket used.
346 (if server-use-tcp
347 (list :family nil
348 :service t
349 :host (or server-host 'local)
350 :plist '(:authenticated nil))
351 (list :family 'local
352 :service server-file
353 :plist '(:authenticated t)))))
e101e718
JB
354 (unless server-process (error "Could not start server process"))
355 (when server-use-tcp
356 (let ((auth-key
357 (loop
358 ;; The auth key is a 64-byte string of random chars in the
359 ;; range `!'..`~'.
360 for i below 64
361 collect (+ 33 (random 94)) into auth
362 finally return (concat auth))))
363 (process-put server-process :auth-key auth-key)
364 (with-temp-file server-file
365 (set-buffer-multibyte nil)
366 (setq buffer-file-coding-system 'no-conversion)
367 (insert (format-network-address
368 (process-contact server-process :local))
c42690a6 369 " " (int-to-string (emacs-pid))
e101e718 370 "\n" auth-key))))))))
33186f32
DL
371
372;;;###autoload
373(define-minor-mode server-mode
374 "Toggle Server mode.
375With ARG, turn Server mode on if ARG is positive, off otherwise.
376Server mode runs a process that accepts commands from the
377`emacsclient' program. See `server-start' and Info node `Emacs server'."
378 :global t
379 :group 'server
bf247b6e 380 :version "22.1"
33186f32
DL
381 ;; Fixme: Should this check for an existing server socket and do
382 ;; nothing if there is one (for multiple Emacs sessions)?
383 (server-start (not server-mode)))
9ae0f972 384\f
337e3c70 385(defun* server-process-filter (proc string)
33186f32
DL
386 "Process a request from the server to edit some files.
387PROC is the server process. Format of STRING is \"PATH PATH PATH... \\n\"."
337e3c70
JB
388 ;; First things first: let's check the authentication
389 (unless (process-get proc :authenticated)
390 (if (and (string-match "-auth \\(.*?\\)\n" string)
757e1681 391 (equal (match-string 1 string) (process-get proc :auth-key)))
337e3c70
JB
392 (progn
393 (setq string (substring string (match-end 0)))
394 (process-put proc :authenticated t)
395 (server-log "Authentication successful" proc))
396 (server-log "Authentication failed" proc)
95eefb35 397 (process-send-string proc "Authentication failed")
337e3c70
JB
398 (delete-process proc)
399 ;; We return immediately
400 (return-from server-process-filter)))
0c851d78 401 (server-log string proc)
337e3c70 402 (let ((prev (process-get proc :previous-string)))
3f7ef08e
SM
403 (when prev
404 (setq string (concat prev string))
337e3c70 405 (process-put proc :previous-string nil)))
68469f74
RS
406 ;; If the input is multiple lines,
407 ;; process each line individually.
408 (while (string-match "\n" string)
409 (let ((request (substring string 0 (match-beginning 0)))
6b7430a8
KH
410 (coding-system (and default-enable-multibyte-characters
411 (or file-name-coding-system
412 default-file-name-coding-system)))
44a56b29 413 client nowait eval
9ae0f972 414 (files nil)
8c493570 415 (lineno 1)
337e3c70 416 (tmp-frame nil) ;; Sometimes used to embody the selected display.
8c493570 417 (columnno 0))
68469f74 418 ;; Remove this line from STRING.
0c851d78
SM
419 (setq string (substring string (match-end 0)))
420 (setq client (cons proc nil))
421 (while (string-match "[^ ]* " request)
724629d2 422 (let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
0c851d78
SM
423 (setq request (substring request (match-end 0)))
424 (cond
95eefb35
JB
425 ((equal "-nowait" arg) (setq nowait t))
426 ((equal "-eval" arg) (setq eval t))
427 ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
428 (let ((display (server-unquote-arg (match-string 1 request))))
429 (setq request (substring request (match-end 0)))
430 (condition-case err
431 (setq tmp-frame (server-select-display display))
432 (error (process-send-string proc (nth 1 err))
433 (setq request "")))))
434 ;; ARG is a line number option.
435 ((string-match "\\`\\+[0-9]+\\'" arg)
436 (setq lineno (string-to-number (substring arg 1))))
437 ;; ARG is line number:column option.
438 ((string-match "\\`+\\([0-9]+\\):\\([0-9]+\\)\\'" arg)
439 (setq lineno (string-to-number (match-string 1 arg))
440 columnno (string-to-number (match-string 2 arg))))
441 (t
442 ;; Undo the quoting that emacsclient does
443 ;; for certain special characters.
444 (setq arg (server-unquote-arg arg))
445 ;; Now decode the file name if necessary.
446 (when coding-system
447 (setq arg (decode-coding-string arg coding-system)))
448 (if eval
449 (let* (errorp
450 (v (condition-case errobj
451 (eval (car (read-from-string arg)))
452 (error (setq errorp t) errobj))))
453 (when v
454 (with-temp-buffer
455 (let ((standard-output (current-buffer)))
456 (when errorp (princ "error: "))
457 (pp v)
458 (ignore-errors
459 (process-send-region proc (point-min) (point-max)))
460 ))))
461 ;; ARG is a file name.
462 ;; Collapse multiple slashes to single slashes.
463 (setq arg (command-line-normalize-file-name arg))
464 (push (list arg lineno columnno) files))
465 (setq lineno 1)
466 (setq columnno 0)))))
0c851d78
SM
467 (when files
468 (run-hooks 'pre-command-hook)
469 (server-visit-files files client nowait)
470 (run-hooks 'post-command-hook))
471 ;; CLIENT is now a list (CLIENTNUM BUFFERS...)
472 (if (null (cdr client))
473 ;; This client is empty; get rid of it immediately.
474 (progn
475 (delete-process proc)
476 (server-log "Close empty client" proc))
477 ;; We visited some buffer for this client.
478 (or nowait (push client server-clients))
64f51134 479 (unless (or isearch-mode (minibufferp))
cf1175df
RS
480 (server-switch-buffer (nth 1 client))
481 (run-hooks 'server-switch-hook)
482 (unless nowait
8a26c165 483 (message "%s" (substitute-command-keys
95eefb35 484 "When done with a buffer, type \\[server-edit]")))))
7acc677b
SM
485 (when (frame-live-p tmp-frame)
486 ;; Delete tmp-frame or make it visible depending on whether it's
487 ;; been used or not.
488 (server-unselect-display tmp-frame))))
68469f74 489 ;; Save for later any partial line that remains.
0c851d78 490 (when (> (length string) 0)
337e3c70 491 (process-put proc :previous-string string)))
9ae0f972 492
6b98185f
RS
493(defun server-goto-line-column (file-line-col)
494 (goto-line (nth 1 file-line-col))
495 (let ((column-number (nth 2 file-line-col)))
337e3c70
JB
496 (when (> column-number 0)
497 (move-to-column (1- column-number)))))
6b98185f 498
dfa35e6b 499(defun server-visit-files (files client &optional nowait)
44a56b29 500 "Find FILES and return the list CLIENT with the buffers nconc'd.
8c493570 501FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
dfa35e6b
RS
502NOWAIT non-nil means this client is not waiting for the results,
503so don't mark these buffers specially, just visit them normally."
e82e73c2 504 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
44a56b29 505 (let ((last-nonmenu-event t) client-record)
3a0ce849
RS
506 ;; Restore the current buffer afterward, but not using save-excursion,
507 ;; because we don't want to save point in this buffer
508 ;; if it happens to be one of those specified by the server.
44a56b29
SM
509 (save-current-buffer
510 (dolist (file files)
511 ;; If there is an existing buffer modified or the file is
512 ;; modified, revert it. If there is an existing buffer with
513 ;; deleted file, offer to write it.
cd7320d4
JB
514 (let* ((minibuffer-auto-raise (or server-raise-frame
515 minibuffer-auto-raise))
c2d0d432 516 (filen (car file))
44a56b29 517 (obuf (get-file-buffer filen)))
c398358a 518 (add-to-history 'file-name-history filen)
44a56b29
SM
519 (if (and obuf (set-buffer obuf))
520 (progn
521 (cond ((file-exists-p filen)
95eefb35
JB
522 (when (not (verify-visited-file-modtime obuf))
523 (revert-buffer t nil)))
44a56b29 524 (t
95eefb35
JB
525 (when (y-or-n-p
526 (concat "File no longer exists: "
527 filen
528 ", write buffer to file? "))
529 (write-file filen))))
44a56b29
SM
530 (setq server-existing-buffer t)
531 (server-goto-line-column file))
532 (set-buffer (find-file-noselect filen))
533 (server-goto-line-column file)
534 (run-hooks 'server-visit-hook)))
535 (unless nowait
536 ;; When the buffer is killed, inform the clients.
537 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
538 (push (car client) server-buffer-clients))
539 (push (current-buffer) client-record)))
9ae0f972 540 (nconc client client-record)))
541\f
b392bac9 542(defun server-buffer-done (buffer &optional for-killing)
9ae0f972 543 "Mark BUFFER as \"done\" for its client(s).
9184aafb
RS
544This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
545NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
8b3e840e
SM
546or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
547a temp file).
548FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
0c851d78 549 (let ((next-buffer nil)
9184aafb 550 (killed nil)
9ae0f972 551 (old-clients server-clients))
552 (while old-clients
553 (let ((client (car old-clients)))
8b3e840e 554 (or next-buffer
9ae0f972 555 (setq next-buffer (nth 1 (memq buffer client))))
556 (delq buffer client)
68469f74
RS
557 ;; Delete all dead buffers from CLIENT.
558 (let ((tail client))
559 (while tail
560 (and (bufferp (car tail))
561 (null (buffer-name (car tail)))
562 (delq (car tail) client))
563 (setq tail (cdr tail))))
9ae0f972 564 ;; If client now has no pending buffers,
565 ;; tell it that it is done, and forget it entirely.
0c851d78
SM
566 (unless (cdr client)
567 (delete-process (car client))
568 (server-log "Close" (car client))
9ae0f972 569 (setq server-clients (delq client server-clients))))
570 (setq old-clients (cdr old-clients)))
337e3c70
JB
571 (when (and (bufferp buffer) (buffer-name buffer))
572 ;; We may or may not kill this buffer;
573 ;; if we do, do not call server-buffer-done recursively
574 ;; from kill-buffer-hook.
575 (let ((server-kill-buffer-running t))
576 (with-current-buffer buffer
577 (setq server-buffer-clients nil)
578 (run-hooks 'server-done-hook))
579 ;; Notice whether server-done-hook killed the buffer.
580 (if (null (buffer-name buffer))
581 (setq killed t)
582 ;; Don't bother killing or burying the buffer
583 ;; when we are called from kill-buffer.
584 (unless for-killing
585 (when (and (not killed)
586 server-kill-new-buffers
587 (with-current-buffer buffer
588 (not server-existing-buffer)))
599f9a5c 589 (setq killed t)
337e3c70
JB
590 (bury-buffer buffer)
591 (kill-buffer buffer))
592 (unless killed
593 (if (server-temp-file-p buffer)
594 (progn
595 (kill-buffer buffer)
596 (setq killed t))
597 (bury-buffer buffer)))))))
9184aafb 598 (list next-buffer killed)))
9ae0f972 599
408784a7 600(defun server-temp-file-p (&optional buffer)
9ae0f972 601 "Return non-nil if BUFFER contains a file considered temporary.
602These are files whose names suggest they are repeatedly
603reused to pass information to another program.
604
605The variable `server-temp-file-regexp' controls which filenames
606are considered temporary."
607 (and (buffer-file-name buffer)
608 (string-match server-temp-file-regexp (buffer-file-name buffer))))
609
610(defun server-done ()
cc9875f9 611 "Offer to save current buffer, mark it as \"done\" for clients.
ed9ae328
RS
612This kills or buries the buffer, then returns a list
613of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
614as a suggestion for what to select next, or nil.
615KILLED is t if we killed BUFFER, which happens if it was created
616specifically for the clients and did not exist before their request for it."
408784a7
SM
617 (when server-buffer-clients
618 (if (server-temp-file-p)
619 ;; For a temp file, save, and do make a non-numeric backup
620 ;; (unless make-backup-files is nil).
621 (let ((version-control nil)
622 (buffer-backed-up nil))
623 (save-buffer))
337e3c70
JB
624 (when (and (buffer-modified-p)
625 buffer-file-name
626 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
627 (save-buffer)))
408784a7 628 (server-buffer-done (current-buffer))))
faf931a8 629
71207de2
RS
630;; Ask before killing a server buffer.
631;; It was suggested to release its client instead,
632;; but I think that is dangerous--the client would proceed
633;; using whatever is on disk in that file. -- rms.
03d78665
RS
634(defun server-kill-buffer-query-function ()
635 (or (not server-buffer-clients)
636 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
637 (buffer-name (current-buffer))))))
638
faf931a8 639(add-hook 'kill-buffer-query-functions
03d78665
RS
640 'server-kill-buffer-query-function)
641
642(defun server-kill-emacs-query-function ()
e82e73c2
RS
643 (let (live-client
644 (tail server-clients))
645 ;; See if any clients have any buffers that are still alive.
646 (while tail
337e3c70
JB
647 (when (memq t (mapcar 'stringp (mapcar 'buffer-name (cdr (car tail)))))
648 (setq live-client t))
e82e73c2
RS
649 (setq tail (cdr tail)))
650 (or (not live-client)
651 (yes-or-no-p "Server buffers still have clients; exit anyway? "))))
03d78665
RS
652
653(add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
b392bac9 654
fb873cfc 655(defvar server-kill-buffer-running nil
599f9a5c 656 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
fb873cfc 657
b392bac9 658(defun server-kill-buffer ()
fb873cfc
RS
659 ;; Prevent infinite recursion if user has made server-done-hook
660 ;; call kill-buffer.
661 (or server-kill-buffer-running
599f9a5c
RS
662 (and server-buffer-clients
663 (let ((server-kill-buffer-running t))
664 (when server-process
665 (server-buffer-done (current-buffer) t))))))
9ae0f972 666\f
667(defun server-edit (&optional arg)
668 "Switch to next server editing buffer; say \"Done\" for current buffer.
669If a server buffer is current, it is marked \"done\" and optionally saved.
ed9ae328 670The buffer is also killed if it did not exist before the clients asked for it.
9ae0f972 671When all of a client's buffers are marked as \"done\", the client is notified.
672
673Temporary files such as MH <draft> files are always saved and backed up,
991298c3
RS
674no questions asked. (The variable `make-backup-files', if nil, still
675inhibits a backup; you can set it locally in a particular buffer to
676prevent a backup for it.) The variable `server-temp-file-regexp' controls
9ae0f972 677which filenames are considered temporary.
678
64f51134 679If invoked with a prefix argument, or if there is no server process running,
9ae0f972 680starts server process and that is all. Invoked by \\[server-edit]."
9ae0f972 681 (interactive "P")
6b519504 682 (cond
95eefb35
JB
683 ((or arg
684 (not server-process)
685 (memq (process-status server-process) '(signal exit)))
686 (server-mode 1))
687 (server-clients (apply 'server-switch-buffer (server-done)))
688 (t (message "No server editing buffers exist"))))
9ae0f972 689
98a4349c 690(defun server-switch-buffer (&optional next-buffer killed-one)
9ae0f972 691 "Switch to another buffer, preferably one that has a client.
692Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
9184aafb
RS
693 ;; KILLED-ONE is t in a recursive call
694 ;; if we have already killed one temp-file server buffer.
695 ;; This means we should avoid the final "switch to some other buffer"
696 ;; since we've already effectively done that.
ca0c7250
SM
697 (if (null next-buffer)
698 (if server-clients
699 (server-switch-buffer (nth 1 (car server-clients)) killed-one)
0c851d78 700 (unless (or killed-one (window-dedicated-p (selected-window)))
90ee5627
RS
701 (switch-to-buffer (other-buffer))
702 (message "No server buffers remain to edit")))
ca0c7250
SM
703 (if (not (buffer-name next-buffer))
704 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
9ae0f972 705 ;; and try the next surviving server buffer.
ca0c7250
SM
706 (apply 'server-switch-buffer (server-buffer-done next-buffer))
707 ;; OK, we know next-buffer is live, let's display and select it.
408784a7
SM
708 (if (functionp server-window)
709 (funcall server-window next-buffer)
710 (let ((win (get-buffer-window next-buffer 0)))
711 (if (and win (not server-window))
712 ;; The buffer is already displayed: just reuse the window.
90caccca
JB
713 (progn
714 (select-window win)
715 (set-buffer next-buffer))
408784a7
SM
716 ;; Otherwise, let's find an appropriate window.
717 (cond ((and (windowp server-window)
718 (window-live-p server-window))
719 (select-window server-window))
720 ((framep server-window)
337e3c70
JB
721 (unless (frame-live-p server-window)
722 (setq server-window (make-frame)))
408784a7 723 (select-window (frame-selected-window server-window))))
337e3c70
JB
724 (when (window-minibuffer-p (selected-window))
725 (select-window (next-window nil 'nomini 0)))
408784a7
SM
726 ;; Move to a non-dedicated window, if we have one.
727 (when (window-dedicated-p (selected-window))
728 (select-window
729 (get-window-with-predicate
730 (lambda (w)
731 (and (not (window-dedicated-p w))
732 (equal (frame-parameter (window-frame w) 'display)
733 (frame-parameter (selected-frame) 'display))))
734 'nomini 'visible (selected-window))))
735 (condition-case nil
736 (switch-to-buffer next-buffer)
737 ;; After all the above, we might still have ended up with
738 ;; a minibuffer/dedicated-window (if there's no other).
90caccca
JB
739 (error (pop-to-buffer next-buffer)))))))
740 (when server-raise-frame
741 (select-frame-set-input-focus (window-frame (selected-window))))))
9ae0f972 742
772c5eb7 743(define-key ctl-x-map "#" 'server-edit)
df4e8a11
DL
744
745(defun server-unload-hook ()
2e8457a0 746 (server-mode -1)
df4e8a11
DL
747 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
748 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
749 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
3bb38bc2 750
2e8457a0 751(add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
3bb38bc2 752(add-hook 'server-unload-hook 'server-unload-hook)
16c15321
RM
753\f
754(provide 'server)
c88ab9ce 755
2e8457a0 756;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
c88ab9ce 757;;; server.el ends here