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