1 ;;; server.el --- Lisp code for GNU Emacs running as server process
3 ;; Copyright (C) 1986, 87, 92, 94, 95, 96, 97, 98, 99, 2000, 2001
4 ;; Free Software Foundation, Inc.
6 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
10 ;; Changes by peck@sun.com and by rms.
12 ;; This file is part of GNU Emacs.
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)
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.
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.
31 ;; This Lisp code is run in Emacs when it is to operate as
32 ;; a server for other processes.
34 ;; Load this library and do M-x server-edit to enable Emacs as a server.
35 ;; Emacs runs the program ../arch-lib/emacsserver as a subprocess
36 ;; for communication with clients. If there are no client buffers to edit,
37 ;; server-edit acts like (switch-to-buffer (other-buffer))
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.
44 ;; Note that any number of clients may dispatch files to emacs to be edited.
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.
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:
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.
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.
63 ;; 3. When the program that wants to use "the editor" is running
64 ;; as a subprocess of Emacs.
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.
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.
79 (eval-when-compile (require 'cl))
82 "Emacs running as a server process."
85 (defcustom server-visit-hook nil
86 "*Hook run when visiting a file for the Emacs server."
90 (defcustom server-switch-hook nil
91 "*Hook run when switching to a buffer for the Emacs server."
95 (defcustom server-done-hook nil
96 "*Hook run when done editing a buffer for the Emacs server."
100 (defvar server-process nil
101 "The current server process")
103 (defvar server-previous-strings nil)
105 (defvar server-clients nil
106 "List of current server clients.
107 Each element is (CLIENTID BUFFERS...) where CLIENTID is a string
108 that can be given to the server process to identify a client.
109 When a buffer is marked as \"done\", it is removed from this list.")
111 (defvar server-buffer-clients nil
112 "List of client ids for clients requesting editing of current buffer.")
113 (make-variable-buffer-local 'server-buffer-clients)
114 ;; Changing major modes should not erase this local.
115 (put 'server-buffer-clients 'permanent-local t)
117 (defvar server-window nil
118 "*The window to use for selecting Emacs server buffers.
119 If nil, use the selected window.
120 If it is a frame, use the frame's selected window.")
122 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
123 "*Regexp which should match filenames of temporary files
124 which are deleted and reused after each edit
125 by the programs that invoke the Emacs server."
129 (defcustom server-kill-new-buffers t
130 "*Whether to kill buffers when done with them.
131 If non-nil, kill a buffer unless it already existed before editing
132 it with Emacs server. If nil, kill only buffers as specified by
133 `server-temp-file-regexp'.
134 Please note that only buffers are killed that still have a client,
135 i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
141 (or (assq 'server-buffer-clients minor-mode-alist)
142 (setq minor-mode-alist (cons '(server-buffer-clients " Server") minor-mode-alist)))
144 (defvar server-existing-buffer nil
145 "Non-nil means the buffer existed before the server was asked to visit it.
146 This means that the server should not kill the buffer when you say you
147 are done with it in the server.")
148 (make-variable-buffer-local 'server-existing-buffer)
150 (defvar server-socket-name
151 (if (or (not (file-writable-p "~/"))
152 (and (file-writable-p "/tmp/")
153 (not (zerop (logand (file-modes "/tmp/") 512)))))
154 (format "/tmp/esrv%d-%s" (user-uid) (system-name))
155 (format "~/.emacs-server-%s" (system-name))))
157 ;; If a *server* buffer exists,
158 ;; write STRING to it for logging purposes.
159 (defun server-log (string &optional client)
160 (if (get-buffer "*server*")
161 (with-current-buffer "*server*"
162 (goto-char (point-max))
163 (insert (current-time-string)
164 (if client (format " %s:" client) " ")
166 (or (bolp) (newline)))))
168 (defun server-sentinel (proc msg)
169 ;; Purge server-previous-strings of the now irrelevant entry.
170 (setq server-previous-strings
171 (delq (assq proc server-previous-strings) server-previous-strings))
172 (let ((ps (assq proc server-clients)))
173 (dolist (buf (cdr ps))
174 (with-current-buffer buf
175 ;; Remove PROC from the clients of each buffer.
176 (setq server-buffer-clients (delq proc server-buffer-clients))))
177 ;; Remove PROC from the list of clients.
178 (if ps (setq server-clients (delq ps server-clients))))
179 (server-log (format "Status changed to %s" (process-status proc)) proc))
181 (defun server-unquote-arg (arg)
182 (replace-regexp-in-string
192 (defun server-start (&optional leave-dead)
193 "Allow this Emacs process to be a server for client processes.
194 This starts a server communications subprocess through which
195 client \"editors\" can send your editing commands to this Emacs job.
196 To use the server, set up the program `emacsclient' in the
197 Emacs distribution as your standard \"editor\".
199 Prefix arg means just kill any existing server communications subprocess."
202 (condition-case () (delete-process server-process) (error nil))
203 ;; Delete the socket files made by previous server invocations.
204 (condition-case () (delete-file server-socket-name) (error nil))
205 ;; If this Emacs already had a server, clear out associated status.
206 (while server-clients
207 (let ((buffer (nth 1 (car server-clients))))
208 (server-buffer-done buffer)))
211 (server-log (message "Restarting server")))
212 (let ((umask (default-file-modes)))
215 (set-default-file-modes ?\700)
217 (make-network-process
218 :name "server" :family 'local :server t :noquery t
219 :service server-socket-name
220 :sentinel 'server-sentinel :filter 'server-process-filter
221 ;; We must receive file names without being decoded.
222 ;; Those are decoded by server-process-filter according
223 ;; to file-name-coding-system.
225 (set-default-file-modes umask)))))
227 ;Process a request from the server to edit some files.
228 ;Format of STRING is "PATH PATH PATH... \n"
229 (defun server-process-filter (proc string)
230 (server-log string proc)
231 (let ((ps (assq proc server-previous-strings)))
233 (setq string (concat (cdr ps) string))
235 ;; If the input is multiple lines,
236 ;; process each line individually.
237 (while (string-match "\n" string)
238 (let ((request (substring string 0 (match-beginning 0)))
239 (coding-system (and default-enable-multibyte-characters
240 (or file-name-coding-system
241 default-file-name-coding-system)))
246 ;; Remove this line from STRING.
247 (setq string (substring string (match-end 0)))
248 (setq client (cons proc nil))
249 (while (string-match "[^ ]* " request)
250 (let ((arg (substring request (match-beginning 0) (1- (match-end 0))))
252 (setq request (substring request (match-end 0)))
254 ((equal "-nowait" arg) (setq nowait t))
255 ;; ARG is a line number option.
256 ((string-match "\\`\\+[0-9]+\\'" arg)
257 (setq lineno (string-to-int (substring arg 1))))
258 ;; ARG is line number:column option.
259 ((string-match "\\`+\\([0-9]+\\):\\([0-9]+\\)\\'" arg)
260 (setq lineno (string-to-int (match-string 1 arg))
261 columnno (string-to-int (match-string 2 arg))))
263 ;; Undo the quoting that emacsclient does
264 ;; for certain special characters.
265 (setq arg (server-unquote-arg arg))
266 ;; Now decode the file name if necessary.
268 (setq arg (decode-coding-string arg coding-system)))
269 ;; ARG is a file name.
270 ;; Collapse multiple slashes to single slashes.
271 (setq arg (command-line-normalize-file-name arg))
272 (push (list arg lineno columnno) files)
274 (setq columnno 0)))))
276 (run-hooks 'pre-command-hook)
277 (server-visit-files files client nowait)
278 (run-hooks 'post-command-hook))
279 ;; CLIENT is now a list (CLIENTNUM BUFFERS...)
280 (if (null (cdr client))
281 ;; This client is empty; get rid of it immediately.
283 (delete-process proc)
284 (server-log "Close empty client" proc))
285 ;; We visited some buffer for this client.
286 (or nowait (push client server-clients))
287 (server-switch-buffer (nth 1 client))
288 (run-hooks 'server-switch-hook)
290 (message (substitute-command-keys
291 "When done with a buffer, type \\[server-edit]"))))))
292 ;; Save for later any partial line that remains.
293 (when (> (length string) 0)
294 (let ((ps (assq proc server-previous-strings)))
295 (if ps (setcdr ps string)
296 (push (cons proc string) server-previous-strings)))))
298 (defun server-goto-line-column (file-line-col)
299 (goto-line (nth 1 file-line-col))
300 (let ((column-number (nth 2 file-line-col)))
301 (if (> column-number 0)
302 (move-to-column (1- column-number)))))
304 (defun server-visit-files (files client &optional nowait)
305 "Finds FILES and returns the list CLIENT with the buffers nconc'd.
306 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
307 NOWAIT non-nil means this client is not waiting for the results,
308 so don't mark these buffers specially, just visit them normally."
309 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
310 (let (client-record (last-nonmenu-event t) (obuf (current-buffer)))
311 ;; Restore the current buffer afterward, but not using save-excursion,
312 ;; because we don't want to save point in this buffer
313 ;; if it happens to be one of those specified by the server.
316 ;; If there is an existing buffer modified or the file is
317 ;; modified, revert it. If there is an existing buffer with
318 ;; deleted file, offer to write it.
319 (let* ((filen (car (car files)))
320 (obuf (get-file-buffer filen)))
321 (push filen file-name-history)
322 (if (and obuf (set-buffer obuf))
324 (cond ((file-exists-p filen)
325 (if (not (verify-visited-file-modtime obuf))
326 (revert-buffer t nil)))
329 (concat "File no longer exists: "
331 ", write buffer to file? "))
332 (write-file filen))))
333 (setq server-existing-buffer t)
334 (server-goto-line-column (car files)))
335 (set-buffer (find-file-noselect filen))
336 (server-goto-line-column (car files))
337 (run-hooks 'server-visit-hook)))
339 (setq server-buffer-clients
340 (cons (car client) server-buffer-clients)))
341 (setq client-record (cons (current-buffer) client-record))
342 (setq files (cdr files)))
344 (nconc client client-record)))
346 (defun server-buffer-done (buffer &optional for-killing)
347 "Mark BUFFER as \"done\" for its client(s).
348 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
349 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
350 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
352 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
353 (let ((next-buffer nil)
355 (old-clients server-clients))
357 (let ((client (car old-clients)))
359 (setq next-buffer (nth 1 (memq buffer client))))
361 ;; Delete all dead buffers from CLIENT.
364 (and (bufferp (car tail))
365 (null (buffer-name (car tail)))
366 (delq (car tail) client))
367 (setq tail (cdr tail))))
368 ;; If client now has no pending buffers,
369 ;; tell it that it is done, and forget it entirely.
371 (delete-process (car client))
372 (server-log "Close" (car client))
373 (setq server-clients (delq client server-clients))))
374 (setq old-clients (cdr old-clients)))
375 (if (and (bufferp buffer) (buffer-name buffer))
376 ;; We may or may not kill this buffer;
377 ;; if we do, do not call server-buffer-done recursively
378 ;; from kill-buffer-hook.
379 (let ((server-kill-buffer-running t))
382 (setq server-buffer-clients nil)
383 (run-hooks 'server-done-hook))
384 ;; Notice whether server-done-hook killed the buffer.
385 (if (null (buffer-name buffer))
387 ;; Don't bother killing or burying the buffer
388 ;; when we are called from kill-buffer.
390 (when (and (not killed)
391 server-kill-new-buffers
392 (with-current-buffer buffer
393 (not server-existing-buffer)))
396 (kill-buffer buffer))
398 (if (server-temp-file-p buffer)
402 (bury-buffer buffer)))))))
403 (list next-buffer killed)))
405 (defun server-temp-file-p (buffer)
406 "Return non-nil if BUFFER contains a file considered temporary.
407 These are files whose names suggest they are repeatedly
408 reused to pass information to another program.
410 The variable `server-temp-file-regexp' controls which filenames
411 are considered temporary."
412 (and (buffer-file-name buffer)
413 (string-match server-temp-file-regexp (buffer-file-name buffer))))
415 (defun server-done ()
416 "Offer to save current buffer, mark it as \"done\" for clients.
417 This kills or buries the buffer, then returns a list
418 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
419 as a suggestion for what to select next, or nil.
420 KILLED is t if we killed BUFFER, which happens if it was created
421 specifically for the clients and did not exist before their request for it."
422 (let ((buffer (current-buffer)))
423 (if server-buffer-clients
425 (if (server-temp-file-p buffer)
426 ;; For a temp file, save, and do make a non-numeric backup
427 ;; (unless make-backup-files is nil).
428 (let ((version-control nil)
429 (buffer-backed-up nil))
431 (if (and (buffer-modified-p)
433 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
435 (server-buffer-done buffer)))))
437 ;; Ask before killing a server buffer.
438 ;; It was suggested to release its client instead,
439 ;; but I think that is dangerous--the client would proceed
440 ;; using whatever is on disk in that file. -- rms.
441 (defun server-kill-buffer-query-function ()
442 (or (not server-buffer-clients)
443 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
444 (buffer-name (current-buffer))))))
446 (add-hook 'kill-buffer-query-functions
447 'server-kill-buffer-query-function)
449 (defun server-kill-emacs-query-function ()
451 (tail server-clients))
452 ;; See if any clients have any buffers that are still alive.
454 (if (memq t (mapcar 'stringp (mapcar 'buffer-name (cdr (car tail)))))
455 (setq live-client t))
456 (setq tail (cdr tail)))
457 (or (not live-client)
458 (yes-or-no-p "Server buffers still have clients; exit anyway? "))))
460 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
462 (defvar server-kill-buffer-running nil
463 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
465 ;; When a buffer is killed, inform the clients.
466 (add-hook 'kill-buffer-hook 'server-kill-buffer)
467 (defun server-kill-buffer ()
468 ;; Prevent infinite recursion if user has made server-done-hook
470 (or server-kill-buffer-running
471 (and server-buffer-clients
472 (let ((server-kill-buffer-running t))
474 (server-buffer-done (current-buffer) t))))))
476 (defun server-edit (&optional arg)
477 "Switch to next server editing buffer; say \"Done\" for current buffer.
478 If a server buffer is current, it is marked \"done\" and optionally saved.
479 The buffer is also killed if it did not exist before the clients asked for it.
480 When all of a client's buffers are marked as \"done\", the client is notified.
482 Temporary files such as MH <draft> files are always saved and backed up,
483 no questions asked. (The variable `make-backup-files', if nil, still
484 inhibits a backup; you can set it locally in a particular buffer to
485 prevent a backup for it.) The variable `server-temp-file-regexp' controls
486 which filenames are considered temporary.
488 If invoked with a prefix argument, or if there is no server process running,
489 starts server process and that is all. Invoked by \\[server-edit]."
493 (memq (process-status server-process) '(signal exit)))
495 (apply 'server-switch-buffer (server-done))))
497 (defun server-switch-buffer (&optional next-buffer killed-one)
498 "Switch to another buffer, preferably one that has a client.
499 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
500 ;; KILLED-ONE is t in a recursive call
501 ;; if we have already killed one temp-file server buffer.
502 ;; This means we should avoid the final "switch to some other buffer"
503 ;; since we've already effectively done that.
504 (if (null next-buffer)
506 (server-switch-buffer (nth 1 (car server-clients)) killed-one)
507 (unless (or killed-one (window-dedicated-p (selected-window)))
508 (switch-to-buffer (other-buffer))))
509 (if (not (buffer-name next-buffer))
510 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
511 ;; and try the next surviving server buffer.
512 (apply 'server-switch-buffer (server-buffer-done next-buffer))
513 ;; OK, we know next-buffer is live, let's display and select it.
514 (let ((win (get-buffer-window next-buffer 0)))
515 (if (and win (not server-window))
516 ;; The buffer is already displayed: just reuse the window.
517 (let ((frame (window-frame win)))
518 (if (eq (frame-visible-p frame) 'icon)
521 (set-buffer next-buffer))
522 ;; Otherwise, let's find an appropriate window.
523 (cond ((and (windowp server-window)
524 (window-live-p server-window))
525 (select-window server-window))
526 ((framep server-window)
527 (if (not (frame-live-p server-window))
528 (setq server-window (make-frame)))
529 (select-window (frame-selected-window server-window))))
530 (if (window-minibuffer-p (selected-window))
531 (select-window (next-window nil 'nomini 0)))
532 ;; Move to a non-dedicated window, if we have one.
533 (when (window-dedicated-p (selected-window))
534 (select-window (get-window-with-predicate
535 (lambda (w) (not (window-dedicated-p w)))
536 'nomini 'visible (selected-window))))
538 (switch-to-buffer next-buffer)
539 ;; After all the above, we might still have ended up with
540 ;; a minibuffer/dedicated-window (if there's no other).
541 (error (pop-to-buffer next-buffer))))))))
543 (global-set-key "\C-x#" 'server-edit)
545 (defun server-unload-hook ()
546 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
547 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
548 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
552 ;;; server.el ends here