Merge from emacs-23
[emacs.git] / lisp / server.el
blobe3af82231aeb5711b67bff8987b87f1dc4245ab6
1 ;;; server.el --- Lisp code for GNU Emacs running as server process
3 ;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 ;; 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
7 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
8 ;; Maintainer: FSF
9 ;; Keywords: processes
11 ;; Changes by peck@sun.com and by rms.
12 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
14 ;; This file is part of GNU Emacs.
16 ;; GNU Emacs is free software: you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
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
37 ;; (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.
77 ;; Todo:
79 ;; - handle command-line-args-left.
80 ;; - move most of the args processing and decision making from emacsclient.c
81 ;; to here.
82 ;; - fix up handling of the client's environment (place it in the terminal?).
84 ;;; Code:
86 (eval-when-compile (require 'cl))
88 (defgroup server nil
89 "Emacs running as a server process."
90 :group 'external)
92 (defcustom server-use-tcp nil
93 "If non-nil, use TCP sockets instead of local sockets."
94 :set #'(lambda (sym val)
95 (unless (featurep 'make-network-process '(:family local))
96 (setq val t)
97 (unless load-in-progress
98 (message "Local sockets unsupported, using TCP sockets")))
99 (when val (random t))
100 (set-default sym val))
101 :group 'server
102 :type 'boolean
103 :version "22.1")
105 (defcustom server-host nil
106 "The name or IP address to use as host address of the server process.
107 If set, the server accepts remote connections; otherwise it is local."
108 :group 'server
109 :type '(choice
110 (string :tag "Name or IP address")
111 (const :tag "Local" nil))
112 :version "22.1")
113 ;;;###autoload
114 (put 'server-host 'risky-local-variable t)
116 (defcustom server-port nil
117 "The port number that the server process should listen on."
118 :group 'server
119 :type '(choice
120 (string :tag "Port number")
121 (const :tag "Random" nil))
122 :version "24.1")
123 ;;;###autoload
124 (put 'server-port 'risky-local-variable t)
126 (defcustom server-auth-dir (locate-user-emacs-file "server/")
127 "Directory for server authentication files.
129 NOTE: On FAT32 filesystems, directories are not secure;
130 files can be read and modified by any user or process.
131 It is strongly suggested to set `server-auth-dir' to a
132 directory residing in a NTFS partition instead."
133 :group 'server
134 :type 'directory
135 :version "22.1")
136 ;;;###autoload
137 (put 'server-auth-dir 'risky-local-variable t)
139 (defcustom server-raise-frame t
140 "If non-nil, raise frame when switching to a buffer."
141 :group 'server
142 :type 'boolean
143 :version "22.1")
145 (defcustom server-visit-hook nil
146 "Hook run when visiting a file for the Emacs server."
147 :group 'server
148 :type 'hook)
150 (defcustom server-switch-hook nil
151 "Hook run when switching to a buffer for the Emacs server."
152 :group 'server
153 :type 'hook)
155 (defcustom server-done-hook nil
156 "Hook run when done editing a buffer for the Emacs server."
157 :group 'server
158 :type 'hook)
160 (defvar server-process nil
161 "The current server process.")
163 (defvar server-clients nil
164 "List of current server clients.
165 Each element is a process.")
167 (defvar server-buffer-clients nil
168 "List of client processes requesting editing of current buffer.")
169 (make-variable-buffer-local 'server-buffer-clients)
170 ;; Changing major modes should not erase this local.
171 (put 'server-buffer-clients 'permanent-local t)
173 (defcustom server-window nil
174 "Specification of the window to use for selecting Emacs server buffers.
175 If nil, use the selected window.
176 If it is a function, it should take one argument (a buffer) and
177 display and select it. A common value is `pop-to-buffer'.
178 If it is a window, use that.
179 If it is a frame, use the frame's selected window.
181 It is not meaningful to set this to a specific frame or window with Custom.
182 Only programs can do so."
183 :group 'server
184 :version "22.1"
185 :type '(choice (const :tag "Use selected window"
186 :match (lambda (widget value)
187 (not (functionp value)))
188 nil)
189 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
190 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
191 (function :tag "Other function")))
193 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
194 "Regexp matching names of temporary files.
195 These are deleted and reused after each edit by the programs that
196 invoke the Emacs server."
197 :group 'server
198 :type 'regexp)
200 (defcustom server-kill-new-buffers t
201 "Whether to kill buffers when done with them.
202 If non-nil, kill a buffer unless it already existed before editing
203 it with the Emacs server. If nil, kill only buffers as specified by
204 `server-temp-file-regexp'.
205 Please note that only buffers that still have a client are killed,
206 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
207 in this way."
208 :group 'server
209 :type 'boolean
210 :version "21.1")
212 (or (assq 'server-buffer-clients minor-mode-alist)
213 (push '(server-buffer-clients " Server") minor-mode-alist))
215 (defvar server-existing-buffer nil
216 "Non-nil means the buffer existed before the server was asked to visit it.
217 This means that the server should not kill the buffer when you say you
218 are done with it in the server.")
219 (make-variable-buffer-local 'server-existing-buffer)
221 (defcustom server-name "server"
222 "The name of the Emacs server, if this Emacs process creates one.
223 The command `server-start' makes use of this. It should not be
224 changed while a server is running."
225 :group 'server
226 :type 'string
227 :version "23.1")
229 ;; We do not use `temporary-file-directory' here, because emacsclient
230 ;; does not read the init file.
231 (defvar server-socket-dir
232 (and (featurep 'make-network-process '(:family local))
233 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
234 "The directory in which to place the server socket.
235 If local sockets are not supported, this is nil.")
237 (defun server-clients-with (property value)
238 "Return a list of clients with PROPERTY set to VALUE."
239 (let (result)
240 (dolist (proc server-clients result)
241 (when (equal value (process-get proc property))
242 (push proc result)))))
244 (defun server-add-client (proc)
245 "Create a client for process PROC, if it doesn't already have one.
246 New clients have no properties."
247 (add-to-list 'server-clients proc))
249 (defmacro server-with-environment (env vars &rest body)
250 "Evaluate BODY with environment variables VARS set to those in ENV.
251 The environment variables are then restored to their previous values.
253 VARS should be a list of strings.
254 ENV should be in the same format as `process-environment'."
255 (declare (indent 2))
256 (let ((var (make-symbol "var"))
257 (value (make-symbol "value")))
258 `(let ((process-environment process-environment))
259 (dolist (,var ,vars)
260 (let ((,value (getenv-internal ,var ,env)))
261 (push (if (stringp ,value)
262 (concat ,var "=" ,value)
263 ,var)
264 process-environment)))
265 (progn ,@body))))
267 (defun server-delete-client (proc &optional noframe)
268 "Delete PROC, including its buffers, terminals and frames.
269 If NOFRAME is non-nil, let the frames live.
270 Updates `server-clients'."
271 (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
272 ;; Force a new lookup of client (prevents infinite recursion).
273 (when (memq proc server-clients)
274 (let ((buffers (process-get proc 'buffers)))
276 ;; Kill the client's buffers.
277 (dolist (buf buffers)
278 (when (buffer-live-p buf)
279 (with-current-buffer buf
280 ;; Kill the buffer if necessary.
281 (when (and (equal server-buffer-clients
282 (list proc))
283 (or (and server-kill-new-buffers
284 (not server-existing-buffer))
285 (server-temp-file-p))
286 (not (buffer-modified-p)))
287 (let (flag)
288 (unwind-protect
289 (progn (setq server-buffer-clients nil)
290 (kill-buffer (current-buffer))
291 (setq flag t))
292 (unless flag
293 ;; Restore clients if user pressed C-g in `kill-buffer'.
294 (setq server-buffer-clients (list proc)))))))))
296 ;; Delete the client's frames.
297 (unless noframe
298 (dolist (frame (frame-list))
299 (when (and (frame-live-p frame)
300 (equal proc (frame-parameter frame 'client)))
301 ;; Prevent `server-handle-delete-frame' from calling us
302 ;; recursively.
303 (set-frame-parameter frame 'client nil)
304 (delete-frame frame))))
306 (setq server-clients (delq proc server-clients))
308 ;; Delete the client's tty.
309 (let ((terminal (process-get proc 'terminal)))
310 ;; Only delete the terminal if it is non-nil.
311 (when (and terminal (eq (terminal-live-p terminal) t))
312 (delete-terminal terminal)))
314 ;; Delete the client's process.
315 (if (eq (process-status proc) 'open)
316 (delete-process proc))
318 (server-log "Deleted" proc))))
320 (defvar server-log-time-function 'current-time-string
321 "Function to generate timestamps for `server-buffer'.")
323 (defconst server-buffer " *server*"
324 "Buffer used internally by Emacs's server.
325 One use is to log the I/O for debugging purposes (see `server-log'),
326 the other is to provide a current buffer in which the process filter can
327 safely let-bind buffer-local variables like `default-directory'.")
329 (defvar server-log nil
330 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
332 (defun server-log (string &optional client)
333 "If `server-log' is non-nil, log STRING to `server-buffer'.
334 If CLIENT is non-nil, add a description of it to the logged message."
335 (when server-log
336 (with-current-buffer (get-buffer-create server-buffer)
337 (goto-char (point-max))
338 (insert (funcall server-log-time-function)
339 (cond
340 ((null client) " ")
341 ((listp client) (format " %s: " (car client)))
342 (t (format " %s: " client)))
343 string)
344 (or (bolp) (newline)))))
346 (defun server-sentinel (proc msg)
347 "The process sentinel for Emacs server connections."
348 ;; If this is a new client process, set the query-on-exit flag to nil
349 ;; for this process (it isn't inherited from the server process).
350 (when (and (eq (process-status proc) 'open)
351 (process-query-on-exit-flag proc))
352 (set-process-query-on-exit-flag proc nil))
353 ;; Delete the associated connection file, if applicable.
354 ;; Although there's no 100% guarantee that the file is owned by the
355 ;; running Emacs instance, server-start uses server-running-p to check
356 ;; for possible servers before doing anything, so it *should* be ours.
357 (and (process-contact proc :server)
358 (eq (process-status proc) 'closed)
359 (ignore-errors
360 (delete-file (process-get proc :server-file))))
361 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
362 (server-delete-client proc))
364 (defun server-select-display (display)
365 ;; If the current frame is on `display' we're all set.
366 ;; Similarly if we are unable to open frames on other displays, there's
367 ;; nothing more we can do.
368 (unless (or (not (fboundp 'make-frame-on-display))
369 (equal (frame-parameter (selected-frame) 'display) display))
370 ;; Otherwise, look for an existing frame there and select it.
371 (dolist (frame (frame-list))
372 (when (equal (frame-parameter frame 'display) display)
373 (select-frame frame)))
374 ;; If there's no frame on that display yet, create and select one.
375 (unless (equal (frame-parameter (selected-frame) 'display) display)
376 (let* ((buffer (generate-new-buffer " *server-dummy*"))
377 (frame (make-frame-on-display
378 display
379 ;; Make it display (and remember) some dummy buffer, so
380 ;; we can detect later if the frame is in use or not.
381 `((server-dummy-buffer . ,buffer)
382 ;; This frame may be deleted later (see
383 ;; server-unselect-display) so we want it to be as
384 ;; unobtrusive as possible.
385 (visibility . nil)))))
386 (select-frame frame)
387 (set-window-buffer (selected-window) buffer)
388 frame))))
390 (defun server-unselect-display (frame)
391 (when (frame-live-p frame)
392 ;; If the temporary frame is in use (displays something real), make it
393 ;; visible. If not (which can happen if the user's customizations call
394 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
395 ;; the last real frame is deleted.
396 (if (and (eq (frame-first-window frame)
397 (next-window (frame-first-window frame) 'nomini))
398 (eq (window-buffer (frame-first-window frame))
399 (frame-parameter frame 'server-dummy-buffer)))
400 ;; The temp frame still only shows one buffer, and that is the
401 ;; internal temp buffer.
402 (delete-frame frame)
403 (set-frame-parameter frame 'visibility t))
404 (kill-buffer (frame-parameter frame 'server-dummy-buffer))
405 (set-frame-parameter frame 'server-dummy-buffer nil)))
407 (defun server-handle-delete-frame (frame)
408 "Delete the client connection when the emacsclient frame is deleted.
409 \(To be used from `delete-frame-functions'.)"
410 (let ((proc (frame-parameter frame 'client)))
411 (when (and (frame-live-p frame)
412 proc
413 ;; See if this is the last frame for this client.
414 (>= 1 (let ((frame-num 0))
415 (dolist (f (frame-list))
416 (when (eq proc (frame-parameter f 'client))
417 (setq frame-num (1+ frame-num))))
418 frame-num)))
419 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
420 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
422 (defun server-handle-suspend-tty (terminal)
423 "Notify the emacsclient process to suspend itself when its tty device is suspended."
424 (dolist (proc (server-clients-with 'terminal terminal))
425 (server-log (format "server-handle-suspend-tty, terminal %s" terminal) proc)
426 (condition-case err
427 (server-send-string proc "-suspend \n")
428 (file-error ;The pipe/socket was closed.
429 (ignore-errors (server-delete-client proc))))))
431 (defun server-unquote-arg (arg)
432 "Remove &-quotation from ARG.
433 See `server-quote-arg' and `server-process-filter'."
434 (replace-regexp-in-string
435 "&." (lambda (s)
436 (case (aref s 1)
437 (?& "&")
438 (?- "-")
439 (?n "\n")
440 (t " ")))
441 arg t t))
443 (defun server-quote-arg (arg)
444 "In ARG, insert a & before each &, each space, each newline, and -.
445 Change spaces to underscores, too, so that the return value never
446 contains a space.
448 See `server-unquote-arg' and `server-process-filter'."
449 (replace-regexp-in-string
450 "[-&\n ]" (lambda (s)
451 (case (aref s 0)
452 (?& "&&")
453 (?- "&-")
454 (?\n "&n")
455 (?\s "&_")))
456 arg t t))
458 (defun server-send-string (proc string)
459 "A wrapper around `process-send-string' for logging."
460 (server-log (concat "Sent " string) proc)
461 (process-send-string proc string))
463 (defun server-ensure-safe-dir (dir)
464 "Make sure DIR is a directory with no race-condition issues.
465 Creates the directory if necessary and makes sure:
466 - there's no symlink involved
467 - it's owned by us
468 - it's not readable/writable by anybody else."
469 (setq dir (directory-file-name dir))
470 (let ((attrs (file-attributes dir 'integer)))
471 (unless attrs
472 (letf (((default-file-modes) ?\700)) (make-directory dir t))
473 (setq attrs (file-attributes dir 'integer)))
475 ;; Check that it's safe for use.
476 (let* ((uid (nth 2 attrs))
477 (w32 (eq system-type 'windows-nt))
478 (safe (catch :safe
479 (unless (eq t (car attrs)) ; is a dir?
480 (throw :safe nil))
481 (when (and w32 (zerop uid)) ; on FAT32?
482 (display-warning
483 'server
484 (format "Using `%s' to store Emacs-server authentication files.
485 Directories on FAT32 filesystems are NOT secure against tampering.
486 See variable `server-auth-dir' for details."
487 (file-name-as-directory dir))
488 :warning)
489 (throw :safe t))
490 (unless (eql uid (user-uid)) ; is the dir ours?
491 (throw :safe nil))
492 (when w32 ; on NTFS?
493 (throw :safe t))
494 (unless (zerop (logand ?\077 (file-modes dir)))
495 (throw :safe nil))
496 t)))
497 (unless safe
498 (error "The directory `%s' is unsafe" dir)))))
500 ;;;###autoload
501 (defun server-start (&optional leave-dead inhibit-prompt)
502 "Allow this Emacs process to be a server for client processes.
503 This starts a server communications subprocess through which
504 client \"editors\" can send your editing commands to this Emacs
505 job. To use the server, set up the program `emacsclient' in the
506 Emacs distribution as your standard \"editor\".
508 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
509 kill any existing server communications subprocess.
511 If a server is already running, restart it. If clients are
512 running, ask the user for confirmation first, unless optional
513 argument INHIBIT-PROMPT is non-nil.
515 To force-start a server, do \\[server-force-delete] and then
516 \\[server-start]."
517 (interactive "P")
518 (when (or (not server-clients)
519 ;; Ask the user before deleting existing clients---except
520 ;; when we can't get user input, which may happen when
521 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
522 (cond
523 ((and (daemonp)
524 (null (cdr (frame-list)))
525 (eq (selected-frame) terminal-frame))
526 leave-dead)
527 (inhibit-prompt t)
528 (t (yes-or-no-p
529 "The current server still has clients; delete them? "))))
530 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
531 (server-file (expand-file-name server-name server-dir)))
532 (when server-process
533 ;; kill it dead!
534 (ignore-errors (delete-process server-process)))
535 ;; Delete the socket files made by previous server invocations.
536 (if (not (eq t (server-running-p server-name)))
537 ;; Remove any leftover socket or authentication file
538 (ignore-errors
539 (let (delete-by-moving-to-trash)
540 (delete-file server-file)))
541 (setq server-mode nil) ;; already set by the minor mode code
542 (display-warning
543 'server
544 (concat "Unable to start the Emacs server.\n"
545 (format "There is an existing Emacs server, named %S.\n"
546 server-name)
547 "To start the server in this Emacs process, stop the existing
548 server or call `M-x server-force-delete' to forcibly disconnect it.")
549 :warning)
550 (setq leave-dead t))
551 ;; If this Emacs already had a server, clear out associated status.
552 (while server-clients
553 (server-delete-client (car server-clients)))
554 ;; Now any previous server is properly stopped.
555 (if leave-dead
556 (progn
557 (unless (eq t leave-dead) (server-log (message "Server stopped")))
558 (setq server-process nil))
559 ;; Make sure there is a safe directory in which to place the socket.
560 (server-ensure-safe-dir server-dir)
561 (when server-process
562 (server-log (message "Restarting server")))
563 (letf (((default-file-modes) ?\700))
564 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
565 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
566 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
567 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
568 (add-hook 'kill-emacs-hook 'server-force-stop) ;Cleanup upon exit.
569 (setq server-process
570 (apply #'make-network-process
571 :name server-name
572 :server t
573 :noquery t
574 :sentinel 'server-sentinel
575 :filter 'server-process-filter
576 ;; We must receive file names without being decoded.
577 ;; Those are decoded by server-process-filter according
578 ;; to file-name-coding-system. Also don't get
579 ;; confused by CRs since we don't quote them.
580 :coding 'raw-text-unix
581 ;; The other args depend on the kind of socket used.
582 (if server-use-tcp
583 (list :family 'ipv4 ;; We're not ready for IPv6 yet
584 :service (or server-port t)
585 :host (or server-host 'local)
586 :plist '(:authenticated nil))
587 (list :family 'local
588 :service server-file
589 :plist '(:authenticated t)))))
590 (unless server-process (error "Could not start server process"))
591 (process-put server-process :server-file server-file)
592 (when server-use-tcp
593 (let ((auth-key
594 (loop
595 ;; The auth key is a 64-byte string of random chars in the
596 ;; range `!'..`~'.
597 repeat 64
598 collect (+ 33 (random 94)) into auth
599 finally return (concat auth))))
600 (process-put server-process :auth-key auth-key)
601 (with-temp-file server-file
602 (set-buffer-multibyte nil)
603 (setq buffer-file-coding-system 'no-conversion)
604 (insert (format-network-address
605 (process-contact server-process :local))
606 " " (number-to-string (emacs-pid)) ; Kept for compatibility
607 "\n" auth-key)))))))))
609 (defun server-force-stop ()
610 "Kill all connections to the current server.
611 This function is meant to be called from `kill-emacs-hook'."
612 (server-start t t))
614 ;;;###autoload
615 (defun server-force-delete (&optional name)
616 "Unconditionally delete connection file for server NAME.
617 If server is running, it is first stopped.
618 NAME defaults to `server-name'. With argument, ask for NAME."
619 (interactive
620 (list (if current-prefix-arg
621 (read-string "Server name: " nil nil server-name))))
622 (when server-mode (with-temp-message nil (server-mode -1)))
623 (let ((file (expand-file-name (or name server-name)
624 (if server-use-tcp
625 server-auth-dir
626 server-socket-dir))))
627 (condition-case nil
628 (let (delete-by-moving-to-trash)
629 (delete-file file)
630 (message "Connection file %S deleted" file))
631 (file-error
632 (message "No connection file %S" file)))))
634 (defun server-running-p (&optional name)
635 "Test whether server NAME is running.
637 Return values:
638 nil the server is definitely not running.
639 t the server seems to be running.
640 something else we cannot determine whether it's running without using
641 commands which may have to wait for a long time."
642 (unless name (setq name server-name))
643 (condition-case nil
644 (if server-use-tcp
645 (with-temp-buffer
646 (insert-file-contents-literally (expand-file-name name server-auth-dir))
647 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
648 (assq 'comm
649 (process-attributes
650 (string-to-number (match-string 1))))
652 :other))
653 (delete-process
654 (make-network-process
655 :name "server-client-test" :family 'local :server nil :noquery t
656 :service (expand-file-name name server-socket-dir)))
658 (file-error nil)))
660 ;;;###autoload
661 (define-minor-mode server-mode
662 "Toggle Server mode.
663 With ARG, turn Server mode on if ARG is positive, off otherwise.
664 Server mode runs a process that accepts commands from the
665 `emacsclient' program. See `server-start' and Info node `Emacs server'."
666 :global t
667 :group 'server
668 :version "22.1"
669 ;; Fixme: Should this check for an existing server socket and do
670 ;; nothing if there is one (for multiple Emacs sessions)?
671 (server-start (not server-mode)))
673 (defun server-eval-and-print (expr proc)
674 "Eval EXPR and send the result back to client PROC."
675 (let ((v (eval (car (read-from-string expr)))))
676 (when (and v proc)
677 (with-temp-buffer
678 (let ((standard-output (current-buffer)))
679 (pp v)
680 (let ((text (buffer-substring-no-properties
681 (point-min) (point-max))))
682 (server-send-string
683 proc (format "-print %s\n"
684 (server-quote-arg text)))))))))
686 (defun server-create-tty-frame (tty type proc)
687 (unless tty
688 (error "Invalid terminal device"))
689 (unless type
690 (error "Invalid terminal type"))
691 (add-to-list 'frame-inherited-parameters 'client)
692 (let ((frame
693 (server-with-environment (process-get proc 'env)
694 '("LANG" "LC_CTYPE" "LC_ALL"
695 ;; For tgetent(3); list according to ncurses(3).
696 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
697 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
698 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
699 "TERMINFO_DIRS" "TERMPATH"
700 ;; rxvt wants these
701 "COLORFGBG" "COLORTERM")
702 (make-frame `((window-system . nil)
703 (tty . ,tty)
704 (tty-type . ,type)
705 ;; Ignore nowait here; we always need to
706 ;; clean up opened ttys when the client dies.
707 (client . ,proc)
708 ;; This is a leftover from an earlier
709 ;; attempt at making it possible for process
710 ;; run in the server process to use the
711 ;; environment of the client process.
712 ;; It has no effect now and to make it work
713 ;; we'd need to decide how to make
714 ;; process-environment interact with client
715 ;; envvars, and then to change the
716 ;; C functions `child_setup' and
717 ;; `getenv_internal' accordingly.
718 (environment . ,(process-get proc 'env)))))))
720 ;; ttys don't use the `display' parameter, but callproc.c does to set
721 ;; the DISPLAY environment on subprocesses.
722 (set-frame-parameter frame 'display
723 (getenv-internal "DISPLAY" (process-get proc 'env)))
724 (select-frame frame)
725 (process-put proc 'frame frame)
726 (process-put proc 'terminal (frame-terminal frame))
728 ;; Display *scratch* by default.
729 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
731 frame))
733 (defun server-create-window-system-frame (display nowait proc parent-id)
734 (add-to-list 'frame-inherited-parameters 'client)
735 (if (not (fboundp 'make-frame-on-display))
736 (progn
737 ;; This emacs does not support X.
738 (server-log "Window system unsupported" proc)
739 (server-send-string proc "-window-system-unsupported \n")
740 nil)
741 ;; Flag frame as client-created, but use a dummy client.
742 ;; This will prevent the frame from being deleted when
743 ;; emacsclient quits while also preventing
744 ;; `server-save-buffers-kill-terminal' from unexpectedly
745 ;; killing emacs on that frame.
746 (let* ((params `((client . ,(if nowait 'nowait proc))
747 ;; This is a leftover, see above.
748 (environment . ,(process-get proc 'env))))
749 (display (or display
750 (frame-parameter nil 'display)
751 (getenv "DISPLAY")
752 (error "Please specify display")))
753 frame)
754 (if parent-id
755 (push (cons 'parent-id (string-to-number parent-id)) params))
756 (setq frame (make-frame-on-display display params))
757 (server-log (format "%s created" frame) proc)
758 (select-frame frame)
759 (process-put proc 'frame frame)
760 (process-put proc 'terminal (frame-terminal frame))
762 ;; Display *scratch* by default.
763 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
764 frame)))
766 (defun server-goto-toplevel (proc)
767 (condition-case nil
768 ;; If we're running isearch, we must abort it to allow Emacs to
769 ;; display the buffer and switch to it.
770 (dolist (buffer (buffer-list))
771 (with-current-buffer buffer
772 (when (bound-and-true-p isearch-mode)
773 (isearch-cancel))))
774 ;; Signaled by isearch-cancel.
775 (quit (message nil)))
776 (when (> (recursion-depth) 0)
777 ;; We're inside a minibuffer already, so if the emacs-client is trying
778 ;; to open a frame on a new display, we might end up with an unusable
779 ;; frame because input from that display will be blocked (until exiting
780 ;; the minibuffer). Better exit this minibuffer right away.
781 ;; Similarly with recursive-edits such as the splash screen.
782 (run-with-timer 0 nil (lexical-let ((proc proc))
783 (lambda () (server-execute-continuation proc))))
784 (top-level)))
786 ;; We use various special properties on process objects:
787 ;; - `env' stores the info about the environment of the emacsclient process.
788 ;; - `continuation' is a no-arg function that we need to execute. It contains
789 ;; commands we wanted to execute in some earlier invocation of the process
790 ;; filter but that we somehow were unable to process at that time
791 ;; (e.g. because we first need to throw to the toplevel).
793 (defun server-execute-continuation (proc)
794 (let ((continuation (process-get proc 'continuation)))
795 (process-put proc 'continuation nil)
796 (if continuation (ignore-errors (funcall continuation)))))
798 (defun* server-process-filter (proc string)
799 "Process a request from the server to edit some files.
800 PROC is the server process. STRING consists of a sequence of
801 commands prefixed by a dash. Some commands have arguments;
802 these are &-quoted and need to be decoded by `server-unquote-arg'.
803 The filter parses and executes these commands.
805 To illustrate the protocol, here is an example command that
806 emacsclient sends to create a new X frame (note that the whole
807 sequence is sent on a single line):
809 -env HOME=/home/lorentey
810 -env DISPLAY=:0.0
811 ... lots of other -env commands
812 -display :0.0
813 -window-system
815 The following commands are accepted by the server:
817 `-auth AUTH-STRING'
818 Authenticate the client using the secret authentication string
819 AUTH-STRING.
821 `-env NAME=VALUE'
822 An environment variable on the client side.
824 `-dir DIRNAME'
825 The current working directory of the client process.
827 `-current-frame'
828 Forbid the creation of new frames.
830 `-nowait'
831 Request that the next frame created should not be
832 associated with this client.
834 `-display DISPLAY'
835 Set the display name to open X frames on.
837 `-position LINE[:COLUMN]'
838 Go to the given line and column number
839 in the next file opened.
841 `-file FILENAME'
842 Load the given file in the current frame.
844 `-eval EXPR'
845 Evaluate EXPR as a Lisp expression and return the
846 result in -print commands.
848 `-window-system'
849 Open a new X frame.
851 `-tty DEVICENAME TYPE'
852 Open a new tty frame at the client.
854 `-suspend'
855 Suspend this tty frame. The client sends this string in
856 response to SIGTSTP and SIGTTOU. The server must cease all I/O
857 on this tty until it gets a -resume command.
859 `-resume'
860 Resume this tty frame. The client sends this string when it
861 gets the SIGCONT signal and it is the foreground process on its
862 controlling tty.
864 `-ignore COMMENT'
865 Do nothing, but put the comment in the server log.
866 Useful for debugging.
869 The following commands are accepted by the client:
871 `-emacs-pid PID'
872 Describes the process id of the Emacs process;
873 used to forward window change signals to it.
875 `-window-system-unsupported'
876 Signals that the server does not support creating X frames;
877 the client must try again with a tty frame.
879 `-print STRING'
880 Print STRING on stdout. Used to send values
881 returned by -eval.
883 `-error DESCRIPTION'
884 Signal an error and delete process PROC.
886 `-suspend'
887 Suspend this terminal, i.e., stop the client process.
888 Sent when the user presses C-z."
889 (server-log (concat "Received " string) proc)
890 ;; First things first: let's check the authentication
891 (unless (process-get proc :authenticated)
892 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
893 (equal (match-string 1 string) (process-get proc :auth-key)))
894 (progn
895 (setq string (substring string (match-end 0)))
896 (process-put proc :authenticated t)
897 (server-log "Authentication successful" proc))
898 (server-log "Authentication failed" proc)
899 (server-send-string
900 proc (concat "-error " (server-quote-arg "Authentication failed")))
901 ;; Before calling `delete-process', give emacsclient time to
902 ;; receive the error string and shut down on its own.
903 (sit-for 1)
904 (delete-process proc)
905 ;; We return immediately
906 (return-from server-process-filter)))
907 (let ((prev (process-get proc 'previous-string)))
908 (when prev
909 (setq string (concat prev string))
910 (process-put proc 'previous-string nil)))
911 (condition-case err
912 (progn
913 (server-add-client proc)
914 ;; Send our pid
915 (server-send-string proc (concat "-emacs-pid "
916 (number-to-string (emacs-pid)) "\n"))
917 (if (not (string-match "\n" string))
918 ;; Save for later any partial line that remains.
919 (when (> (length string) 0)
920 (process-put proc 'previous-string string))
922 ;; In earlier versions of server.el (where we used an `emacsserver'
923 ;; process), there could be multiple lines. Nowadays this is not
924 ;; supported any more.
925 (assert (eq (match-end 0) (length string)))
926 (let ((request (substring string 0 (match-beginning 0)))
927 (coding-system (and (default-value 'enable-multibyte-characters)
928 (or file-name-coding-system
929 default-file-name-coding-system)))
930 nowait ; t if emacsclient does not want to wait for us.
931 frame ; Frame opened for the client (if any).
932 display ; Open frame on this display.
933 parent-id ; Window ID for XEmbed
934 dontkill ; t if client should not be killed.
935 commands
937 use-current-frame
938 tty-name ; nil, `window-system', or the tty name.
939 tty-type ; string.
940 files
941 filepos
942 command-line-args-left
943 arg)
944 ;; Remove this line from STRING.
945 (setq string (substring string (match-end 0)))
946 (setq command-line-args-left
947 (mapcar 'server-unquote-arg (split-string request " " t)))
948 (while (setq arg (pop command-line-args-left))
949 (cond
950 ;; -version CLIENT-VERSION: obsolete at birth.
951 ((and (equal "-version" arg) command-line-args-left)
952 (pop command-line-args-left))
954 ;; -nowait: Emacsclient won't wait for a result.
955 ((equal "-nowait" arg) (setq nowait t))
957 ;; -current-frame: Don't create frames.
958 ((equal "-current-frame" arg) (setq use-current-frame t))
960 ;; -display DISPLAY:
961 ;; Open X frames on the given display instead of the default.
962 ((and (equal "-display" arg) command-line-args-left)
963 (setq display (pop command-line-args-left))
964 (if (zerop (length display)) (setq display nil)))
966 ;; -parent-id ID:
967 ;; Open X frame within window ID, via XEmbed.
968 ((and (equal "-parent-id" arg) command-line-args-left)
969 (setq parent-id (pop command-line-args-left))
970 (if (zerop (length parent-id)) (setq parent-id nil)))
972 ;; -window-system: Open a new X frame.
973 ((equal "-window-system" arg)
974 (setq dontkill t)
975 (setq tty-name 'window-system))
977 ;; -resume: Resume a suspended tty frame.
978 ((equal "-resume" arg)
979 (lexical-let ((terminal (process-get proc 'terminal)))
980 (setq dontkill t)
981 (push (lambda ()
982 (when (eq (terminal-live-p terminal) t)
983 (resume-tty terminal)))
984 commands)))
986 ;; -suspend: Suspend the client's frame. (In case we
987 ;; get out of sync, and a C-z sends a SIGTSTP to
988 ;; emacsclient.)
989 ((equal "-suspend" arg)
990 (lexical-let ((terminal (process-get proc 'terminal)))
991 (setq dontkill t)
992 (push (lambda ()
993 (when (eq (terminal-live-p terminal) t)
994 (suspend-tty terminal)))
995 commands)))
997 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
998 ;; (The given comment appears in the server log.)
999 ((and (equal "-ignore" arg) command-line-args-left
1000 (setq dontkill t)
1001 (pop command-line-args-left)))
1003 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1004 ((and (equal "-tty" arg)
1005 (cdr command-line-args-left))
1006 (setq tty-name (pop command-line-args-left)
1007 tty-type (pop command-line-args-left)
1008 dontkill (or dontkill
1009 (not use-current-frame))))
1011 ;; -position LINE[:COLUMN]: Set point to the given
1012 ;; position in the next file.
1013 ((and (equal "-position" arg)
1014 command-line-args-left
1015 (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1016 (car command-line-args-left)))
1017 (setq arg (pop command-line-args-left))
1018 (setq filepos
1019 (cons (string-to-number (match-string 1 arg))
1020 (string-to-number (or (match-string 2 arg) "")))))
1022 ;; -file FILENAME: Load the given file.
1023 ((and (equal "-file" arg)
1024 command-line-args-left)
1025 (let ((file (pop command-line-args-left)))
1026 (if coding-system
1027 (setq file (decode-coding-string file coding-system)))
1028 (setq file (expand-file-name file dir))
1029 (push (cons file filepos) files)
1030 (server-log (format "New file: %s %s"
1031 file (or filepos "")) proc))
1032 (setq filepos nil))
1034 ;; -eval EXPR: Evaluate a Lisp expression.
1035 ((and (equal "-eval" arg)
1036 command-line-args-left)
1037 (if use-current-frame
1038 (setq use-current-frame 'always))
1039 (lexical-let ((expr (pop command-line-args-left)))
1040 (if coding-system
1041 (setq expr (decode-coding-string expr coding-system)))
1042 (push (lambda () (server-eval-and-print expr proc))
1043 commands)
1044 (setq filepos nil)))
1046 ;; -env NAME=VALUE: An environment variable.
1047 ((and (equal "-env" arg) command-line-args-left)
1048 (let ((var (pop command-line-args-left)))
1049 ;; XXX Variables should be encoded as in getenv/setenv.
1050 (process-put proc 'env
1051 (cons var (process-get proc 'env)))))
1053 ;; -dir DIRNAME: The cwd of the emacsclient process.
1054 ((and (equal "-dir" arg) command-line-args-left)
1055 (setq dir (pop command-line-args-left))
1056 (if coding-system
1057 (setq dir (decode-coding-string dir coding-system)))
1058 (setq dir (command-line-normalize-file-name dir)))
1060 ;; Unknown command.
1061 (t (error "Unknown command: %s" arg))))
1063 (setq frame
1064 (cond
1065 ((and use-current-frame
1066 (or (eq use-current-frame 'always)
1067 ;; We can't use the Emacs daemon's
1068 ;; terminal frame.
1069 (not (and (daemonp)
1070 (null (cdr (frame-list)))
1071 (eq (selected-frame)
1072 terminal-frame)))))
1073 (setq tty-name nil tty-type nil)
1074 (if display (server-select-display display)))
1075 ((eq tty-name 'window-system)
1076 (server-create-window-system-frame display nowait proc
1077 parent-id))
1078 ;; When resuming on a tty, tty-name is nil.
1079 (tty-name
1080 (server-create-tty-frame tty-name tty-type proc))))
1082 (process-put
1083 proc 'continuation
1084 (lexical-let ((proc proc)
1085 (files files)
1086 (nowait nowait)
1087 (commands commands)
1088 (dontkill dontkill)
1089 (frame frame)
1090 (dir dir)
1091 (tty-name tty-name))
1092 (lambda ()
1093 (with-current-buffer (get-buffer-create server-buffer)
1094 ;; Use the same cwd as the emacsclient, if possible, so
1095 ;; relative file names work correctly, even in `eval'.
1096 (let ((default-directory
1097 (if (and dir (file-directory-p dir))
1098 dir default-directory)))
1099 (server-execute proc files nowait commands
1100 dontkill frame tty-name))))))
1102 (when (or frame files)
1103 (server-goto-toplevel proc))
1105 (server-execute-continuation proc))))
1106 ;; condition-case
1107 (error (server-return-error proc err))))
1109 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1110 ;; This is run from timers and process-filters, i.e. "asynchronously".
1111 ;; But w.r.t the user, this is not really asynchronous since the timer
1112 ;; is run after 0s and the process-filter is run in response to the
1113 ;; user running `emacsclient'. So it is OK to override the
1114 ;; inhibit-quit flag, which is good since `commands' (as well as
1115 ;; find-file-noselect via the major-mode) can run arbitrary code,
1116 ;; including code that needs to wait.
1117 (with-local-quit
1118 (condition-case err
1119 (let* ((buffers
1120 (when files
1121 (server-visit-files files proc nowait))))
1123 (mapc 'funcall (nreverse commands))
1125 ;; Delete the client if necessary.
1126 (cond
1127 (nowait
1128 ;; Client requested nowait; return immediately.
1129 (server-log "Close nowait client" proc)
1130 (server-delete-client proc))
1131 ((and (not dontkill) (null buffers))
1132 ;; This client is empty; get rid of it immediately.
1133 (server-log "Close empty client" proc)
1134 (server-delete-client proc)))
1135 (cond
1136 ((or isearch-mode (minibufferp))
1137 nil)
1138 ((and frame (null buffers))
1139 (message "%s" (substitute-command-keys
1140 "When done with this frame, type \\[delete-frame]")))
1141 ((not (null buffers))
1142 (server-switch-buffer (car buffers) nil (cdr (car files)))
1143 (run-hooks 'server-switch-hook)
1144 (unless nowait
1145 (message "%s" (substitute-command-keys
1146 "When done with a buffer, type \\[server-edit]")))))
1147 (when (and frame (null tty-name))
1148 (server-unselect-display frame)))
1149 (error (server-return-error proc err)))))
1151 (defun server-return-error (proc err)
1152 (ignore-errors
1153 (server-send-string
1154 proc (concat "-error " (server-quote-arg
1155 (error-message-string err))))
1156 (server-log (error-message-string err) proc)
1157 ;; Before calling `delete-process', give emacsclient time to
1158 ;; receive the error string and shut down on its own.
1159 (sit-for 5)
1160 (delete-process proc)))
1162 (defun server-goto-line-column (line-col)
1163 "Move point to the position indicated in LINE-COL.
1164 LINE-COL should be a pair (LINE . COL)."
1165 (when line-col
1166 (goto-char (point-min))
1167 (forward-line (1- (car line-col)))
1168 (let ((column-number (cdr line-col)))
1169 (when (> column-number 0)
1170 (move-to-column (1- column-number))))))
1172 (defun server-visit-files (files proc &optional nowait)
1173 "Find FILES and return a list of buffers created.
1174 FILES is an alist whose elements are (FILENAME . FILEPOS)
1175 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1176 PROC is the client that requested this operation.
1177 NOWAIT non-nil means this client is not waiting for the results,
1178 so don't mark these buffers specially, just visit them normally."
1179 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1180 (let ((last-nonmenu-event t) client-record)
1181 ;; Restore the current buffer afterward, but not using save-excursion,
1182 ;; because we don't want to save point in this buffer
1183 ;; if it happens to be one of those specified by the server.
1184 (save-current-buffer
1185 (dolist (file files)
1186 ;; If there is an existing buffer modified or the file is
1187 ;; modified, revert it. If there is an existing buffer with
1188 ;; deleted file, offer to write it.
1189 (let* ((minibuffer-auto-raise (or server-raise-frame
1190 minibuffer-auto-raise))
1191 (filen (car file))
1192 (obuf (get-file-buffer filen)))
1193 (add-to-history 'file-name-history filen)
1194 (if (null obuf)
1195 (progn
1196 (run-hooks 'pre-command-hook)
1197 (set-buffer (find-file-noselect filen)))
1198 (set-buffer obuf)
1199 ;; separately for each file, in sync with post-command hooks,
1200 ;; with the new buffer current:
1201 (run-hooks 'pre-command-hook)
1202 (cond ((file-exists-p filen)
1203 (when (not (verify-visited-file-modtime obuf))
1204 (revert-buffer t nil)))
1206 (when (y-or-n-p
1207 (concat "File no longer exists: " filen
1208 ", write buffer to file? "))
1209 (write-file filen))))
1210 (unless server-buffer-clients
1211 (setq server-existing-buffer t)))
1212 (server-goto-line-column (cdr file))
1213 (run-hooks 'server-visit-hook)
1214 ;; hooks may be specific to current buffer:
1215 (run-hooks 'post-command-hook))
1216 (unless nowait
1217 ;; When the buffer is killed, inform the clients.
1218 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1219 (push proc server-buffer-clients))
1220 (push (current-buffer) client-record)))
1221 (unless nowait
1222 (process-put proc 'buffers
1223 (nconc (process-get proc 'buffers) client-record)))
1224 client-record))
1226 (defun server-buffer-done (buffer &optional for-killing)
1227 "Mark BUFFER as \"done\" for its client(s).
1228 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1229 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1230 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1231 a temp file).
1232 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1233 (let ((next-buffer nil)
1234 (killed nil))
1235 (dolist (proc server-clients)
1236 (let ((buffers (process-get proc 'buffers)))
1237 (or next-buffer
1238 (setq next-buffer (nth 1 (memq buffer buffers))))
1239 (when buffers ; Ignore bufferless clients.
1240 (setq buffers (delq buffer buffers))
1241 ;; Delete all dead buffers from PROC.
1242 (dolist (b buffers)
1243 (and (bufferp b)
1244 (not (buffer-live-p b))
1245 (setq buffers (delq b buffers))))
1246 (process-put proc 'buffers buffers)
1247 ;; If client now has no pending buffers,
1248 ;; tell it that it is done, and forget it entirely.
1249 (unless buffers
1250 (server-log "Close" proc)
1251 (if for-killing
1252 ;; `server-delete-client' might delete the client's
1253 ;; frames, which might change the current buffer. We
1254 ;; don't want that (bug#640).
1255 (save-current-buffer
1256 (server-delete-client proc))
1257 (server-delete-client proc))))))
1258 (when (and (bufferp buffer) (buffer-name buffer))
1259 ;; We may or may not kill this buffer;
1260 ;; if we do, do not call server-buffer-done recursively
1261 ;; from kill-buffer-hook.
1262 (let ((server-kill-buffer-running t))
1263 (with-current-buffer buffer
1264 (setq server-buffer-clients nil)
1265 (run-hooks 'server-done-hook))
1266 ;; Notice whether server-done-hook killed the buffer.
1267 (if (null (buffer-name buffer))
1268 (setq killed t)
1269 ;; Don't bother killing or burying the buffer
1270 ;; when we are called from kill-buffer.
1271 (unless for-killing
1272 (when (and (not killed)
1273 server-kill-new-buffers
1274 (with-current-buffer buffer
1275 (not server-existing-buffer)))
1276 (setq killed t)
1277 (bury-buffer buffer)
1278 ;; Prevent kill-buffer from prompting (Bug#3696).
1279 (with-current-buffer buffer
1280 (set-buffer-modified-p nil))
1281 (kill-buffer buffer))
1282 (unless killed
1283 (if (server-temp-file-p buffer)
1284 (progn
1285 (with-current-buffer buffer
1286 (set-buffer-modified-p nil))
1287 (kill-buffer buffer)
1288 (setq killed t))
1289 (bury-buffer buffer)))))))
1290 (list next-buffer killed)))
1292 (defun server-temp-file-p (&optional buffer)
1293 "Return non-nil if BUFFER contains a file considered temporary.
1294 These are files whose names suggest they are repeatedly
1295 reused to pass information to another program.
1297 The variable `server-temp-file-regexp' controls which filenames
1298 are considered temporary."
1299 (and (buffer-file-name buffer)
1300 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1302 (defun server-done ()
1303 "Offer to save current buffer, mark it as \"done\" for clients.
1304 This kills or buries the buffer, then returns a list
1305 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1306 as a suggestion for what to select next, or nil.
1307 KILLED is t if we killed BUFFER, which happens if it was created
1308 specifically for the clients and did not exist before their request for it."
1309 (when server-buffer-clients
1310 (if (server-temp-file-p)
1311 ;; For a temp file, save, and do make a non-numeric backup
1312 ;; (unless make-backup-files is nil).
1313 (let ((version-control nil)
1314 (buffer-backed-up nil))
1315 (save-buffer))
1316 (when (and (buffer-modified-p)
1317 buffer-file-name
1318 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1319 (save-buffer)))
1320 (server-buffer-done (current-buffer))))
1322 ;; Ask before killing a server buffer.
1323 ;; It was suggested to release its client instead,
1324 ;; but I think that is dangerous--the client would proceed
1325 ;; using whatever is on disk in that file. -- rms.
1326 (defun server-kill-buffer-query-function ()
1327 "Ask before killing a server buffer."
1328 (or (not server-buffer-clients)
1329 (let ((res t))
1330 (dolist (proc server-buffer-clients res)
1331 (when (and (memq proc server-clients)
1332 (eq (process-status proc) 'open))
1333 (setq res nil))))
1334 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1335 (buffer-name (current-buffer))))))
1337 (defun server-kill-emacs-query-function ()
1338 "Ask before exiting Emacs if it has live clients."
1339 (or (not server-clients)
1340 (let (live-client)
1341 (dolist (proc server-clients live-client)
1342 (when (memq t (mapcar 'buffer-live-p (process-get
1343 proc 'buffers)))
1344 (setq live-client t))))
1345 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1347 (defvar server-kill-buffer-running nil
1348 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1350 (defun server-kill-buffer ()
1351 "Remove the current buffer from its clients' buffer list.
1352 Designed to be added to `kill-buffer-hook'."
1353 ;; Prevent infinite recursion if user has made server-done-hook
1354 ;; call kill-buffer.
1355 (or server-kill-buffer-running
1356 (and server-buffer-clients
1357 (let ((server-kill-buffer-running t))
1358 (when server-process
1359 (server-buffer-done (current-buffer) t))))))
1361 (defun server-edit (&optional arg)
1362 "Switch to next server editing buffer; say \"Done\" for current buffer.
1363 If a server buffer is current, it is marked \"done\" and optionally saved.
1364 The buffer is also killed if it did not exist before the clients asked for it.
1365 When all of a client's buffers are marked as \"done\", the client is notified.
1367 Temporary files such as MH <draft> files are always saved and backed up,
1368 no questions asked. (The variable `make-backup-files', if nil, still
1369 inhibits a backup; you can set it locally in a particular buffer to
1370 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1371 which filenames are considered temporary.
1373 If invoked with a prefix argument, or if there is no server process running,
1374 starts server process and that is all. Invoked by \\[server-edit]."
1375 (interactive "P")
1376 (cond
1377 ((or arg
1378 (not server-process)
1379 (memq (process-status server-process) '(signal exit)))
1380 (server-mode 1))
1381 (server-clients (apply 'server-switch-buffer (server-done)))
1382 (t (message "No server editing buffers exist"))))
1384 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1385 "Switch to another buffer, preferably one that has a client.
1386 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1388 KILLED-ONE is t in a recursive call if we have already killed one
1389 temp-file server buffer. This means we should avoid the final
1390 \"switch to some other buffer\" since we've already effectively
1391 done that.
1393 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1394 visit NEXT-BUFFER in an existing window. If non-nil, it should
1395 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1396 (if (null next-buffer)
1397 (progn
1398 (let ((rest server-clients))
1399 (while (and rest (not next-buffer))
1400 (let ((proc (car rest)))
1401 ;; Only look at frameless clients, or those in the selected
1402 ;; frame.
1403 (when (or (not (process-get proc 'frame))
1404 (eq (process-get proc 'frame) (selected-frame)))
1405 (setq next-buffer (car (process-get proc 'buffers))))
1406 (setq rest (cdr rest)))))
1407 (and next-buffer (server-switch-buffer next-buffer killed-one))
1408 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1409 ;; (switch-to-buffer (other-buffer))
1410 (message "No server buffers remain to edit")))
1411 (if (not (buffer-live-p next-buffer))
1412 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1413 ;; and try the next surviving server buffer.
1414 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1415 ;; OK, we know next-buffer is live, let's display and select it.
1416 (if (functionp server-window)
1417 (funcall server-window next-buffer)
1418 (let ((win (get-buffer-window next-buffer 0)))
1419 (if (and win (not server-window))
1420 ;; The buffer is already displayed: just reuse the
1421 ;; window. If FILEPOS is non-nil, use it to replace the
1422 ;; window's own value of point.
1423 (progn
1424 (select-window win)
1425 (set-buffer next-buffer)
1426 (when filepos
1427 (server-goto-line-column filepos)))
1428 ;; Otherwise, let's find an appropriate window.
1429 (cond ((window-live-p server-window)
1430 (select-window server-window))
1431 ((framep server-window)
1432 (unless (frame-live-p server-window)
1433 (setq server-window (make-frame)))
1434 (select-window (frame-selected-window server-window))))
1435 (when (window-minibuffer-p (selected-window))
1436 (select-window (next-window nil 'nomini 0)))
1437 ;; Move to a non-dedicated window, if we have one.
1438 (when (window-dedicated-p (selected-window))
1439 (select-window
1440 (get-window-with-predicate
1441 (lambda (w)
1442 (and (not (window-dedicated-p w))
1443 (equal (frame-terminal (window-frame w))
1444 (frame-terminal (selected-frame)))))
1445 'nomini 'visible (selected-window))))
1446 (condition-case nil
1447 (switch-to-buffer next-buffer)
1448 ;; After all the above, we might still have ended up with
1449 ;; a minibuffer/dedicated-window (if there's no other).
1450 (error (pop-to-buffer next-buffer)))))))
1451 (when server-raise-frame
1452 (select-frame-set-input-focus (window-frame (selected-window))))))
1454 ;;;###autoload
1455 (defun server-save-buffers-kill-terminal (arg)
1456 ;; Called from save-buffers-kill-terminal in files.el.
1457 "Offer to save each buffer, then kill the current client.
1458 With ARG non-nil, silently save all file-visiting buffers, then kill.
1460 If emacsclient was started with a list of filenames to edit, then
1461 only these files will be asked to be saved."
1462 (let ((proc (frame-parameter (selected-frame) 'client)))
1463 (cond ((eq proc 'nowait)
1464 ;; Nowait frames have no client buffer list.
1465 (if (cdr (frame-list))
1466 (progn (save-some-buffers arg)
1467 (delete-frame))
1468 ;; If we're the last frame standing, kill Emacs.
1469 (save-buffers-kill-emacs arg)))
1470 ((processp proc)
1471 (let ((buffers (process-get proc 'buffers)))
1472 ;; If client is bufferless, emulate a normal Emacs exit
1473 ;; and offer to save all buffers. Otherwise, offer to
1474 ;; save only the buffers belonging to the client.
1475 (save-some-buffers
1476 arg (if buffers
1477 (lambda () (memq (current-buffer) buffers))
1479 (server-delete-client proc)))
1480 (t (error "Invalid client frame")))))
1482 (define-key ctl-x-map "#" 'server-edit)
1484 (defun server-unload-function ()
1485 "Unload the server library."
1486 (server-mode -1)
1487 (substitute-key-definition 'server-edit nil ctl-x-map)
1488 (save-current-buffer
1489 (dolist (buffer (buffer-list))
1490 (set-buffer buffer)
1491 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1492 ;; continue standard unloading
1493 nil)
1496 (provide 'server)
1498 ;;; server.el ends here