* fileio.c (Finsert_file_contents): Undo previous change.
[emacs.git] / lisp / server.el
blobe02f63a8268ef15391ee1a5ad682ece2e713d216
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 a prefix argument ARG, enable Server mode if ARG is
673 positive, and disable it otherwise. If called from Lisp, enable
674 Server mode if ARG is omitted or nil.
676 Server mode runs a process that accepts commands from the
677 `emacsclient' program. See Info node `Emacs server' and
678 `server-start' for details."
679 :global t
680 :group 'server
681 :version "22.1"
682 ;; Fixme: Should this check for an existing server socket and do
683 ;; nothing if there is one (for multiple Emacs sessions)?
684 (server-start (not server-mode)))
686 (defun server-eval-and-print (expr proc)
687 "Eval EXPR and send the result back to client PROC."
688 ;; While we're running asynchronously (from a process filter), it is likely
689 ;; that the emacsclient command was run in response to a user
690 ;; action, so the user probably knows that Emacs is processing this
691 ;; emacsclient request, so if we get a C-g it's likely that the user
692 ;; intended it to interrupt us rather than interrupt whatever Emacs
693 ;; was doing before it started handling the process filter.
694 ;; Hence `with-local-quit' (bug#6585).
695 (let ((v (with-local-quit (eval (car (read-from-string expr))))))
696 (when proc
697 (with-temp-buffer
698 (let ((standard-output (current-buffer)))
699 (pp v)
700 (let ((text (buffer-substring-no-properties
701 (point-min) (point-max))))
702 (server-send-string
703 proc (format "-print %s\n"
704 (server-quote-arg text)))))))))
706 (defun server-create-tty-frame (tty type proc)
707 (unless tty
708 (error "Invalid terminal device"))
709 (unless type
710 (error "Invalid terminal type"))
711 (add-to-list 'frame-inherited-parameters 'client)
712 (let ((frame
713 (server-with-environment (process-get proc 'env)
714 '("LANG" "LC_CTYPE" "LC_ALL"
715 ;; For tgetent(3); list according to ncurses(3).
716 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
717 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
718 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
719 "TERMINFO_DIRS" "TERMPATH"
720 ;; rxvt wants these
721 "COLORFGBG" "COLORTERM")
722 (make-frame `((window-system . nil)
723 (tty . ,tty)
724 (tty-type . ,type)
725 ;; Ignore nowait here; we always need to
726 ;; clean up opened ttys when the client dies.
727 (client . ,proc)
728 ;; This is a leftover from an earlier
729 ;; attempt at making it possible for process
730 ;; run in the server process to use the
731 ;; environment of the client process.
732 ;; It has no effect now and to make it work
733 ;; we'd need to decide how to make
734 ;; process-environment interact with client
735 ;; envvars, and then to change the
736 ;; C functions `child_setup' and
737 ;; `getenv_internal' accordingly.
738 (environment . ,(process-get proc 'env)))))))
740 ;; ttys don't use the `display' parameter, but callproc.c does to set
741 ;; the DISPLAY environment on subprocesses.
742 (set-frame-parameter frame 'display
743 (getenv-internal "DISPLAY" (process-get proc 'env)))
744 (select-frame frame)
745 (process-put proc 'frame frame)
746 (process-put proc 'terminal (frame-terminal frame))
748 ;; Display *scratch* by default.
749 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
751 frame))
753 (defun server-create-window-system-frame (display nowait proc parent-id
754 &optional parameters)
755 (add-to-list 'frame-inherited-parameters 'client)
756 (if (not (fboundp 'make-frame-on-display))
757 (progn
758 ;; This emacs does not support X.
759 (server-log "Window system unsupported" proc)
760 (server-send-string proc "-window-system-unsupported \n")
761 nil)
762 ;; Flag frame as client-created, but use a dummy client.
763 ;; This will prevent the frame from being deleted when
764 ;; emacsclient quits while also preventing
765 ;; `server-save-buffers-kill-terminal' from unexpectedly
766 ;; killing emacs on that frame.
767 (let* ((params `((client . ,(if nowait 'nowait proc))
768 ;; This is a leftover, see above.
769 (environment . ,(process-get proc 'env))
770 ,@parameters))
771 (display (or display
772 (frame-parameter nil 'display)
773 (getenv "DISPLAY")
774 (error "Please specify display")))
775 frame)
776 (if parent-id
777 (push (cons 'parent-id (string-to-number parent-id)) params))
778 (setq frame (make-frame-on-display display params))
779 (server-log (format "%s created" frame) proc)
780 (select-frame frame)
781 (process-put proc 'frame frame)
782 (process-put proc 'terminal (frame-terminal frame))
784 ;; Display *scratch* by default.
785 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
786 frame)))
788 (defun server-goto-toplevel (proc)
789 (condition-case nil
790 ;; If we're running isearch, we must abort it to allow Emacs to
791 ;; display the buffer and switch to it.
792 (dolist (buffer (buffer-list))
793 (with-current-buffer buffer
794 (when (bound-and-true-p isearch-mode)
795 (isearch-cancel))))
796 ;; Signaled by isearch-cancel.
797 (quit (message nil)))
798 (when (> (recursion-depth) 0)
799 ;; We're inside a minibuffer already, so if the emacs-client is trying
800 ;; to open a frame on a new display, we might end up with an unusable
801 ;; frame because input from that display will be blocked (until exiting
802 ;; the minibuffer). Better exit this minibuffer right away.
803 ;; Similarly with recursive-edits such as the splash screen.
804 (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
805 (top-level)))
807 ;; We use various special properties on process objects:
808 ;; - `env' stores the info about the environment of the emacsclient process.
809 ;; - `continuation' is a no-arg function that we need to execute. It contains
810 ;; commands we wanted to execute in some earlier invocation of the process
811 ;; filter but that we somehow were unable to process at that time
812 ;; (e.g. because we first need to throw to the toplevel).
814 (defun server-execute-continuation (proc)
815 (let ((continuation (process-get proc 'continuation)))
816 (process-put proc 'continuation nil)
817 (if continuation (ignore-errors (funcall continuation)))))
819 (defun* server-process-filter (proc string)
820 "Process a request from the server to edit some files.
821 PROC is the server process. STRING consists of a sequence of
822 commands prefixed by a dash. Some commands have arguments;
823 these are &-quoted and need to be decoded by `server-unquote-arg'.
824 The filter parses and executes these commands.
826 To illustrate the protocol, here is an example command that
827 emacsclient sends to create a new X frame (note that the whole
828 sequence is sent on a single line):
830 -env HOME=/home/lorentey
831 -env DISPLAY=:0.0
832 ... lots of other -env commands
833 -display :0.0
834 -window-system
836 The following commands are accepted by the server:
838 `-auth AUTH-STRING'
839 Authenticate the client using the secret authentication string
840 AUTH-STRING.
842 `-env NAME=VALUE'
843 An environment variable on the client side.
845 `-dir DIRNAME'
846 The current working directory of the client process.
848 `-current-frame'
849 Forbid the creation of new frames.
851 `-frame-parameters ALIST'
852 Set the parameters of the created frame.
854 `-nowait'
855 Request that the next frame created should not be
856 associated with this client.
858 `-display DISPLAY'
859 Set the display name to open X frames on.
861 `-position LINE[:COLUMN]'
862 Go to the given line and column number
863 in the next file opened.
865 `-file FILENAME'
866 Load the given file in the current frame.
868 `-eval EXPR'
869 Evaluate EXPR as a Lisp expression and return the
870 result in -print commands.
872 `-window-system'
873 Open a new X frame.
875 `-tty DEVICENAME TYPE'
876 Open a new tty frame at the client.
878 `-suspend'
879 Suspend this tty frame. The client sends this string in
880 response to SIGTSTP and SIGTTOU. The server must cease all I/O
881 on this tty until it gets a -resume command.
883 `-resume'
884 Resume this tty frame. The client sends this string when it
885 gets the SIGCONT signal and it is the foreground process on its
886 controlling tty.
888 `-ignore COMMENT'
889 Do nothing, but put the comment in the server log.
890 Useful for debugging.
893 The following commands are accepted by the client:
895 `-emacs-pid PID'
896 Describes the process id of the Emacs process;
897 used to forward window change signals to it.
899 `-window-system-unsupported'
900 Signals that the server does not support creating X frames;
901 the client must try again with a tty frame.
903 `-print STRING'
904 Print STRING on stdout. Used to send values
905 returned by -eval.
907 `-error DESCRIPTION'
908 Signal an error and delete process PROC.
910 `-suspend'
911 Suspend this terminal, i.e., stop the client process.
912 Sent when the user presses C-z."
913 (server-log (concat "Received " string) proc)
914 ;; First things first: let's check the authentication
915 (unless (process-get proc :authenticated)
916 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
917 (equal (match-string 1 string) (process-get proc :auth-key)))
918 (progn
919 (setq string (substring string (match-end 0)))
920 (process-put proc :authenticated t)
921 (server-log "Authentication successful" proc))
922 (server-log "Authentication failed" proc)
923 (server-send-string
924 proc (concat "-error " (server-quote-arg "Authentication failed")))
925 ;; Before calling `delete-process', give emacsclient time to
926 ;; receive the error string and shut down on its own.
927 (sit-for 1)
928 (delete-process proc)
929 ;; We return immediately
930 (return-from server-process-filter)))
931 (let ((prev (process-get proc 'previous-string)))
932 (when prev
933 (setq string (concat prev string))
934 (process-put proc 'previous-string nil)))
935 (condition-case err
936 (progn
937 (server-add-client proc)
938 ;; Send our pid
939 (server-send-string proc (concat "-emacs-pid "
940 (number-to-string (emacs-pid)) "\n"))
941 (if (not (string-match "\n" string))
942 ;; Save for later any partial line that remains.
943 (when (> (length string) 0)
944 (process-put proc 'previous-string string))
946 ;; In earlier versions of server.el (where we used an `emacsserver'
947 ;; process), there could be multiple lines. Nowadays this is not
948 ;; supported any more.
949 (assert (eq (match-end 0) (length string)))
950 (let ((request (substring string 0 (match-beginning 0)))
951 (coding-system (and (default-value 'enable-multibyte-characters)
952 (or file-name-coding-system
953 default-file-name-coding-system)))
954 nowait ; t if emacsclient does not want to wait for us.
955 frame ; Frame opened for the client (if any).
956 display ; Open frame on this display.
957 parent-id ; Window ID for XEmbed
958 dontkill ; t if client should not be killed.
959 commands
961 use-current-frame
962 frame-parameters ;parameters for newly created frame
963 tty-name ; nil, `window-system', or the tty name.
964 tty-type ; string.
965 files
966 filepos
967 args-left)
968 ;; Remove this line from STRING.
969 (setq string (substring string (match-end 0)))
970 (setq args-left
971 (mapcar 'server-unquote-arg (split-string request " " t)))
972 (while args-left
973 (pcase (pop args-left)
974 ;; -version CLIENT-VERSION: obsolete at birth.
975 (`"-version" (pop args-left))
977 ;; -nowait: Emacsclient won't wait for a result.
978 (`"-nowait" (setq nowait t))
980 ;; -current-frame: Don't create frames.
981 (`"-current-frame" (setq use-current-frame t))
983 ;; -frame-parameters: Set frame parameters
984 (`"-frame-parameters"
985 (let ((alist (pop args-left)))
986 (if coding-system
987 (setq alist (decode-coding-string alist coding-system)))
988 (setq frame-parameters (car (read-from-string alist)))))
990 ;; -display DISPLAY:
991 ;; Open X frames on the given display instead of the default.
992 (`"-display"
993 (setq display (pop args-left))
994 (if (zerop (length display)) (setq display nil)))
996 ;; -parent-id ID:
997 ;; Open X frame within window ID, via XEmbed.
998 (`"-parent-id"
999 (setq parent-id (pop args-left))
1000 (if (zerop (length parent-id)) (setq parent-id nil)))
1002 ;; -window-system: Open a new X frame.
1003 (`"-window-system"
1004 (setq dontkill t)
1005 (setq tty-name 'window-system))
1007 ;; -resume: Resume a suspended tty frame.
1008 (`"-resume"
1009 (let ((terminal (process-get proc 'terminal)))
1010 (setq dontkill t)
1011 (push (lambda ()
1012 (when (eq (terminal-live-p terminal) t)
1013 (resume-tty terminal)))
1014 commands)))
1016 ;; -suspend: Suspend the client's frame. (In case we
1017 ;; get out of sync, and a C-z sends a SIGTSTP to
1018 ;; emacsclient.)
1019 (`"-suspend"
1020 (let ((terminal (process-get proc 'terminal)))
1021 (setq dontkill t)
1022 (push (lambda ()
1023 (when (eq (terminal-live-p terminal) t)
1024 (suspend-tty terminal)))
1025 commands)))
1027 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1028 ;; (The given comment appears in the server log.)
1029 (`"-ignore"
1030 (setq dontkill t)
1031 (pop args-left))
1033 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1034 (`"-tty"
1035 (setq tty-name (pop args-left)
1036 tty-type (pop args-left)
1037 dontkill (or dontkill
1038 (not use-current-frame))))
1040 ;; -position LINE[:COLUMN]: Set point to the given
1041 ;; position in the next file.
1042 (`"-position"
1043 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1044 (car args-left)))
1045 (error "Invalid -position command in client args"))
1046 (let ((arg (pop args-left)))
1047 (setq filepos
1048 (cons (string-to-number (match-string 1 arg))
1049 (string-to-number (or (match-string 2 arg)
1050 ""))))))
1052 ;; -file FILENAME: Load the given file.
1053 (`"-file"
1054 (let ((file (pop args-left)))
1055 (if coding-system
1056 (setq file (decode-coding-string file coding-system)))
1057 (setq file (expand-file-name file dir))
1058 (push (cons file filepos) files)
1059 (server-log (format "New file: %s %s"
1060 file (or filepos "")) proc))
1061 (setq filepos nil))
1063 ;; -eval EXPR: Evaluate a Lisp expression.
1064 (`"-eval"
1065 (if use-current-frame
1066 (setq use-current-frame 'always))
1067 (let ((expr (pop args-left)))
1068 (if coding-system
1069 (setq expr (decode-coding-string expr coding-system)))
1070 (push (lambda () (server-eval-and-print expr proc))
1071 commands)
1072 (setq filepos nil)))
1074 ;; -env NAME=VALUE: An environment variable.
1075 (`"-env"
1076 (let ((var (pop args-left)))
1077 ;; XXX Variables should be encoded as in getenv/setenv.
1078 (process-put proc 'env
1079 (cons var (process-get proc 'env)))))
1081 ;; -dir DIRNAME: The cwd of the emacsclient process.
1082 (`"-dir"
1083 (setq dir (pop args-left))
1084 (if coding-system
1085 (setq dir (decode-coding-string dir coding-system)))
1086 (setq dir (command-line-normalize-file-name dir)))
1088 ;; Unknown command.
1089 (arg (error "Unknown command: %s" arg))))
1091 (setq frame
1092 (cond
1093 ((and use-current-frame
1094 (or (eq use-current-frame 'always)
1095 ;; We can't use the Emacs daemon's
1096 ;; terminal frame.
1097 (not (and (daemonp)
1098 (null (cdr (frame-list)))
1099 (eq (selected-frame)
1100 terminal-frame)))))
1101 (setq tty-name nil tty-type nil)
1102 (if display (server-select-display display)))
1103 ((eq tty-name 'window-system)
1104 (server-create-window-system-frame display nowait proc
1105 parent-id
1106 frame-parameters))
1107 ;; When resuming on a tty, tty-name is nil.
1108 (tty-name
1109 (server-create-tty-frame tty-name tty-type proc))))
1111 (process-put
1112 proc 'continuation
1113 (lambda ()
1114 (with-current-buffer (get-buffer-create server-buffer)
1115 ;; Use the same cwd as the emacsclient, if possible, so
1116 ;; relative file names work correctly, even in `eval'.
1117 (let ((default-directory
1118 (if (and dir (file-directory-p dir))
1119 dir default-directory)))
1120 (server-execute proc files nowait commands
1121 dontkill frame tty-name)))))
1123 (when (or frame files)
1124 (server-goto-toplevel proc))
1126 (server-execute-continuation proc))))
1127 ;; condition-case
1128 (error (server-return-error proc err))))
1130 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1131 ;; This is run from timers and process-filters, i.e. "asynchronously".
1132 ;; But w.r.t the user, this is not really asynchronous since the timer
1133 ;; is run after 0s and the process-filter is run in response to the
1134 ;; user running `emacsclient'. So it is OK to override the
1135 ;; inhibit-quit flag, which is good since `commands' (as well as
1136 ;; find-file-noselect via the major-mode) can run arbitrary code,
1137 ;; including code that needs to wait.
1138 (with-local-quit
1139 (condition-case err
1140 (let* ((buffers
1141 (when files
1142 (server-visit-files files proc nowait))))
1144 (mapc 'funcall (nreverse commands))
1146 ;; Delete the client if necessary.
1147 (cond
1148 (nowait
1149 ;; Client requested nowait; return immediately.
1150 (server-log "Close nowait client" proc)
1151 (server-delete-client proc))
1152 ((and (not dontkill) (null buffers))
1153 ;; This client is empty; get rid of it immediately.
1154 (server-log "Close empty client" proc)
1155 (server-delete-client proc)))
1156 (cond
1157 ((or isearch-mode (minibufferp))
1158 nil)
1159 ((and frame (null buffers))
1160 (message "%s" (substitute-command-keys
1161 "When done with this frame, type \\[delete-frame]")))
1162 ((not (null buffers))
1163 (server-switch-buffer (car buffers) nil (cdr (car files)))
1164 (run-hooks 'server-switch-hook)
1165 (unless nowait
1166 (message "%s" (substitute-command-keys
1167 "When done with a buffer, type \\[server-edit]")))))
1168 (when (and frame (null tty-name))
1169 (server-unselect-display frame)))
1170 ((quit error)
1171 (when (eq (car err) 'quit)
1172 (message "Quit emacsclient request"))
1173 (server-return-error proc err)))))
1175 (defun server-return-error (proc err)
1176 (ignore-errors
1177 (server-send-string
1178 proc (concat "-error " (server-quote-arg
1179 (error-message-string err))))
1180 (server-log (error-message-string err) proc)
1181 ;; Before calling `delete-process', give emacsclient time to
1182 ;; receive the error string and shut down on its own.
1183 (sit-for 5)
1184 (delete-process proc)))
1186 (defun server-goto-line-column (line-col)
1187 "Move point to the position indicated in LINE-COL.
1188 LINE-COL should be a pair (LINE . COL)."
1189 (when line-col
1190 (goto-char (point-min))
1191 (forward-line (1- (car line-col)))
1192 (let ((column-number (cdr line-col)))
1193 (when (> column-number 0)
1194 (move-to-column (1- column-number))))))
1196 (defun server-visit-files (files proc &optional nowait)
1197 "Find FILES and return a list of buffers created.
1198 FILES is an alist whose elements are (FILENAME . FILEPOS)
1199 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1200 PROC is the client that requested this operation.
1201 NOWAIT non-nil means this client is not waiting for the results,
1202 so don't mark these buffers specially, just visit them normally."
1203 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1204 (let ((last-nonmenu-event t) client-record)
1205 ;; Restore the current buffer afterward, but not using save-excursion,
1206 ;; because we don't want to save point in this buffer
1207 ;; if it happens to be one of those specified by the server.
1208 (save-current-buffer
1209 (dolist (file files)
1210 ;; If there is an existing buffer modified or the file is
1211 ;; modified, revert it. If there is an existing buffer with
1212 ;; deleted file, offer to write it.
1213 (let* ((minibuffer-auto-raise (or server-raise-frame
1214 minibuffer-auto-raise))
1215 (filen (car file))
1216 (obuf (get-file-buffer filen)))
1217 (add-to-history 'file-name-history filen)
1218 (if (null obuf)
1219 (progn
1220 (run-hooks 'pre-command-hook)
1221 (set-buffer (find-file-noselect filen)))
1222 (set-buffer obuf)
1223 ;; separately for each file, in sync with post-command hooks,
1224 ;; with the new buffer current:
1225 (run-hooks 'pre-command-hook)
1226 (cond ((file-exists-p filen)
1227 (when (not (verify-visited-file-modtime obuf))
1228 (revert-buffer t nil)))
1230 (when (y-or-n-p
1231 (concat "File no longer exists: " filen
1232 ", write buffer to file? "))
1233 (write-file filen))))
1234 (unless server-buffer-clients
1235 (setq server-existing-buffer t)))
1236 (server-goto-line-column (cdr file))
1237 (run-hooks 'server-visit-hook)
1238 ;; hooks may be specific to current buffer:
1239 (run-hooks 'post-command-hook))
1240 (unless nowait
1241 ;; When the buffer is killed, inform the clients.
1242 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1243 (push proc server-buffer-clients))
1244 (push (current-buffer) client-record)))
1245 (unless nowait
1246 (process-put proc 'buffers
1247 (nconc (process-get proc 'buffers) client-record)))
1248 client-record))
1250 (defvar server-kill-buffer-running nil
1251 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1253 (defun server-buffer-done (buffer &optional for-killing)
1254 "Mark BUFFER as \"done\" for its client(s).
1255 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1256 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1257 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1258 a temp file).
1259 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1260 (let ((next-buffer nil)
1261 (killed nil))
1262 (dolist (proc server-clients)
1263 (let ((buffers (process-get proc 'buffers)))
1264 (or next-buffer
1265 (setq next-buffer (nth 1 (memq buffer buffers))))
1266 (when buffers ; Ignore bufferless clients.
1267 (setq buffers (delq buffer buffers))
1268 ;; Delete all dead buffers from PROC.
1269 (dolist (b buffers)
1270 (and (bufferp b)
1271 (not (buffer-live-p b))
1272 (setq buffers (delq b buffers))))
1273 (process-put proc 'buffers buffers)
1274 ;; If client now has no pending buffers,
1275 ;; tell it that it is done, and forget it entirely.
1276 (unless buffers
1277 (server-log "Close" proc)
1278 (if for-killing
1279 ;; `server-delete-client' might delete the client's
1280 ;; frames, which might change the current buffer. We
1281 ;; don't want that (bug#640).
1282 (save-current-buffer
1283 (server-delete-client proc))
1284 (server-delete-client proc))))))
1285 (when (and (bufferp buffer) (buffer-name buffer))
1286 ;; We may or may not kill this buffer;
1287 ;; if we do, do not call server-buffer-done recursively
1288 ;; from kill-buffer-hook.
1289 (let ((server-kill-buffer-running t))
1290 (with-current-buffer buffer
1291 (setq server-buffer-clients nil)
1292 (run-hooks 'server-done-hook))
1293 ;; Notice whether server-done-hook killed the buffer.
1294 (if (null (buffer-name buffer))
1295 (setq killed t)
1296 ;; Don't bother killing or burying the buffer
1297 ;; when we are called from kill-buffer.
1298 (unless for-killing
1299 (when (and (not killed)
1300 server-kill-new-buffers
1301 (with-current-buffer buffer
1302 (not server-existing-buffer)))
1303 (setq killed t)
1304 (bury-buffer buffer)
1305 ;; Prevent kill-buffer from prompting (Bug#3696).
1306 (with-current-buffer buffer
1307 (set-buffer-modified-p nil))
1308 (kill-buffer buffer))
1309 (unless killed
1310 (if (server-temp-file-p buffer)
1311 (progn
1312 (with-current-buffer buffer
1313 (set-buffer-modified-p nil))
1314 (kill-buffer buffer)
1315 (setq killed t))
1316 (bury-buffer buffer)))))))
1317 (list next-buffer killed)))
1319 (defun server-temp-file-p (&optional buffer)
1320 "Return non-nil if BUFFER contains a file considered temporary.
1321 These are files whose names suggest they are repeatedly
1322 reused to pass information to another program.
1324 The variable `server-temp-file-regexp' controls which filenames
1325 are considered temporary."
1326 (and (buffer-file-name buffer)
1327 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1329 (defun server-done ()
1330 "Offer to save current buffer, mark it as \"done\" for clients.
1331 This kills or buries the buffer, then returns a list
1332 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1333 as a suggestion for what to select next, or nil.
1334 KILLED is t if we killed BUFFER, which happens if it was created
1335 specifically for the clients and did not exist before their request for it."
1336 (when server-buffer-clients
1337 (if (server-temp-file-p)
1338 ;; For a temp file, save, and do make a non-numeric backup
1339 ;; (unless make-backup-files is nil).
1340 (let ((version-control nil)
1341 (buffer-backed-up nil))
1342 (save-buffer))
1343 (when (and (buffer-modified-p)
1344 buffer-file-name
1345 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1346 (save-buffer)))
1347 (server-buffer-done (current-buffer))))
1349 ;; Ask before killing a server buffer.
1350 ;; It was suggested to release its client instead,
1351 ;; but I think that is dangerous--the client would proceed
1352 ;; using whatever is on disk in that file. -- rms.
1353 (defun server-kill-buffer-query-function ()
1354 "Ask before killing a server buffer."
1355 (or (not server-buffer-clients)
1356 (let ((res t))
1357 (dolist (proc server-buffer-clients)
1358 (when (and (memq proc server-clients)
1359 (eq (process-status proc) 'open))
1360 (setq res nil)))
1361 res)
1362 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1363 (buffer-name (current-buffer))))))
1365 (defun server-kill-emacs-query-function ()
1366 "Ask before exiting Emacs if it has live clients."
1367 (or (not server-clients)
1368 (let (live-client)
1369 (dolist (proc server-clients)
1370 (when (memq t (mapcar 'buffer-live-p (process-get
1371 proc 'buffers)))
1372 (setq live-client t)))
1373 live-client)
1374 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1376 (defun server-kill-buffer ()
1377 "Remove the current buffer from its clients' buffer list.
1378 Designed to be added to `kill-buffer-hook'."
1379 ;; Prevent infinite recursion if user has made server-done-hook
1380 ;; call kill-buffer.
1381 (or server-kill-buffer-running
1382 (and server-buffer-clients
1383 (let ((server-kill-buffer-running t))
1384 (when server-process
1385 (server-buffer-done (current-buffer) t))))))
1387 (defun server-edit (&optional arg)
1388 "Switch to next server editing buffer; say \"Done\" for current buffer.
1389 If a server buffer is current, it is marked \"done\" and optionally saved.
1390 The buffer is also killed if it did not exist before the clients asked for it.
1391 When all of a client's buffers are marked as \"done\", the client is notified.
1393 Temporary files such as MH <draft> files are always saved and backed up,
1394 no questions asked. (The variable `make-backup-files', if nil, still
1395 inhibits a backup; you can set it locally in a particular buffer to
1396 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1397 which filenames are considered temporary.
1399 If invoked with a prefix argument, or if there is no server process running,
1400 starts server process and that is all. Invoked by \\[server-edit]."
1401 (interactive "P")
1402 (cond
1403 ((or arg
1404 (not server-process)
1405 (memq (process-status server-process) '(signal exit)))
1406 (server-mode 1))
1407 (server-clients (apply 'server-switch-buffer (server-done)))
1408 (t (message "No server editing buffers exist"))))
1410 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1411 "Switch to another buffer, preferably one that has a client.
1412 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1414 KILLED-ONE is t in a recursive call if we have already killed one
1415 temp-file server buffer. This means we should avoid the final
1416 \"switch to some other buffer\" since we've already effectively
1417 done that.
1419 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1420 visit NEXT-BUFFER in an existing window. If non-nil, it should
1421 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1422 (if (null next-buffer)
1423 (progn
1424 (let ((rest server-clients))
1425 (while (and rest (not next-buffer))
1426 (let ((proc (car rest)))
1427 ;; Only look at frameless clients, or those in the selected
1428 ;; frame.
1429 (when (or (not (process-get proc 'frame))
1430 (eq (process-get proc 'frame) (selected-frame)))
1431 (setq next-buffer (car (process-get proc 'buffers))))
1432 (setq rest (cdr rest)))))
1433 (and next-buffer (server-switch-buffer next-buffer killed-one))
1434 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1435 ;; (switch-to-buffer (other-buffer))
1436 (message "No server buffers remain to edit")))
1437 (if (not (buffer-live-p next-buffer))
1438 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1439 ;; and try the next surviving server buffer.
1440 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1441 ;; OK, we know next-buffer is live, let's display and select it.
1442 (if (functionp server-window)
1443 (funcall server-window next-buffer)
1444 (let ((win (get-buffer-window next-buffer 0)))
1445 (if (and win (not server-window))
1446 ;; The buffer is already displayed: just reuse the
1447 ;; window. If FILEPOS is non-nil, use it to replace the
1448 ;; window's own value of point.
1449 (progn
1450 (select-window win)
1451 (set-buffer next-buffer)
1452 (when filepos
1453 (server-goto-line-column filepos)))
1454 ;; Otherwise, let's find an appropriate window.
1455 (cond ((window-live-p server-window)
1456 (select-window server-window))
1457 ((framep server-window)
1458 (unless (frame-live-p server-window)
1459 (setq server-window (make-frame)))
1460 (select-window (frame-selected-window server-window))))
1461 (when (window-minibuffer-p (selected-window))
1462 (select-window (next-window nil 'nomini 0)))
1463 ;; Move to a non-dedicated window, if we have one.
1464 (when (window-dedicated-p (selected-window))
1465 (select-window
1466 (get-window-with-predicate
1467 (lambda (w)
1468 (and (not (window-dedicated-p w))
1469 (equal (frame-terminal (window-frame w))
1470 (frame-terminal (selected-frame)))))
1471 'nomini 'visible (selected-window))))
1472 (condition-case nil
1473 (switch-to-buffer next-buffer)
1474 ;; After all the above, we might still have ended up with
1475 ;; a minibuffer/dedicated-window (if there's no other).
1476 (error (pop-to-buffer next-buffer)))))))
1477 (when server-raise-frame
1478 (select-frame-set-input-focus (window-frame (selected-window))))))
1480 ;;;###autoload
1481 (defun server-save-buffers-kill-terminal (arg)
1482 ;; Called from save-buffers-kill-terminal in files.el.
1483 "Offer to save each buffer, then kill the current client.
1484 With ARG non-nil, silently save all file-visiting buffers, then kill.
1486 If emacsclient was started with a list of filenames to edit, then
1487 only these files will be asked to be saved."
1488 (let ((proc (frame-parameter (selected-frame) 'client)))
1489 (cond ((eq proc 'nowait)
1490 ;; Nowait frames have no client buffer list.
1491 (if (cdr (frame-list))
1492 (progn (save-some-buffers arg)
1493 (delete-frame))
1494 ;; If we're the last frame standing, kill Emacs.
1495 (save-buffers-kill-emacs arg)))
1496 ((processp proc)
1497 (let ((buffers (process-get proc 'buffers)))
1498 ;; If client is bufferless, emulate a normal Emacs exit
1499 ;; and offer to save all buffers. Otherwise, offer to
1500 ;; save only the buffers belonging to the client.
1501 (save-some-buffers
1502 arg (if buffers
1503 (lambda () (memq (current-buffer) buffers))
1505 (server-delete-client proc)))
1506 (t (error "Invalid client frame")))))
1508 (define-key ctl-x-map "#" 'server-edit)
1510 (defun server-unload-function ()
1511 "Unload the server library."
1512 (server-mode -1)
1513 (substitute-key-definition 'server-edit nil ctl-x-map)
1514 (save-current-buffer
1515 (dolist (buffer (buffer-list))
1516 (set-buffer buffer)
1517 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1518 ;; continue standard unloading
1519 nil)
1521 (defun server-eval-at (server form)
1522 "Eval FORM on Emacs Server SERVER."
1523 (let ((auth-file (expand-file-name server server-auth-dir))
1524 (coding-system-for-read 'binary)
1525 (coding-system-for-write 'binary)
1526 address port secret process)
1527 (unless (file-exists-p auth-file)
1528 (error "No such server definition: %s" auth-file))
1529 (with-temp-buffer
1530 (insert-file-contents auth-file)
1531 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1532 (error "Invalid auth file"))
1533 (setq address (match-string 1)
1534 port (string-to-number (match-string 2)))
1535 (forward-line 1)
1536 (setq secret (buffer-substring (point) (line-end-position)))
1537 (erase-buffer)
1538 (unless (setq process (open-network-stream "eval-at" (current-buffer)
1539 address port))
1540 (error "Unable to contact the server"))
1541 (set-process-query-on-exit-flag process nil)
1542 (process-send-string
1543 process
1544 (concat "-auth " secret " -eval "
1545 (replace-regexp-in-string
1546 " " "&_" (format "%S" form))
1547 "\n"))
1548 (while (memq (process-status process) '(open run))
1549 (accept-process-output process 0 10))
1550 (goto-char (point-min))
1551 ;; If the result is nil, there's nothing in the buffer. If the
1552 ;; result is non-nil, it's after "-print ".
1553 (when (search-forward "\n-print" nil t)
1554 (let ((start (point)))
1555 (while (search-forward "&_" nil t)
1556 (replace-match " " t t))
1557 (goto-char start)
1558 (read (current-buffer)))))))
1561 (provide 'server)
1563 ;;; server.el ends here