* lisp/emacs-lisp/bytecomp.el (byte-recompile-file): New fun.
[emacs.git] / lisp / server.el
blob6fbef70768d949d7bc3ba13f196622654755780c
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)
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, the server is not started.
512 To force-start a server, do \\[server-force-delete] and then
513 \\[server-start]."
514 (interactive "P")
515 (when (or (not server-clients)
516 ;; Ask the user before deleting existing clients---except
517 ;; when we can't get user input, which may happen when
518 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
519 (if (and (daemonp)
520 (null (cdr (frame-list)))
521 (eq (selected-frame) terminal-frame))
522 leave-dead
523 (yes-or-no-p
524 "The current server still has clients; delete them? ")))
525 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
526 (server-file (expand-file-name server-name server-dir)))
527 (when server-process
528 ;; kill it dead!
529 (ignore-errors (delete-process server-process)))
530 ;; Delete the socket files made by previous server invocations.
531 (if (not (eq t (server-running-p server-name)))
532 ;; Remove any leftover socket or authentication file
533 (ignore-errors
534 (let (delete-by-moving-to-trash)
535 (delete-file server-file)))
536 (setq server-mode nil) ;; already set by the minor mode code
537 (display-warning
538 'server
539 (concat "Unable to start the Emacs server.\n"
540 (format "There is an existing Emacs server, named %S.\n"
541 server-name)
542 "To start the server in this Emacs process, stop the existing
543 server or call `M-x server-force-delete' to forcibly disconnect it.")
544 :warning)
545 (setq leave-dead t))
546 ;; If this Emacs already had a server, clear out associated status.
547 (while server-clients
548 (server-delete-client (car server-clients)))
549 ;; Now any previous server is properly stopped.
550 (if leave-dead
551 (progn
552 (unless (eq t leave-dead) (server-log (message "Server stopped")))
553 (setq server-process nil))
554 ;; Make sure there is a safe directory in which to place the socket.
555 (server-ensure-safe-dir server-dir)
556 (when server-process
557 (server-log (message "Restarting server")))
558 (letf (((default-file-modes) ?\700))
559 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
560 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
561 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
562 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
563 (add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
564 (setq server-process
565 (apply #'make-network-process
566 :name server-name
567 :server t
568 :noquery t
569 :sentinel 'server-sentinel
570 :filter 'server-process-filter
571 ;; We must receive file names without being decoded.
572 ;; Those are decoded by server-process-filter according
573 ;; to file-name-coding-system. Also don't get
574 ;; confused by CRs since we don't quote them.
575 :coding 'raw-text-unix
576 ;; The other args depend on the kind of socket used.
577 (if server-use-tcp
578 (list :family 'ipv4 ;; We're not ready for IPv6 yet
579 :service (or server-port t)
580 :host (or server-host 'local)
581 :plist '(:authenticated nil))
582 (list :family 'local
583 :service server-file
584 :plist '(:authenticated t)))))
585 (unless server-process (error "Could not start server process"))
586 (process-put server-process :server-file server-file)
587 (when server-use-tcp
588 (let ((auth-key
589 (loop
590 ;; The auth key is a 64-byte string of random chars in the
591 ;; range `!'..`~'.
592 repeat 64
593 collect (+ 33 (random 94)) into auth
594 finally return (concat auth))))
595 (process-put server-process :auth-key auth-key)
596 (with-temp-file server-file
597 (set-buffer-multibyte nil)
598 (setq buffer-file-coding-system 'no-conversion)
599 (insert (format-network-address
600 (process-contact server-process :local))
601 " " (number-to-string (emacs-pid)) ; Kept for compatibility
602 "\n" auth-key)))))))))
604 ;;;###autoload
605 (defun server-force-delete (&optional name)
606 "Unconditionally delete connection file for server NAME.
607 If server is running, it is first stopped.
608 NAME defaults to `server-name'. With argument, ask for NAME."
609 (interactive
610 (list (if current-prefix-arg
611 (read-string "Server name: " nil nil server-name))))
612 (when server-mode (with-temp-message nil (server-mode -1)))
613 (let ((file (expand-file-name (or name server-name)
614 (if server-use-tcp
615 server-auth-dir
616 server-socket-dir))))
617 (condition-case nil
618 (let (delete-by-moving-to-trash)
619 (delete-file file)
620 (message "Connection file %S deleted" file))
621 (file-error
622 (message "No connection file %S" file)))))
624 (defun server-running-p (&optional name)
625 "Test whether server NAME is running.
627 Return values:
628 nil the server is definitely not running.
629 t the server seems to be running.
630 something else we cannot determine whether it's running without using
631 commands which may have to wait for a long time."
632 (unless name (setq name server-name))
633 (condition-case nil
634 (if server-use-tcp
635 (with-temp-buffer
636 (insert-file-contents-literally (expand-file-name name server-auth-dir))
637 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
638 (assq 'comm
639 (process-attributes
640 (string-to-number (match-string 1))))
642 :other))
643 (delete-process
644 (make-network-process
645 :name "server-client-test" :family 'local :server nil :noquery t
646 :service (expand-file-name name server-socket-dir)))
648 (file-error nil)))
650 ;;;###autoload
651 (define-minor-mode server-mode
652 "Toggle Server mode.
653 With ARG, turn Server mode on if ARG is positive, off otherwise.
654 Server mode runs a process that accepts commands from the
655 `emacsclient' program. See `server-start' and Info node `Emacs server'."
656 :global t
657 :group 'server
658 :version "22.1"
659 ;; Fixme: Should this check for an existing server socket and do
660 ;; nothing if there is one (for multiple Emacs sessions)?
661 (server-start (not server-mode)))
663 (defun server-eval-and-print (expr proc)
664 "Eval EXPR and send the result back to client PROC."
665 (let ((v (eval (car (read-from-string expr)))))
666 (when (and v proc)
667 (with-temp-buffer
668 (let ((standard-output (current-buffer)))
669 (pp v)
670 (let ((text (buffer-substring-no-properties
671 (point-min) (point-max))))
672 (server-send-string
673 proc (format "-print %s\n"
674 (server-quote-arg text)))))))))
676 (defun server-create-tty-frame (tty type proc)
677 (unless tty
678 (error "Invalid terminal device"))
679 (unless type
680 (error "Invalid terminal type"))
681 (add-to-list 'frame-inherited-parameters 'client)
682 (let ((frame
683 (server-with-environment (process-get proc 'env)
684 '("LANG" "LC_CTYPE" "LC_ALL"
685 ;; For tgetent(3); list according to ncurses(3).
686 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
687 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
688 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
689 "TERMINFO_DIRS" "TERMPATH"
690 ;; rxvt wants these
691 "COLORFGBG" "COLORTERM")
692 (make-frame `((window-system . nil)
693 (tty . ,tty)
694 (tty-type . ,type)
695 ;; Ignore nowait here; we always need to
696 ;; clean up opened ttys when the client dies.
697 (client . ,proc)
698 ;; This is a leftover from an earlier
699 ;; attempt at making it possible for process
700 ;; run in the server process to use the
701 ;; environment of the client process.
702 ;; It has no effect now and to make it work
703 ;; we'd need to decide how to make
704 ;; process-environment interact with client
705 ;; envvars, and then to change the
706 ;; C functions `child_setup' and
707 ;; `getenv_internal' accordingly.
708 (environment . ,(process-get proc 'env)))))))
710 ;; ttys don't use the `display' parameter, but callproc.c does to set
711 ;; the DISPLAY environment on subprocesses.
712 (set-frame-parameter frame 'display
713 (getenv-internal "DISPLAY" (process-get proc 'env)))
714 (select-frame frame)
715 (process-put proc 'frame frame)
716 (process-put proc 'terminal (frame-terminal frame))
718 ;; Display *scratch* by default.
719 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
721 frame))
723 (defun server-create-window-system-frame (display nowait proc parent-id)
724 (add-to-list 'frame-inherited-parameters 'client)
725 (if (not (fboundp 'make-frame-on-display))
726 (progn
727 ;; This emacs does not support X.
728 (server-log "Window system unsupported" proc)
729 (server-send-string proc "-window-system-unsupported \n")
730 nil)
731 ;; Flag frame as client-created, but use a dummy client.
732 ;; This will prevent the frame from being deleted when
733 ;; emacsclient quits while also preventing
734 ;; `server-save-buffers-kill-terminal' from unexpectedly
735 ;; killing emacs on that frame.
736 (let* ((params `((client . ,(if nowait 'nowait proc))
737 ;; This is a leftover, see above.
738 (environment . ,(process-get proc 'env))))
739 (display (or display
740 (frame-parameter nil 'display)
741 (getenv "DISPLAY")
742 (error "Please specify display")))
743 frame)
744 (if parent-id
745 (push (cons 'parent-id (string-to-number parent-id)) params))
746 (setq frame (make-frame-on-display display params))
747 (server-log (format "%s created" frame) proc)
748 (select-frame frame)
749 (process-put proc 'frame frame)
750 (process-put proc 'terminal (frame-terminal frame))
752 ;; Display *scratch* by default.
753 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
754 frame)))
756 (defun server-goto-toplevel (proc)
757 (condition-case nil
758 ;; If we're running isearch, we must abort it to allow Emacs to
759 ;; display the buffer and switch to it.
760 (dolist (buffer (buffer-list))
761 (with-current-buffer buffer
762 (when (bound-and-true-p isearch-mode)
763 (isearch-cancel))))
764 ;; Signaled by isearch-cancel.
765 (quit (message nil)))
766 (when (> (recursion-depth) 0)
767 ;; We're inside a minibuffer already, so if the emacs-client is trying
768 ;; to open a frame on a new display, we might end up with an unusable
769 ;; frame because input from that display will be blocked (until exiting
770 ;; the minibuffer). Better exit this minibuffer right away.
771 ;; Similarly with recursive-edits such as the splash screen.
772 (run-with-timer 0 nil (lexical-let ((proc proc))
773 (lambda () (server-execute-continuation proc))))
774 (top-level)))
776 ;; We use various special properties on process objects:
777 ;; - `env' stores the info about the environment of the emacsclient process.
778 ;; - `continuation' is a no-arg function that we need to execute. It contains
779 ;; commands we wanted to execute in some earlier invocation of the process
780 ;; filter but that we somehow were unable to process at that time
781 ;; (e.g. because we first need to throw to the toplevel).
783 (defun server-execute-continuation (proc)
784 (let ((continuation (process-get proc 'continuation)))
785 (process-put proc 'continuation nil)
786 (if continuation (ignore-errors (funcall continuation)))))
788 (defun* server-process-filter (proc string)
789 "Process a request from the server to edit some files.
790 PROC is the server process. STRING consists of a sequence of
791 commands prefixed by a dash. Some commands have arguments;
792 these are &-quoted and need to be decoded by `server-unquote-arg'.
793 The filter parses and executes these commands.
795 To illustrate the protocol, here is an example command that
796 emacsclient sends to create a new X frame (note that the whole
797 sequence is sent on a single line):
799 -env HOME=/home/lorentey
800 -env DISPLAY=:0.0
801 ... lots of other -env commands
802 -display :0.0
803 -window-system
805 The following commands are accepted by the server:
807 `-auth AUTH-STRING'
808 Authenticate the client using the secret authentication string
809 AUTH-STRING.
811 `-env NAME=VALUE'
812 An environment variable on the client side.
814 `-dir DIRNAME'
815 The current working directory of the client process.
817 `-current-frame'
818 Forbid the creation of new frames.
820 `-nowait'
821 Request that the next frame created should not be
822 associated with this client.
824 `-display DISPLAY'
825 Set the display name to open X frames on.
827 `-position LINE[:COLUMN]'
828 Go to the given line and column number
829 in the next file opened.
831 `-file FILENAME'
832 Load the given file in the current frame.
834 `-eval EXPR'
835 Evaluate EXPR as a Lisp expression and return the
836 result in -print commands.
838 `-window-system'
839 Open a new X frame.
841 `-tty DEVICENAME TYPE'
842 Open a new tty frame at the client.
844 `-suspend'
845 Suspend this tty frame. The client sends this string in
846 response to SIGTSTP and SIGTTOU. The server must cease all I/O
847 on this tty until it gets a -resume command.
849 `-resume'
850 Resume this tty frame. The client sends this string when it
851 gets the SIGCONT signal and it is the foreground process on its
852 controlling tty.
854 `-ignore COMMENT'
855 Do nothing, but put the comment in the server log.
856 Useful for debugging.
859 The following commands are accepted by the client:
861 `-emacs-pid PID'
862 Describes the process id of the Emacs process;
863 used to forward window change signals to it.
865 `-window-system-unsupported'
866 Signals that the server does not support creating X frames;
867 the client must try again with a tty frame.
869 `-print STRING'
870 Print STRING on stdout. Used to send values
871 returned by -eval.
873 `-error DESCRIPTION'
874 Signal an error and delete process PROC.
876 `-suspend'
877 Suspend this terminal, i.e., stop the client process.
878 Sent when the user presses C-z."
879 (server-log (concat "Received " string) proc)
880 ;; First things first: let's check the authentication
881 (unless (process-get proc :authenticated)
882 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
883 (equal (match-string 1 string) (process-get proc :auth-key)))
884 (progn
885 (setq string (substring string (match-end 0)))
886 (process-put proc :authenticated t)
887 (server-log "Authentication successful" proc))
888 (server-log "Authentication failed" proc)
889 (server-send-string
890 proc (concat "-error " (server-quote-arg "Authentication failed")))
891 ;; Before calling `delete-process', give emacsclient time to
892 ;; receive the error string and shut down on its own.
893 (sit-for 1)
894 (delete-process proc)
895 ;; We return immediately
896 (return-from server-process-filter)))
897 (let ((prev (process-get proc 'previous-string)))
898 (when prev
899 (setq string (concat prev string))
900 (process-put proc 'previous-string nil)))
901 (condition-case err
902 (progn
903 (server-add-client proc)
904 ;; Send our pid
905 (server-send-string proc (concat "-emacs-pid "
906 (number-to-string (emacs-pid)) "\n"))
907 (if (not (string-match "\n" string))
908 ;; Save for later any partial line that remains.
909 (when (> (length string) 0)
910 (process-put proc 'previous-string string))
912 ;; In earlier versions of server.el (where we used an `emacsserver'
913 ;; process), there could be multiple lines. Nowadays this is not
914 ;; supported any more.
915 (assert (eq (match-end 0) (length string)))
916 (let ((request (substring string 0 (match-beginning 0)))
917 (coding-system (and (default-value 'enable-multibyte-characters)
918 (or file-name-coding-system
919 default-file-name-coding-system)))
920 nowait ; t if emacsclient does not want to wait for us.
921 frame ; Frame opened for the client (if any).
922 display ; Open frame on this display.
923 parent-id ; Window ID for XEmbed
924 dontkill ; t if client should not be killed.
925 commands
927 use-current-frame
928 tty-name ; nil, `window-system', or the tty name.
929 tty-type ; string.
930 files
931 filepos
932 command-line-args-left
933 arg)
934 ;; Remove this line from STRING.
935 (setq string (substring string (match-end 0)))
936 (setq command-line-args-left
937 (mapcar 'server-unquote-arg (split-string request " " t)))
938 (while (setq arg (pop command-line-args-left))
939 (cond
940 ;; -version CLIENT-VERSION: obsolete at birth.
941 ((and (equal "-version" arg) command-line-args-left)
942 (pop command-line-args-left))
944 ;; -nowait: Emacsclient won't wait for a result.
945 ((equal "-nowait" arg) (setq nowait t))
947 ;; -current-frame: Don't create frames.
948 ((equal "-current-frame" arg) (setq use-current-frame t))
950 ;; -display DISPLAY:
951 ;; Open X frames on the given display instead of the default.
952 ((and (equal "-display" arg) command-line-args-left)
953 (setq display (pop command-line-args-left))
954 (if (zerop (length display)) (setq display nil)))
956 ;; -parent-id ID:
957 ;; Open X frame within window ID, via XEmbed.
958 ((and (equal "-parent-id" arg) command-line-args-left)
959 (setq parent-id (pop command-line-args-left))
960 (if (zerop (length parent-id)) (setq parent-id nil)))
962 ;; -window-system: Open a new X frame.
963 ((equal "-window-system" arg)
964 (setq dontkill t)
965 (setq tty-name 'window-system))
967 ;; -resume: Resume a suspended tty frame.
968 ((equal "-resume" arg)
969 (lexical-let ((terminal (process-get proc 'terminal)))
970 (setq dontkill t)
971 (push (lambda ()
972 (when (eq (terminal-live-p terminal) t)
973 (resume-tty terminal)))
974 commands)))
976 ;; -suspend: Suspend the client's frame. (In case we
977 ;; get out of sync, and a C-z sends a SIGTSTP to
978 ;; emacsclient.)
979 ((equal "-suspend" arg)
980 (lexical-let ((terminal (process-get proc 'terminal)))
981 (setq dontkill t)
982 (push (lambda ()
983 (when (eq (terminal-live-p terminal) t)
984 (suspend-tty terminal)))
985 commands)))
987 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
988 ;; (The given comment appears in the server log.)
989 ((and (equal "-ignore" arg) command-line-args-left
990 (setq dontkill t)
991 (pop command-line-args-left)))
993 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
994 ((and (equal "-tty" arg)
995 (cdr command-line-args-left))
996 (setq tty-name (pop command-line-args-left)
997 tty-type (pop command-line-args-left)
998 dontkill (or dontkill
999 (not use-current-frame))))
1001 ;; -position LINE[:COLUMN]: Set point to the given
1002 ;; position in the next file.
1003 ((and (equal "-position" arg)
1004 command-line-args-left
1005 (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1006 (car command-line-args-left)))
1007 (setq arg (pop command-line-args-left))
1008 (setq filepos
1009 (cons (string-to-number (match-string 1 arg))
1010 (string-to-number (or (match-string 2 arg) "")))))
1012 ;; -file FILENAME: Load the given file.
1013 ((and (equal "-file" arg)
1014 command-line-args-left)
1015 (let ((file (pop command-line-args-left)))
1016 (if coding-system
1017 (setq file (decode-coding-string file coding-system)))
1018 (setq file (expand-file-name file dir))
1019 (push (cons file filepos) files)
1020 (server-log (format "New file: %s %s"
1021 file (or filepos "")) proc))
1022 (setq filepos nil))
1024 ;; -eval EXPR: Evaluate a Lisp expression.
1025 ((and (equal "-eval" arg)
1026 command-line-args-left)
1027 (if use-current-frame
1028 (setq use-current-frame 'always))
1029 (lexical-let ((expr (pop command-line-args-left)))
1030 (if coding-system
1031 (setq expr (decode-coding-string expr coding-system)))
1032 (push (lambda () (server-eval-and-print expr proc))
1033 commands)
1034 (setq filepos nil)))
1036 ;; -env NAME=VALUE: An environment variable.
1037 ((and (equal "-env" arg) command-line-args-left)
1038 (let ((var (pop command-line-args-left)))
1039 ;; XXX Variables should be encoded as in getenv/setenv.
1040 (process-put proc 'env
1041 (cons var (process-get proc 'env)))))
1043 ;; -dir DIRNAME: The cwd of the emacsclient process.
1044 ((and (equal "-dir" arg) command-line-args-left)
1045 (setq dir (pop command-line-args-left))
1046 (if coding-system
1047 (setq dir (decode-coding-string dir coding-system)))
1048 (setq dir (command-line-normalize-file-name dir)))
1050 ;; Unknown command.
1051 (t (error "Unknown command: %s" arg))))
1053 (setq frame
1054 (cond
1055 ((and use-current-frame
1056 (or (eq use-current-frame 'always)
1057 ;; We can't use the Emacs daemon's
1058 ;; terminal frame.
1059 (not (and (daemonp)
1060 (null (cdr (frame-list)))
1061 (eq (selected-frame)
1062 terminal-frame)))))
1063 (setq tty-name nil tty-type nil)
1064 (if display (server-select-display display)))
1065 ((eq tty-name 'window-system)
1066 (server-create-window-system-frame display nowait proc
1067 parent-id))
1068 ;; When resuming on a tty, tty-name is nil.
1069 (tty-name
1070 (server-create-tty-frame tty-name tty-type proc))))
1072 (process-put
1073 proc 'continuation
1074 (lexical-let ((proc proc)
1075 (files files)
1076 (nowait nowait)
1077 (commands commands)
1078 (dontkill dontkill)
1079 (frame frame)
1080 (dir dir)
1081 (tty-name tty-name))
1082 (lambda ()
1083 (with-current-buffer (get-buffer-create server-buffer)
1084 ;; Use the same cwd as the emacsclient, if possible, so
1085 ;; relative file names work correctly, even in `eval'.
1086 (let ((default-directory
1087 (if (and dir (file-directory-p dir))
1088 dir default-directory)))
1089 (server-execute proc files nowait commands
1090 dontkill frame tty-name))))))
1092 (when (or frame files)
1093 (server-goto-toplevel proc))
1095 (server-execute-continuation proc))))
1096 ;; condition-case
1097 (error (server-return-error proc err))))
1099 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1100 ;; This is run from timers and process-filters, i.e. "asynchronously".
1101 ;; But w.r.t the user, this is not really asynchronous since the timer
1102 ;; is run after 0s and the process-filter is run in response to the
1103 ;; user running `emacsclient'. So it is OK to override the
1104 ;; inhibit-quit flag, which is good since `commands' (as well as
1105 ;; find-file-noselect via the major-mode) can run arbitrary code,
1106 ;; including code that needs to wait.
1107 (with-local-quit
1108 (condition-case err
1109 (let* ((buffers
1110 (when files
1111 (server-visit-files files proc nowait))))
1113 (mapc 'funcall (nreverse commands))
1115 ;; Delete the client if necessary.
1116 (cond
1117 (nowait
1118 ;; Client requested nowait; return immediately.
1119 (server-log "Close nowait client" proc)
1120 (server-delete-client proc))
1121 ((and (not dontkill) (null buffers))
1122 ;; This client is empty; get rid of it immediately.
1123 (server-log "Close empty client" proc)
1124 (server-delete-client proc)))
1125 (cond
1126 ((or isearch-mode (minibufferp))
1127 nil)
1128 ((and frame (null buffers))
1129 (message "%s" (substitute-command-keys
1130 "When done with this frame, type \\[delete-frame]")))
1131 ((not (null buffers))
1132 (server-switch-buffer (car buffers) nil (cdr (car files)))
1133 (run-hooks 'server-switch-hook)
1134 (unless nowait
1135 (message "%s" (substitute-command-keys
1136 "When done with a buffer, type \\[server-edit]")))))
1137 (when (and frame (null tty-name))
1138 (server-unselect-display frame)))
1139 (error (server-return-error proc err)))))
1141 (defun server-return-error (proc err)
1142 (ignore-errors
1143 (server-send-string
1144 proc (concat "-error " (server-quote-arg
1145 (error-message-string err))))
1146 (server-log (error-message-string err) proc)
1147 ;; Before calling `delete-process', give emacsclient time to
1148 ;; receive the error string and shut down on its own.
1149 (sit-for 5)
1150 (delete-process proc)))
1152 (defun server-goto-line-column (line-col)
1153 "Move point to the position indicated in LINE-COL.
1154 LINE-COL should be a pair (LINE . COL)."
1155 (when line-col
1156 (goto-char (point-min))
1157 (forward-line (1- (car line-col)))
1158 (let ((column-number (cdr line-col)))
1159 (when (> column-number 0)
1160 (move-to-column (1- column-number))))))
1162 (defun server-visit-files (files proc &optional nowait)
1163 "Find FILES and return a list of buffers created.
1164 FILES is an alist whose elements are (FILENAME . FILEPOS)
1165 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1166 PROC is the client that requested this operation.
1167 NOWAIT non-nil means this client is not waiting for the results,
1168 so don't mark these buffers specially, just visit them normally."
1169 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1170 (let ((last-nonmenu-event t) client-record)
1171 ;; Restore the current buffer afterward, but not using save-excursion,
1172 ;; because we don't want to save point in this buffer
1173 ;; if it happens to be one of those specified by the server.
1174 (save-current-buffer
1175 (dolist (file files)
1176 ;; If there is an existing buffer modified or the file is
1177 ;; modified, revert it. If there is an existing buffer with
1178 ;; deleted file, offer to write it.
1179 (let* ((minibuffer-auto-raise (or server-raise-frame
1180 minibuffer-auto-raise))
1181 (filen (car file))
1182 (obuf (get-file-buffer filen)))
1183 (add-to-history 'file-name-history filen)
1184 (if (null obuf)
1185 (progn
1186 (run-hooks 'pre-command-hook)
1187 (set-buffer (find-file-noselect filen)))
1188 (set-buffer obuf)
1189 ;; separately for each file, in sync with post-command hooks,
1190 ;; with the new buffer current:
1191 (run-hooks 'pre-command-hook)
1192 (cond ((file-exists-p filen)
1193 (when (not (verify-visited-file-modtime obuf))
1194 (revert-buffer t nil)))
1196 (when (y-or-n-p
1197 (concat "File no longer exists: " filen
1198 ", write buffer to file? "))
1199 (write-file filen))))
1200 (unless server-buffer-clients
1201 (setq server-existing-buffer t)))
1202 (server-goto-line-column (cdr file))
1203 (run-hooks 'server-visit-hook)
1204 ;; hooks may be specific to current buffer:
1205 (run-hooks 'post-command-hook))
1206 (unless nowait
1207 ;; When the buffer is killed, inform the clients.
1208 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1209 (push proc server-buffer-clients))
1210 (push (current-buffer) client-record)))
1211 (unless nowait
1212 (process-put proc 'buffers
1213 (nconc (process-get proc 'buffers) client-record)))
1214 client-record))
1216 (defun server-buffer-done (buffer &optional for-killing)
1217 "Mark BUFFER as \"done\" for its client(s).
1218 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1219 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1220 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1221 a temp file).
1222 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1223 (let ((next-buffer nil)
1224 (killed nil))
1225 (dolist (proc server-clients)
1226 (let ((buffers (process-get proc 'buffers)))
1227 (or next-buffer
1228 (setq next-buffer (nth 1 (memq buffer buffers))))
1229 (when buffers ; Ignore bufferless clients.
1230 (setq buffers (delq buffer buffers))
1231 ;; Delete all dead buffers from PROC.
1232 (dolist (b buffers)
1233 (and (bufferp b)
1234 (not (buffer-live-p b))
1235 (setq buffers (delq b buffers))))
1236 (process-put proc 'buffers buffers)
1237 ;; If client now has no pending buffers,
1238 ;; tell it that it is done, and forget it entirely.
1239 (unless buffers
1240 (server-log "Close" proc)
1241 (if for-killing
1242 ;; `server-delete-client' might delete the client's
1243 ;; frames, which might change the current buffer. We
1244 ;; don't want that (bug#640).
1245 (save-current-buffer
1246 (server-delete-client proc))
1247 (server-delete-client proc))))))
1248 (when (and (bufferp buffer) (buffer-name buffer))
1249 ;; We may or may not kill this buffer;
1250 ;; if we do, do not call server-buffer-done recursively
1251 ;; from kill-buffer-hook.
1252 (let ((server-kill-buffer-running t))
1253 (with-current-buffer buffer
1254 (setq server-buffer-clients nil)
1255 (run-hooks 'server-done-hook))
1256 ;; Notice whether server-done-hook killed the buffer.
1257 (if (null (buffer-name buffer))
1258 (setq killed t)
1259 ;; Don't bother killing or burying the buffer
1260 ;; when we are called from kill-buffer.
1261 (unless for-killing
1262 (when (and (not killed)
1263 server-kill-new-buffers
1264 (with-current-buffer buffer
1265 (not server-existing-buffer)))
1266 (setq killed t)
1267 (bury-buffer buffer)
1268 ;; Prevent kill-buffer from prompting (Bug#3696).
1269 (with-current-buffer buffer
1270 (set-buffer-modified-p nil))
1271 (kill-buffer buffer))
1272 (unless killed
1273 (if (server-temp-file-p buffer)
1274 (progn
1275 (with-current-buffer buffer
1276 (set-buffer-modified-p nil))
1277 (kill-buffer buffer)
1278 (setq killed t))
1279 (bury-buffer buffer)))))))
1280 (list next-buffer killed)))
1282 (defun server-temp-file-p (&optional buffer)
1283 "Return non-nil if BUFFER contains a file considered temporary.
1284 These are files whose names suggest they are repeatedly
1285 reused to pass information to another program.
1287 The variable `server-temp-file-regexp' controls which filenames
1288 are considered temporary."
1289 (and (buffer-file-name buffer)
1290 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1292 (defun server-done ()
1293 "Offer to save current buffer, mark it as \"done\" for clients.
1294 This kills or buries the buffer, then returns a list
1295 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1296 as a suggestion for what to select next, or nil.
1297 KILLED is t if we killed BUFFER, which happens if it was created
1298 specifically for the clients and did not exist before their request for it."
1299 (when server-buffer-clients
1300 (if (server-temp-file-p)
1301 ;; For a temp file, save, and do make a non-numeric backup
1302 ;; (unless make-backup-files is nil).
1303 (let ((version-control nil)
1304 (buffer-backed-up nil))
1305 (save-buffer))
1306 (when (and (buffer-modified-p)
1307 buffer-file-name
1308 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1309 (save-buffer)))
1310 (server-buffer-done (current-buffer))))
1312 ;; Ask before killing a server buffer.
1313 ;; It was suggested to release its client instead,
1314 ;; but I think that is dangerous--the client would proceed
1315 ;; using whatever is on disk in that file. -- rms.
1316 (defun server-kill-buffer-query-function ()
1317 "Ask before killing a server buffer."
1318 (or (not server-buffer-clients)
1319 (let ((res t))
1320 (dolist (proc server-buffer-clients res)
1321 (when (and (memq proc server-clients)
1322 (eq (process-status proc) 'open))
1323 (setq res nil))))
1324 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1325 (buffer-name (current-buffer))))))
1327 (defun server-kill-emacs-query-function ()
1328 "Ask before exiting Emacs if it has live clients."
1329 (or (not server-clients)
1330 (let (live-client)
1331 (dolist (proc server-clients live-client)
1332 (when (memq t (mapcar 'buffer-live-p (process-get
1333 proc 'buffers)))
1334 (setq live-client t))))
1335 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1337 (defvar server-kill-buffer-running nil
1338 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1340 (defun server-kill-buffer ()
1341 "Remove the current buffer from its clients' buffer list.
1342 Designed to be added to `kill-buffer-hook'."
1343 ;; Prevent infinite recursion if user has made server-done-hook
1344 ;; call kill-buffer.
1345 (or server-kill-buffer-running
1346 (and server-buffer-clients
1347 (let ((server-kill-buffer-running t))
1348 (when server-process
1349 (server-buffer-done (current-buffer) t))))))
1351 (defun server-edit (&optional arg)
1352 "Switch to next server editing buffer; say \"Done\" for current buffer.
1353 If a server buffer is current, it is marked \"done\" and optionally saved.
1354 The buffer is also killed if it did not exist before the clients asked for it.
1355 When all of a client's buffers are marked as \"done\", the client is notified.
1357 Temporary files such as MH <draft> files are always saved and backed up,
1358 no questions asked. (The variable `make-backup-files', if nil, still
1359 inhibits a backup; you can set it locally in a particular buffer to
1360 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1361 which filenames are considered temporary.
1363 If invoked with a prefix argument, or if there is no server process running,
1364 starts server process and that is all. Invoked by \\[server-edit]."
1365 (interactive "P")
1366 (cond
1367 ((or arg
1368 (not server-process)
1369 (memq (process-status server-process) '(signal exit)))
1370 (server-mode 1))
1371 (server-clients (apply 'server-switch-buffer (server-done)))
1372 (t (message "No server editing buffers exist"))))
1374 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1375 "Switch to another buffer, preferably one that has a client.
1376 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1378 KILLED-ONE is t in a recursive call if we have already killed one
1379 temp-file server buffer. This means we should avoid the final
1380 \"switch to some other buffer\" since we've already effectively
1381 done that.
1383 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1384 visit NEXT-BUFFER in an existing window. If non-nil, it should
1385 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1386 (if (null next-buffer)
1387 (progn
1388 (let ((rest server-clients))
1389 (while (and rest (not next-buffer))
1390 (let ((proc (car rest)))
1391 ;; Only look at frameless clients, or those in the selected
1392 ;; frame.
1393 (when (or (not (process-get proc 'frame))
1394 (eq (process-get proc 'frame) (selected-frame)))
1395 (setq next-buffer (car (process-get proc 'buffers))))
1396 (setq rest (cdr rest)))))
1397 (and next-buffer (server-switch-buffer next-buffer killed-one))
1398 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1399 ;; (switch-to-buffer (other-buffer))
1400 (message "No server buffers remain to edit")))
1401 (if (not (buffer-live-p next-buffer))
1402 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1403 ;; and try the next surviving server buffer.
1404 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1405 ;; OK, we know next-buffer is live, let's display and select it.
1406 (if (functionp server-window)
1407 (funcall server-window next-buffer)
1408 (let ((win (get-buffer-window next-buffer 0)))
1409 (if (and win (not server-window))
1410 ;; The buffer is already displayed: just reuse the
1411 ;; window. If FILEPOS is non-nil, use it to replace the
1412 ;; window's own value of point.
1413 (progn
1414 (select-window win)
1415 (set-buffer next-buffer)
1416 (when filepos
1417 (server-goto-line-column filepos)))
1418 ;; Otherwise, let's find an appropriate window.
1419 (cond ((window-live-p server-window)
1420 (select-window server-window))
1421 ((framep server-window)
1422 (unless (frame-live-p server-window)
1423 (setq server-window (make-frame)))
1424 (select-window (frame-selected-window server-window))))
1425 (when (window-minibuffer-p (selected-window))
1426 (select-window (next-window nil 'nomini 0)))
1427 ;; Move to a non-dedicated window, if we have one.
1428 (when (window-dedicated-p (selected-window))
1429 (select-window
1430 (get-window-with-predicate
1431 (lambda (w)
1432 (and (not (window-dedicated-p w))
1433 (equal (frame-terminal (window-frame w))
1434 (frame-terminal (selected-frame)))))
1435 'nomini 'visible (selected-window))))
1436 (condition-case nil
1437 (switch-to-buffer next-buffer)
1438 ;; After all the above, we might still have ended up with
1439 ;; a minibuffer/dedicated-window (if there's no other).
1440 (error (pop-to-buffer next-buffer)))))))
1441 (when server-raise-frame
1442 (select-frame-set-input-focus (window-frame (selected-window))))))
1444 ;;;###autoload
1445 (defun server-save-buffers-kill-terminal (arg)
1446 ;; Called from save-buffers-kill-terminal in files.el.
1447 "Offer to save each buffer, then kill the current client.
1448 With ARG non-nil, silently save all file-visiting buffers, then kill.
1450 If emacsclient was started with a list of filenames to edit, then
1451 only these files will be asked to be saved."
1452 (let ((proc (frame-parameter (selected-frame) 'client)))
1453 (cond ((eq proc 'nowait)
1454 ;; Nowait frames have no client buffer list.
1455 (if (cdr (frame-list))
1456 (progn (save-some-buffers arg)
1457 (delete-frame))
1458 ;; If we're the last frame standing, kill Emacs.
1459 (save-buffers-kill-emacs arg)))
1460 ((processp proc)
1461 (let ((buffers (process-get proc 'buffers)))
1462 ;; If client is bufferless, emulate a normal Emacs exit
1463 ;; and offer to save all buffers. Otherwise, offer to
1464 ;; save only the buffers belonging to the client.
1465 (save-some-buffers
1466 arg (if buffers
1467 (lambda () (memq (current-buffer) buffers))
1469 (server-delete-client proc)))
1470 (t (error "Invalid client frame")))))
1472 (define-key ctl-x-map "#" 'server-edit)
1474 (defun server-unload-function ()
1475 "Unload the server library."
1476 (server-mode -1)
1477 (substitute-key-definition 'server-edit nil ctl-x-map)
1478 (save-current-buffer
1479 (dolist (buffer (buffer-list))
1480 (set-buffer buffer)
1481 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1482 ;; continue standard unloading
1483 nil)
1486 (provide 'server)
1488 ;;; server.el ends here