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,03,2004
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-name
"server")
164 (defvar server-socket-dir
165 (format "/tmp/emacs%d" (user-uid)))
167 (defun server-log (string &optional client
)
168 "If a *server* buffer exists, write STRING to it for logging purposes."
169 (if (get-buffer "*server*")
170 (with-current-buffer "*server*"
171 (goto-char (point-max))
172 (insert (current-time-string)
173 (if client
(format " %s:" client
) " ")
175 (or (bolp) (newline)))))
177 (defun server-sentinel (proc msg
)
178 (let ((client (assq proc server-clients
)))
179 ;; Remove PROC from the list of clients.
181 (setq server-clients
(delq client server-clients
))
182 (dolist (buf (cdr client
))
183 (with-current-buffer buf
184 ;; Remove PROC from the clients of each buffer.
185 (setq server-buffer-clients
(delq proc server-buffer-clients
))
186 ;; Kill the buffer if necessary.
187 (when (and (null server-buffer-clients
)
188 (or (and server-kill-new-buffers
189 (not server-existing-buffer
))
190 (server-temp-file-p)))
191 (kill-buffer (current-buffer)))))))
192 (server-log (format "Status changed to %s" (process-status proc
)) proc
))
194 (defun server-select-display (display)
195 ;; If the current frame is on `display' we're all set.
196 (unless (equal (frame-parameter (selected-frame) 'display
) display
)
197 ;; Otherwise, look for an existing frame there and select it.
198 (dolist (frame (frame-list))
199 (when (equal (frame-parameter frame
'display
) display
)
200 (select-frame frame
)))
201 ;; If there's no frame on that display yet, create a dummy one
203 (unless (equal (frame-parameter (selected-frame) 'display
) display
)
205 (make-frame-on-display
207 ;; This frame is only there in place of an actual "current display"
208 ;; setting, so we want it to be as unobtrusive as possible. That's
209 ;; what the invisibility is for. The minibuffer setting is so that
210 ;; we don't end up displaying a buffer in it (which noone would
212 '((visibility . nil
) (minibuffer . only
)))))))
214 (defun server-unquote-arg (arg)
215 (replace-regexp-in-string
224 (defun server-ensure-safe-dir (dir)
225 "Make sure DIR is a directory with no race-condition issues.
226 Creates the directory if necessary and makes sure:
227 - there's no symlink involved
229 - it's not readable/writable by anybody else."
230 (setq dir
(directory-file-name dir
))
231 (let ((attrs (file-attributes dir
)))
233 (letf (((default-file-modes) ?
\700)) (make-directory dir
))
234 (setq attrs
(file-attributes dir
)))
235 ;; Check that it's safe for use.
236 (unless (and (eq t
(car attrs
)) (eq (nth 2 attrs
) (user-uid))
237 (zerop (logand ?
\077 (file-modes dir
))))
238 (error "The directory %s is unsafe" dir
))))
241 (defun server-start (&optional leave-dead
)
242 "Allow this Emacs process to be a server for client processes.
243 This starts a server communications subprocess through which
244 client \"editors\" can send your editing commands to this Emacs job.
245 To use the server, set up the program `emacsclient' in the
246 Emacs distribution as your standard \"editor\".
248 Prefix arg means just kill any existing server communications subprocess."
250 ;; Make sure there is a safe directory in which to place the socket.
251 (server-ensure-safe-dir server-socket-dir
)
254 (condition-case () (delete-process server-process
) (error nil
)))
255 ;; Delete the socket files made by previous server invocations.
257 (delete-file (expand-file-name server-name server-socket-dir
))
259 ;; If this Emacs already had a server, clear out associated status.
260 (while server-clients
261 (let ((buffer (nth 1 (car server-clients
))))
262 (server-buffer-done buffer
)))
265 (server-log (message "Restarting server")))
266 (letf (((default-file-modes) ?
\700))
268 (make-network-process
269 :name
"server" :family
'local
:server t
:noquery t
270 :service
(expand-file-name server-name server-socket-dir
)
271 :sentinel
'server-sentinel
:filter
'server-process-filter
272 ;; We must receive file names without being decoded.
273 ;; Those are decoded by server-process-filter according
274 ;; to file-name-coding-system.
275 :coding
'raw-text
)))))
278 (define-minor-mode server-mode
280 With ARG, turn Server mode on if ARG is positive, off otherwise.
281 Server mode runs a process that accepts commands from the
282 `emacsclient' program. See `server-start' and Info node `Emacs server'."
286 ;; Fixme: Should this check for an existing server socket and do
287 ;; nothing if there is one (for multiple Emacs sessions)?
288 (server-start (not server-mode
)))
290 (defun server-process-filter (proc string
)
291 "Process a request from the server to edit some files.
292 PROC is the server process. Format of STRING is \"PATH PATH PATH... \\n\"."
293 (server-log string proc
)
294 (let ((prev (process-get proc
'previous-string
)))
296 (setq string
(concat prev string
))
297 (process-put proc
'previous-string nil
)))
298 ;; If the input is multiple lines,
299 ;; process each line individually.
300 (while (string-match "\n" string
)
301 (let ((request (substring string
0 (match-beginning 0)))
302 (coding-system (and default-enable-multibyte-characters
303 (or file-name-coding-system
304 default-file-name-coding-system
)))
308 (tmp-frame nil
) ; Sometimes used to embody the selected display.
310 ;; Remove this line from STRING.
311 (setq string
(substring string
(match-end 0)))
312 (setq client
(cons proc nil
))
313 (while (string-match "[^ ]* " request
)
314 (let ((arg (substring request
(match-beginning 0) (1- (match-end 0)))))
315 (setq request
(substring request
(match-end 0)))
317 ((equal "-nowait" arg
) (setq nowait t
))
318 ((equal "-eval" arg
) (setq eval t
))
319 ((and (equal "-display" arg
) (string-match "\\([^ ]*\\) " request
))
320 (let ((display (server-unquote-arg (match-string 1 request
))))
321 (setq request
(substring request
(match-end 0)))
323 (setq tmp-frame
(server-select-display display
))
324 (error (process-send-string proc
(nth 1 err
))
325 (setq request
"")))))
326 ;; ARG is a line number option.
327 ((string-match "\\`\\+[0-9]+\\'" arg
)
328 (setq lineno
(string-to-int (substring arg
1))))
329 ;; ARG is line number:column option.
330 ((string-match "\\`+\\([0-9]+\\):\\([0-9]+\\)\\'" arg
)
331 (setq lineno
(string-to-int (match-string 1 arg
))
332 columnno
(string-to-int (match-string 2 arg
))))
334 ;; Undo the quoting that emacsclient does
335 ;; for certain special characters.
336 (setq arg
(server-unquote-arg arg
))
337 ;; Now decode the file name if necessary.
339 (setq arg
(decode-coding-string arg coding-system
)))
341 (let ((v (eval (car (read-from-string arg
)))))
344 (let ((standard-output (current-buffer)))
346 ;; Suppress the error rose when the pipe to PROC is closed.
348 (process-send-region proc
(point-min) (point-max))
351 ;; ARG is a file name.
352 ;; Collapse multiple slashes to single slashes.
353 (setq arg
(command-line-normalize-file-name arg
))
354 (push (list arg lineno columnno
) files
))
356 (setq columnno
0)))))
358 (run-hooks 'pre-command-hook
)
359 (server-visit-files files client nowait
)
360 (run-hooks 'post-command-hook
))
361 ;; CLIENT is now a list (CLIENTNUM BUFFERS...)
362 (if (null (cdr client
))
363 ;; This client is empty; get rid of it immediately.
365 (delete-process proc
)
366 (server-log "Close empty client" proc
))
367 ;; We visited some buffer for this client.
368 (or nowait
(push client server-clients
))
369 (unless (or isearch-mode
(minibufferp))
370 (server-switch-buffer (nth 1 client
))
371 (run-hooks 'server-switch-hook
)
373 (message (substitute-command-keys
374 "When done with a buffer, type \\[server-edit]")))))
375 ;; Avoid preserving the connection after the last real frame is deleted.
376 (if tmp-frame
(delete-frame tmp-frame
))))
377 ;; Save for later any partial line that remains.
378 (when (> (length string
) 0)
379 (process-put proc
'previous-string string
)))
381 (defun server-goto-line-column (file-line-col)
382 (goto-line (nth 1 file-line-col
))
383 (let ((column-number (nth 2 file-line-col
)))
384 (if (> column-number
0)
385 (move-to-column (1- column-number
)))))
387 (defun server-visit-files (files client
&optional nowait
)
388 "Find FILES and return the list CLIENT with the buffers nconc'd.
389 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
390 NOWAIT non-nil means this client is not waiting for the results,
391 so don't mark these buffers specially, just visit them normally."
392 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
393 (let ((last-nonmenu-event t
) client-record
)
394 ;; Restore the current buffer afterward, but not using save-excursion,
395 ;; because we don't want to save point in this buffer
396 ;; if it happens to be one of those specified by the server.
399 ;; If there is an existing buffer modified or the file is
400 ;; modified, revert it. If there is an existing buffer with
401 ;; deleted file, offer to write it.
402 (let* ((filen (car file
))
403 (obuf (get-file-buffer filen
)))
404 (push filen file-name-history
)
405 (if (and obuf
(set-buffer obuf
))
407 (cond ((file-exists-p filen
)
408 (if (not (verify-visited-file-modtime obuf
))
409 (revert-buffer t nil
)))
412 (concat "File no longer exists: "
414 ", write buffer to file? "))
415 (write-file filen
))))
416 (setq server-existing-buffer t
)
417 (server-goto-line-column file
))
418 (set-buffer (find-file-noselect filen
))
419 (server-goto-line-column file
)
420 (run-hooks 'server-visit-hook
)))
422 ;; When the buffer is killed, inform the clients.
423 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
424 (push (car client
) server-buffer-clients
))
425 (push (current-buffer) client-record
)))
426 (nconc client client-record
)))
428 (defun server-buffer-done (buffer &optional for-killing
)
429 "Mark BUFFER as \"done\" for its client(s).
430 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
431 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
432 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
434 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
435 (let ((next-buffer nil
)
437 (old-clients server-clients
))
439 (let ((client (car old-clients
)))
441 (setq next-buffer
(nth 1 (memq buffer client
))))
443 ;; Delete all dead buffers from CLIENT.
446 (and (bufferp (car tail
))
447 (null (buffer-name (car tail
)))
448 (delq (car tail
) client
))
449 (setq tail
(cdr tail
))))
450 ;; If client now has no pending buffers,
451 ;; tell it that it is done, and forget it entirely.
453 (delete-process (car client
))
454 (server-log "Close" (car client
))
455 (setq server-clients
(delq client server-clients
))))
456 (setq old-clients
(cdr old-clients
)))
457 (if (and (bufferp buffer
) (buffer-name buffer
))
458 ;; We may or may not kill this buffer;
459 ;; if we do, do not call server-buffer-done recursively
460 ;; from kill-buffer-hook.
461 (let ((server-kill-buffer-running t
))
462 (with-current-buffer buffer
463 (setq server-buffer-clients nil
)
464 (run-hooks 'server-done-hook
))
465 ;; Notice whether server-done-hook killed the buffer.
466 (if (null (buffer-name buffer
))
468 ;; Don't bother killing or burying the buffer
469 ;; when we are called from kill-buffer.
471 (when (and (not killed
)
472 server-kill-new-buffers
473 (with-current-buffer buffer
474 (not server-existing-buffer
)))
477 (kill-buffer buffer
))
479 (if (server-temp-file-p buffer
)
483 (bury-buffer buffer
)))))))
484 (list next-buffer killed
)))
486 (defun server-temp-file-p (&optional buffer
)
487 "Return non-nil if BUFFER contains a file considered temporary.
488 These are files whose names suggest they are repeatedly
489 reused to pass information to another program.
491 The variable `server-temp-file-regexp' controls which filenames
492 are considered temporary."
493 (and (buffer-file-name buffer
)
494 (string-match server-temp-file-regexp
(buffer-file-name buffer
))))
496 (defun server-done ()
497 "Offer to save current buffer, mark it as \"done\" for clients.
498 This kills or buries the buffer, then returns a list
499 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
500 as a suggestion for what to select next, or nil.
501 KILLED is t if we killed BUFFER, which happens if it was created
502 specifically for the clients and did not exist before their request for it."
503 (when server-buffer-clients
504 (if (server-temp-file-p)
505 ;; For a temp file, save, and do make a non-numeric backup
506 ;; (unless make-backup-files is nil).
507 (let ((version-control nil
)
508 (buffer-backed-up nil
))
510 (if (and (buffer-modified-p)
512 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
514 (server-buffer-done (current-buffer))))
516 ;; Ask before killing a server buffer.
517 ;; It was suggested to release its client instead,
518 ;; but I think that is dangerous--the client would proceed
519 ;; using whatever is on disk in that file. -- rms.
520 (defun server-kill-buffer-query-function ()
521 (or (not server-buffer-clients
)
522 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
523 (buffer-name (current-buffer))))))
525 (add-hook 'kill-buffer-query-functions
526 'server-kill-buffer-query-function
)
528 (defun server-kill-emacs-query-function ()
530 (tail server-clients
))
531 ;; See if any clients have any buffers that are still alive.
533 (if (memq t
(mapcar 'stringp
(mapcar 'buffer-name
(cdr (car tail
)))))
534 (setq live-client t
))
535 (setq tail
(cdr tail
)))
536 (or (not live-client
)
537 (yes-or-no-p "Server buffers still have clients; exit anyway? "))))
539 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
541 (defvar server-kill-buffer-running nil
542 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
544 (defun server-kill-buffer ()
545 ;; Prevent infinite recursion if user has made server-done-hook
547 (or server-kill-buffer-running
548 (and server-buffer-clients
549 (let ((server-kill-buffer-running t
))
551 (server-buffer-done (current-buffer) t
))))))
553 (defun server-edit (&optional arg
)
554 "Switch to next server editing buffer; say \"Done\" for current buffer.
555 If a server buffer is current, it is marked \"done\" and optionally saved.
556 The buffer is also killed if it did not exist before the clients asked for it.
557 When all of a client's buffers are marked as \"done\", the client is notified.
559 Temporary files such as MH <draft> files are always saved and backed up,
560 no questions asked. (The variable `make-backup-files', if nil, still
561 inhibits a backup; you can set it locally in a particular buffer to
562 prevent a backup for it.) The variable `server-temp-file-regexp' controls
563 which filenames are considered temporary.
565 If invoked with a prefix argument, or if there is no server process running,
566 starts server process and that is all. Invoked by \\[server-edit]."
570 (memq (process-status server-process
) '(signal exit
)))
572 (apply 'server-switch-buffer
(server-done))))
574 (defun server-switch-buffer (&optional next-buffer killed-one
)
575 "Switch to another buffer, preferably one that has a client.
576 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it."
577 ;; KILLED-ONE is t in a recursive call
578 ;; if we have already killed one temp-file server buffer.
579 ;; This means we should avoid the final "switch to some other buffer"
580 ;; since we've already effectively done that.
581 (if (null next-buffer
)
583 (server-switch-buffer (nth 1 (car server-clients
)) killed-one
)
584 (unless (or killed-one
(window-dedicated-p (selected-window)))
585 (switch-to-buffer (other-buffer))
586 (message "No server buffers remain to edit")))
587 (if (not (buffer-name next-buffer
))
588 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
589 ;; and try the next surviving server buffer.
590 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
591 ;; OK, we know next-buffer is live, let's display and select it.
592 (if (functionp server-window
)
593 (funcall server-window next-buffer
)
594 (let ((win (get-buffer-window next-buffer
0)))
595 (if (and win
(not server-window
))
596 ;; The buffer is already displayed: just reuse the window.
597 (let ((frame (window-frame win
)))
598 (if (eq (frame-visible-p frame
) 'icon
)
601 (set-buffer next-buffer
))
602 ;; Otherwise, let's find an appropriate window.
603 (cond ((and (windowp server-window
)
604 (window-live-p server-window
))
605 (select-window server-window
))
606 ((framep server-window
)
607 (if (not (frame-live-p server-window
))
608 (setq server-window
(make-frame)))
609 (select-window (frame-selected-window server-window
))))
610 (if (window-minibuffer-p (selected-window))
611 (select-window (next-window nil
'nomini
0)))
612 ;; Move to a non-dedicated window, if we have one.
613 (when (window-dedicated-p (selected-window))
615 (get-window-with-predicate
617 (and (not (window-dedicated-p w
))
618 (equal (frame-parameter (window-frame w
) 'display
)
619 (frame-parameter (selected-frame) 'display
))))
620 'nomini
'visible
(selected-window))))
622 (switch-to-buffer next-buffer
)
623 ;; After all the above, we might still have ended up with
624 ;; a minibuffer/dedicated-window (if there's no other).
625 (error (pop-to-buffer next-buffer
)))))))))
627 (global-set-key "\C-x#" 'server-edit
)
629 (defun server-unload-hook ()
631 (remove-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
632 (remove-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
633 (remove-hook 'kill-buffer-hook
'server-kill-buffer
))
635 (add-hook 'server-unload-hook
'server-unload-hook
)
639 ;;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
640 ;;; server.el ends here