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