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