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,01,02,2003
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 opens up a socket for communication with clients. If there are no
36 ;; client buffers to edit, server-edit acts like (switch-to-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-clients nil
104 "List of current server clients.
105 Each element is (CLIENTID BUFFERS...) where CLIENTID is a string
106 that can be given to the server process to identify a client.
107 When a buffer is marked as \"done\", it is removed from this list.")
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
)
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.
123 It is not meaningful to set this to a specific frame or window with Custom.
124 Only programs can do so."
127 :type
'(choice (const :tag
"Use selected window"
128 :match
(lambda (widget value
)
129 (not (functionp value
)))
131 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
132 (function :tag
"Other function")))
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."
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
153 (or (assq 'server-buffer-clients minor-mode-alist
)
154 (setq minor-mode-alist
(cons '(server-buffer-clients " Server") minor-mode-alist
)))
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
)
162 (defvar server-socket-name
163 (format "/tmp/emacs%d-%s/server" (user-uid)
164 (substring (system-name) 0 (string-match "\\." (system-name)))))
166 (defun server-log (string &optional client
)
167 "If a *server* buffer exists, write STRING to it for logging purposes."
168 (if (get-buffer "*server*")
169 (with-current-buffer "*server*"
170 (goto-char (point-max))
171 (insert (current-time-string)
172 (if client
(format " %s:" client
) " ")
174 (or (bolp) (newline)))))
176 (defun server-sentinel (proc msg
)
177 (let ((client (assq proc server-clients
)))
178 ;; Remove PROC from the list of clients.
180 (setq server-clients
(delq client server-clients
))
181 (dolist (buf (cdr client
))
182 (with-current-buffer buf
183 ;; Remove PROC from the clients of each buffer.
184 (setq server-buffer-clients
(delq proc server-buffer-clients
))
185 ;; Kill the buffer if necessary.
186 (when (and (null server-buffer-clients
)
187 (or (and server-kill-new-buffers
188 (not server-existing-buffer
))
189 (server-temp-file-p)))
190 (kill-buffer (current-buffer)))))))
191 (server-log (format "Status changed to %s" (process-status proc
)) proc
))
193 (defun server-select-display (display)
194 ;; If the current frame is on `display' we're all set.
195 (unless (equal (frame-parameter (selected-frame) 'display
) display
)
196 ;; Otherwise, look for an existing frame there and select it.
197 (dolist (frame (frame-list))
198 (when (equal (frame-parameter frame
'display
) display
)
199 (select-frame frame
)))
200 ;; If there's no frame on that display yet, create a dummy one
202 (unless (equal (frame-parameter (selected-frame) 'display
) display
)
204 (make-frame-on-display
206 ;; This frame is only there in place of an actual "current display"
207 ;; setting, so we want it to be as unobtrusive as possible. That's
208 ;; what the invisibility is for. The minibuffer setting is so that
209 ;; we don't end up displaying a buffer in it (which noone would
211 '((visibility . nil
) (minibuffer . only
)))))))
213 (defun server-unquote-arg (arg)
214 (replace-regexp-in-string
223 (defun server-ensure-safe-dir (dir)
224 "Make sure DIR is a directory with no race-condition issues.
225 Creates the directory if necessary and makes sure:
226 - there's no symlink involved
228 - it's not readable/writable by anybody else."
229 (setq dir
(directory-file-name dir
))
230 (let ((attrs (file-attributes dir
)))
232 (letf (((default-file-modes) ?
\700)) (make-directory dir
))
233 (setq attrs
(file-attributes dir
)))
234 ;; Check that it's safe for use.
235 (unless (and (eq t
(car attrs
)) (eq (nth 2 attrs
) (user-uid))
236 (zerop (logand ?
\077 (file-modes dir
))))
237 (error "The directory %s is unsafe" dir
))))
240 (defun server-start (&optional leave-dead
)
241 "Allow this Emacs process to be a server for client processes.
242 This starts a server communications subprocess through which
243 client \"editors\" can send your editing commands to this Emacs job.
244 To use the server, set up the program `emacsclient' in the
245 Emacs distribution as your standard \"editor\".
247 Prefix arg means just kill any existing server communications subprocess."
249 ;; Make sure there is a safe directory in which to place the socket.
250 (server-ensure-safe-dir (file-name-directory server-socket-name
))
253 (condition-case () (delete-process server-process
) (error nil
)))
254 ;; Delete the socket files made by previous server invocations.
255 (condition-case () (delete-file server-socket-name
) (error nil
))
256 ;; If this Emacs already had a server, clear out associated status.
257 (while server-clients
258 (let ((buffer (nth 1 (car server-clients
))))
259 (server-buffer-done buffer
)))
262 (server-log (message "Restarting server")))
263 (letf (((default-file-modes) ?
\700))
265 (make-network-process
266 :name
"server" :family
'local
:server t
:noquery t
267 :service server-socket-name
268 :sentinel
'server-sentinel
:filter
'server-process-filter
269 ;; We must receive file names without being decoded.
270 ;; Those are decoded by server-process-filter according
271 ;; to file-name-coding-system.
272 :coding
'raw-text
)))))
275 (define-minor-mode server-mode
277 With ARG, turn Server mode on if ARG is positive, off otherwise.
278 Server mode runs a process that accepts commands from the
279 `emacsclient' program. See `server-start' and Info node `Emacs server'."
283 ;; Fixme: Should this check for an existing server socket and do
284 ;; nothing if there is one (for multiple Emacs sessions)?
285 (server-start (not server-mode
)))
287 (defun server-process-filter (proc string
)
288 "Process a request from the server to edit some files.
289 PROC is the server process. Format of STRING is \"PATH PATH PATH... \\n\"."
290 (server-log string proc
)
291 (let ((prev (process-get proc
'previous-string
)))
293 (setq string
(concat prev string
))
294 (process-put proc
'previous-string nil
)))
295 ;; If the input is multiple lines,
296 ;; process each line individually.
297 (while (string-match "\n" string
)
298 (let ((request (substring string
0 (match-beginning 0)))
299 (coding-system (and default-enable-multibyte-characters
300 (or file-name-coding-system
301 default-file-name-coding-system
)))
306 ;; Remove this line from STRING.
307 (setq string
(substring string
(match-end 0)))
308 (setq client
(cons proc nil
))
309 (while (string-match "[^ ]* " request
)
310 (let ((arg (substring request
(match-beginning 0) (1- (match-end 0)))))
311 (setq request
(substring request
(match-end 0)))
313 ((equal "-nowait" arg
) (setq nowait t
))
314 ((equal "-eval" arg
) (setq eval t
))
315 ((and (equal "-display" arg
) (string-match "\\([^ ]*\\) " request
))
316 (let ((display (server-unquote-arg (match-string 1 request
))))
317 (setq request
(substring request
(match-end 0)))
319 (server-select-display display
)
320 (error (process-send-string proc
(nth 1 err
))
321 (setq request
"")))))
322 ;; ARG is a line number option.
323 ((string-match "\\`\\+[0-9]+\\'" arg
)
324 (setq lineno
(string-to-int (substring arg
1))))
325 ;; ARG is line number:column option.
326 ((string-match "\\`+\\([0-9]+\\):\\([0-9]+\\)\\'" arg
)
327 (setq lineno
(string-to-int (match-string 1 arg
))
328 columnno
(string-to-int (match-string 2 arg
))))
330 ;; Undo the quoting that emacsclient does
331 ;; for certain special characters.
332 (setq arg
(server-unquote-arg arg
))
333 ;; Now decode the file name if necessary.
335 (setq arg
(decode-coding-string arg coding-system
)))
337 (let ((v (eval (car (read-from-string arg
)))))
340 (let ((standard-output (current-buffer)))
342 (process-send-region proc
(point-min) (point-max))))))
343 ;; ARG is a file name.
344 ;; Collapse multiple slashes to single slashes.
345 (setq arg
(command-line-normalize-file-name arg
))
346 (push (list arg lineno columnno
) files
))
348 (setq columnno
0)))))
350 (run-hooks 'pre-command-hook
)
351 (server-visit-files files client nowait
)
352 (run-hooks 'post-command-hook
))
353 ;; CLIENT is now a list (CLIENTNUM BUFFERS...)
354 (if (null (cdr client
))
355 ;; This client is empty; get rid of it immediately.
357 (delete-process proc
)
358 (server-log "Close empty client" proc
))
359 ;; We visited some buffer for this client.
360 (or nowait
(push client server-clients
))
361 (unless (or isearch-mode
(minibufferp))
362 (server-switch-buffer (nth 1 client
))
363 (run-hooks 'server-switch-hook
)
365 (message (substitute-command-keys
366 "When done with a buffer, type \\[server-edit]")))))))
367 ;; Save for later any partial line that remains.
368 (when (> (length string
) 0)
369 (process-put proc
'previous-string string
)))
371 (defun server-goto-line-column (file-line-col)
372 (goto-line (nth 1 file-line-col
))
373 (let ((column-number (nth 2 file-line-col
)))
374 (if (> column-number
0)
375 (move-to-column (1- column-number
)))))
377 (defun server-visit-files (files client
&optional nowait
)
378 "Find FILES and return the list CLIENT with the buffers nconc'd.
379 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
380 NOWAIT non-nil means this client is not waiting for the results,
381 so don't mark these buffers specially, just visit them normally."
382 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
383 (let ((last-nonmenu-event t
) client-record
)
384 ;; Restore the current buffer afterward, but not using save-excursion,
385 ;; because we don't want to save point in this buffer
386 ;; if it happens to be one of those specified by the server.
389 ;; If there is an existing buffer modified or the file is
390 ;; modified, revert it. If there is an existing buffer with
391 ;; deleted file, offer to write it.
392 (let* ((filen (car file
))
393 (obuf (get-file-buffer filen
)))
394 (push filen file-name-history
)
395 (if (and obuf
(set-buffer obuf
))
397 (cond ((file-exists-p filen
)
398 (if (not (verify-visited-file-modtime obuf
))
399 (revert-buffer t nil
)))
402 (concat "File no longer exists: "
404 ", write buffer to file? "))
405 (write-file filen
))))
406 (setq server-existing-buffer t
)
407 (server-goto-line-column file
))
408 (set-buffer (find-file-noselect filen
))
409 (server-goto-line-column file
)
410 (run-hooks 'server-visit-hook
)))
412 ;; When the buffer is killed, inform the clients.
413 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
414 (push (car client
) server-buffer-clients
))
415 (push (current-buffer) client-record
)))
416 (nconc client client-record
)))
418 (defun server-buffer-done (buffer &optional for-killing
)
419 "Mark BUFFER as \"done\" for its client(s).
420 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
421 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
422 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
424 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
425 (let ((next-buffer nil
)
427 (old-clients server-clients
))
429 (let ((client (car old-clients
)))
431 (setq next-buffer
(nth 1 (memq buffer client
))))
433 ;; Delete all dead buffers from CLIENT.
436 (and (bufferp (car tail
))
437 (null (buffer-name (car tail
)))
438 (delq (car tail
) client
))
439 (setq tail
(cdr tail
))))
440 ;; If client now has no pending buffers,
441 ;; tell it that it is done, and forget it entirely.
443 (delete-process (car client
))
444 (server-log "Close" (car client
))
445 (setq server-clients
(delq client server-clients
))))
446 (setq old-clients
(cdr old-clients
)))
447 (if (and (bufferp buffer
) (buffer-name buffer
))
448 ;; We may or may not kill this buffer;
449 ;; if we do, do not call server-buffer-done recursively
450 ;; from kill-buffer-hook.
451 (let ((server-kill-buffer-running t
))
452 (with-current-buffer buffer
453 (setq server-buffer-clients nil
)
454 (run-hooks 'server-done-hook
))
455 ;; Notice whether server-done-hook killed the buffer.
456 (if (null (buffer-name buffer
))
458 ;; Don't bother killing or burying the buffer
459 ;; when we are called from kill-buffer.
461 (when (and (not killed
)
462 server-kill-new-buffers
463 (with-current-buffer buffer
464 (not server-existing-buffer
)))
467 (kill-buffer buffer
))
469 (if (server-temp-file-p buffer
)
473 (bury-buffer buffer
)))))))
474 (list next-buffer killed
)))
476 (defun server-temp-file-p (&optional buffer
)
477 "Return non-nil if BUFFER contains a file considered temporary.
478 These are files whose names suggest they are repeatedly
479 reused to pass information to another program.
481 The variable `server-temp-file-regexp' controls which filenames
482 are considered temporary."
483 (and (buffer-file-name buffer
)
484 (string-match server-temp-file-regexp
(buffer-file-name buffer
))))
486 (defun server-done ()
487 "Offer to save current buffer, mark it as \"done\" for clients.
488 This kills or buries the buffer, then returns a list
489 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
490 as a suggestion for what to select next, or nil.
491 KILLED is t if we killed BUFFER, which happens if it was created
492 specifically for the clients and did not exist before their request for it."
493 (when server-buffer-clients
494 (if (server-temp-file-p)
495 ;; For a temp file, save, and do make a non-numeric backup
496 ;; (unless make-backup-files is nil).
497 (let ((version-control nil
)
498 (buffer-backed-up nil
))
500 (if (and (buffer-modified-p)
502 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
504 (server-buffer-done (current-buffer))))
506 ;; Ask before killing a server buffer.
507 ;; It was suggested to release its client instead,
508 ;; but I think that is dangerous--the client would proceed
509 ;; using whatever is on disk in that file. -- rms.
510 (defun server-kill-buffer-query-function ()
511 (or (not server-buffer-clients
)
512 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
513 (buffer-name (current-buffer))))))
515 (add-hook 'kill-buffer-query-functions
516 'server-kill-buffer-query-function
)
518 (defun server-kill-emacs-query-function ()
520 (tail server-clients
))
521 ;; See if any clients have any buffers that are still alive.
523 (if (memq t
(mapcar 'stringp
(mapcar 'buffer-name
(cdr (car tail
)))))
524 (setq live-client t
))
525 (setq tail
(cdr tail
)))
526 (or (not live-client
)
527 (yes-or-no-p "Server buffers still have clients; exit anyway? "))))
529 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
531 (defvar server-kill-buffer-running nil
532 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
534 (defun server-kill-buffer ()
535 ;; Prevent infinite recursion if user has made server-done-hook
537 (or server-kill-buffer-running
538 (and server-buffer-clients
539 (let ((server-kill-buffer-running t
))
541 (server-buffer-done (current-buffer) t
))))))
543 (defun server-edit (&optional arg
)
544 "Switch to next server editing buffer; say \"Done\" for current buffer.
545 If a server buffer is current, it is marked \"done\" and optionally saved.
546 The buffer is also killed if it did not exist before the clients asked for it.
547 When all of a client's buffers are marked as \"done\", the client is notified.
549 Temporary files such as MH <draft> files are always saved and backed up,
550 no questions asked. (The variable `make-backup-files', if nil, still
551 inhibits a backup; you can set it locally in a particular buffer to
552 prevent a backup for it.) The variable `server-temp-file-regexp' controls
553 which filenames are considered temporary.
555 If invoked with a prefix argument, or if there is no server process running,
556 starts server process and that is all. Invoked by \\[server-edit]."
560 (memq (process-status server-process
) '(signal exit
)))
562 (apply 'server-switch-buffer
(server-done))))
564 (defun server-switch-buffer (&optional next-buffer killed-one
)
565 "Switch to another buffer, preferably one that has a client.
566 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
567 ;; KILLED-ONE is t in a recursive call
568 ;; if we have already killed one temp-file server buffer.
569 ;; This means we should avoid the final "switch to some other buffer"
570 ;; since we've already effectively done that.
571 (if (null next-buffer
)
573 (server-switch-buffer (nth 1 (car server-clients
)) killed-one
)
574 (unless (or killed-one
(window-dedicated-p (selected-window)))
575 (switch-to-buffer (other-buffer))
576 (message "No server buffers remain to edit")))
577 (if (not (buffer-name next-buffer
))
578 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
579 ;; and try the next surviving server buffer.
580 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
581 ;; OK, we know next-buffer is live, let's display and select it.
582 (if (functionp server-window
)
583 (funcall server-window next-buffer
)
584 (let ((win (get-buffer-window next-buffer
0)))
585 (if (and win
(not server-window
))
586 ;; The buffer is already displayed: just reuse the window.
587 (let ((frame (window-frame win
)))
588 (if (eq (frame-visible-p frame
) 'icon
)
591 (set-buffer next-buffer
))
592 ;; Otherwise, let's find an appropriate window.
593 (cond ((and (windowp server-window
)
594 (window-live-p server-window
))
595 (select-window server-window
))
596 ((framep server-window
)
597 (if (not (frame-live-p server-window
))
598 (setq server-window
(make-frame)))
599 (select-window (frame-selected-window server-window
))))
600 (if (window-minibuffer-p (selected-window))
601 (select-window (next-window nil
'nomini
0)))
602 ;; Move to a non-dedicated window, if we have one.
603 (when (window-dedicated-p (selected-window))
605 (get-window-with-predicate
607 (and (not (window-dedicated-p w
))
608 (equal (frame-parameter (window-frame w
) 'display
)
609 (frame-parameter (selected-frame) 'display
))))
610 'nomini
'visible
(selected-window))))
612 (switch-to-buffer next-buffer
)
613 ;; After all the above, we might still have ended up with
614 ;; a minibuffer/dedicated-window (if there's no other).
615 (error (pop-to-buffer next-buffer
)))))))))
617 (global-set-key "\C-x#" 'server-edit
)
619 (defun server-unload-hook ()
621 (remove-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
622 (remove-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
623 (remove-hook 'kill-buffer-hook
'server-kill-buffer
))
627 ;;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
628 ;;; server.el ends here