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>
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/>.
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
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.
77 ;; - handle command-line-args-left.
78 ;; - move most of the args processing and decision making from emacsclient.c
80 ;; - fix up handling of the client's environment (place it in the terminal?).
84 (eval-when-compile (require 'cl
))
87 "Emacs running as a server process."
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
))
95 (unless load-in-progress
96 (message "Local sockets unsupported, using TCP sockets")))
98 (set-default sym val
))
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."
108 (string :tag
"Name or IP address")
109 (const :tag
"Local" nil
))
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
121 (string :tag
"Port number")
122 (const :tag
"Random" nil
))
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."
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."
146 (defcustom server-visit-hook nil
147 "Hook run when visiting a file for the Emacs server."
151 (defcustom server-switch-hook nil
152 "Hook run when switching to a buffer for the Emacs server."
156 (defcustom server-done-hook nil
157 "Hook run when done editing a buffer for the Emacs server."
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."
186 :type
'(choice (const :tag
"Use selected window"
187 :match
(lambda (widget value
)
188 (not (functionp value
)))
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."
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
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."
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."
241 (dolist (proc server-clients
)
242 (when (equal value
(process-get proc property
))
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'."
258 (let ((var (make-symbol "var"))
259 (value (make-symbol "value")))
260 `(let ((process-environment process-environment
))
262 (let ((,value
(getenv-internal ,var
,env
)))
263 (push (if (stringp ,value
)
264 (concat ,var
"=" ,value
)
266 process-environment
)))
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
285 (or (and server-kill-new-buffers
286 (not server-existing-buffer
))
287 (server-temp-file-p))
288 (not (buffer-modified-p)))
291 (progn (setq server-buffer-clients nil
)
292 (kill-buffer (current-buffer))
295 ;; Restore clients if user pressed C-g in `kill-buffer'.
296 (setq server-buffer-clients
(list proc
)))))))))
298 ;; Delete the client's frames.
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
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."
338 (with-current-buffer (get-buffer-create server-buffer
)
339 (goto-char (point-max))
340 (insert (funcall server-log-time-function
)
343 ((listp client
) (format " %s: " (car client
)))
344 (t (format " %s: " client
)))
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
)
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
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
)))))
389 (set-window-buffer (selected-window) buffer
)
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.
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
)
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
))))
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
)
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
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
451 See `server-unquote-arg' and `server-process-filter'."
452 (replace-regexp-in-string
453 "[-&\n ]" (lambda (s)
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
471 - it's not readable/writable by anybody else."
472 (setq dir
(directory-file-name dir
))
473 (let ((attrs (file-attributes dir
'integer
)))
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
))
482 (unless (eq t
(car attrs
)) ; is a dir?
484 (when (and w32
(zerop uid
)) ; on FAT32?
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
))
493 (unless (or (= uid
(user-uid)) ; is the dir ours?
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)))
503 (unless (zerop (logand ?
\077 (file-modes dir
)))
507 (error "The directory `%s' is unsafe" dir
)))))
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
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.
533 (null (cdr (frame-list)))
534 (eq (selected-frame) terminal-frame
))
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
)))
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
548 (let (delete-by-moving-to-trash)
549 (delete-file server-file
)))
550 (setq server-mode nil
) ;; already set by the minor mode code
553 (concat "Unable to start the Emacs server.\n"
554 (format "There is an existing Emacs server, named %S.\n"
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.")
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.
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
)
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.
579 (apply #'make-network-process
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.
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
))
598 :plist
'(:authenticated t
)))))
599 (unless server-process
(error "Could not start server process"))
600 (process-put server-process
:server-file server-file
)
604 ;; The auth key is a 64-byte string of random chars in the
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'."
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."
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
)
635 server-socket-dir
))))
637 (let (delete-by-moving-to-trash)
639 (message "Connection file %S deleted" file
))
641 (message "No connection file %S" file
)))))
643 (defun server-running-p (&optional name
)
644 "Test whether server NAME is running.
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
))
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]+\\)")
659 (string-to-number (match-string 1))))
663 (make-network-process
664 :name
"server-client-test" :family
'local
:server nil
:noquery t
665 :service
(expand-file-name name server-socket-dir
)))
670 (define-minor-mode 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."
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 (let ((v (eval (car (read-from-string expr
)))))
691 (let ((standard-output (current-buffer)))
693 (let ((text (buffer-substring-no-properties
694 (point-min) (point-max))))
696 proc
(format "-print %s\n"
697 (server-quote-arg text
)))))))))
699 (defun server-create-tty-frame (tty type proc
)
701 (error "Invalid terminal device"))
703 (error "Invalid terminal type"))
704 (add-to-list 'frame-inherited-parameters
'client
)
706 (server-with-environment (process-get proc
'env
)
707 '("LANG" "LC_CTYPE" "LC_ALL"
708 ;; For tgetent(3); list according to ncurses(3).
709 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
710 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
711 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
712 "TERMINFO_DIRS" "TERMPATH"
714 "COLORFGBG" "COLORTERM")
715 (make-frame `((window-system . nil
)
718 ;; Ignore nowait here; we always need to
719 ;; clean up opened ttys when the client dies.
721 ;; This is a leftover from an earlier
722 ;; attempt at making it possible for process
723 ;; run in the server process to use the
724 ;; environment of the client process.
725 ;; It has no effect now and to make it work
726 ;; we'd need to decide how to make
727 ;; process-environment interact with client
728 ;; envvars, and then to change the
729 ;; C functions `child_setup' and
730 ;; `getenv_internal' accordingly.
731 (environment .
,(process-get proc
'env
)))))))
733 ;; ttys don't use the `display' parameter, but callproc.c does to set
734 ;; the DISPLAY environment on subprocesses.
735 (set-frame-parameter frame
'display
736 (getenv-internal "DISPLAY" (process-get proc
'env
)))
738 (process-put proc
'frame frame
)
739 (process-put proc
'terminal
(frame-terminal frame
))
741 ;; Display *scratch* by default.
742 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
746 (defun server-create-window-system-frame (display nowait proc parent-id
747 &optional parameters
)
748 (add-to-list 'frame-inherited-parameters
'client
)
749 (if (not (fboundp 'make-frame-on-display
))
751 ;; This emacs does not support X.
752 (server-log "Window system unsupported" proc
)
753 (server-send-string proc
"-window-system-unsupported \n")
755 ;; Flag frame as client-created, but use a dummy client.
756 ;; This will prevent the frame from being deleted when
757 ;; emacsclient quits while also preventing
758 ;; `server-save-buffers-kill-terminal' from unexpectedly
759 ;; killing emacs on that frame.
760 (let* ((params `((client .
,(if nowait
'nowait proc
))
761 ;; This is a leftover, see above.
762 (environment .
,(process-get proc
'env
))
765 (frame-parameter nil
'display
)
767 (error "Please specify display")))
770 (push (cons 'parent-id
(string-to-number parent-id
)) params
))
771 (setq frame
(make-frame-on-display display params
))
772 (server-log (format "%s created" frame
) proc
)
774 (process-put proc
'frame frame
)
775 (process-put proc
'terminal
(frame-terminal frame
))
777 ;; Display *scratch* by default.
778 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
781 (defun server-goto-toplevel (proc)
783 ;; If we're running isearch, we must abort it to allow Emacs to
784 ;; display the buffer and switch to it.
785 (dolist (buffer (buffer-list))
786 (with-current-buffer buffer
787 (when (bound-and-true-p isearch-mode
)
789 ;; Signaled by isearch-cancel.
790 (quit (message nil
)))
791 (when (> (recursion-depth) 0)
792 ;; We're inside a minibuffer already, so if the emacs-client is trying
793 ;; to open a frame on a new display, we might end up with an unusable
794 ;; frame because input from that display will be blocked (until exiting
795 ;; the minibuffer). Better exit this minibuffer right away.
796 ;; Similarly with recursive-edits such as the splash screen.
797 (run-with-timer 0 nil
(lambda () (server-execute-continuation proc
)))
800 ;; We use various special properties on process objects:
801 ;; - `env' stores the info about the environment of the emacsclient process.
802 ;; - `continuation' is a no-arg function that we need to execute. It contains
803 ;; commands we wanted to execute in some earlier invocation of the process
804 ;; filter but that we somehow were unable to process at that time
805 ;; (e.g. because we first need to throw to the toplevel).
807 (defun server-execute-continuation (proc)
808 (let ((continuation (process-get proc
'continuation
)))
809 (process-put proc
'continuation nil
)
810 (if continuation
(ignore-errors (funcall continuation
)))))
812 (defun* server-process-filter
(proc string
)
813 "Process a request from the server to edit some files.
814 PROC is the server process. STRING consists of a sequence of
815 commands prefixed by a dash. Some commands have arguments;
816 these are &-quoted and need to be decoded by `server-unquote-arg'.
817 The filter parses and executes these commands.
819 To illustrate the protocol, here is an example command that
820 emacsclient sends to create a new X frame (note that the whole
821 sequence is sent on a single line):
823 -env HOME=/home/lorentey
825 ... lots of other -env commands
829 The following commands are accepted by the server:
832 Authenticate the client using the secret authentication string
836 An environment variable on the client side.
839 The current working directory of the client process.
842 Forbid the creation of new frames.
844 `-frame-parameters ALIST'
845 Set the parameters of the created frame.
848 Request that the next frame created should not be
849 associated with this client.
852 Set the display name to open X frames on.
854 `-position LINE[:COLUMN]'
855 Go to the given line and column number
856 in the next file opened.
859 Load the given file in the current frame.
862 Evaluate EXPR as a Lisp expression and return the
863 result in -print commands.
868 `-tty DEVICENAME TYPE'
869 Open a new tty frame at the client.
872 Suspend this tty frame. The client sends this string in
873 response to SIGTSTP and SIGTTOU. The server must cease all I/O
874 on this tty until it gets a -resume command.
877 Resume this tty frame. The client sends this string when it
878 gets the SIGCONT signal and it is the foreground process on its
882 Do nothing, but put the comment in the server log.
883 Useful for debugging.
886 The following commands are accepted by the client:
889 Describes the process id of the Emacs process;
890 used to forward window change signals to it.
892 `-window-system-unsupported'
893 Signals that the server does not support creating X frames;
894 the client must try again with a tty frame.
897 Print STRING on stdout. Used to send values
901 Signal an error and delete process PROC.
904 Suspend this terminal, i.e., stop the client process.
905 Sent when the user presses C-z."
906 (server-log (concat "Received " string
) proc
)
907 ;; First things first: let's check the authentication
908 (unless (process-get proc
:authenticated
)
909 (if (and (string-match "-auth \\([!-~]+\\)\n?" string
)
910 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
912 (setq string
(substring string
(match-end 0)))
913 (process-put proc
:authenticated t
)
914 (server-log "Authentication successful" proc
))
915 (server-log "Authentication failed" proc
)
917 proc
(concat "-error " (server-quote-arg "Authentication failed")))
918 ;; Before calling `delete-process', give emacsclient time to
919 ;; receive the error string and shut down on its own.
921 (delete-process proc
)
922 ;; We return immediately
923 (return-from server-process-filter
)))
924 (let ((prev (process-get proc
'previous-string
)))
926 (setq string
(concat prev string
))
927 (process-put proc
'previous-string nil
)))
930 (server-add-client proc
)
932 (server-send-string proc
(concat "-emacs-pid "
933 (number-to-string (emacs-pid)) "\n"))
934 (if (not (string-match "\n" string
))
935 ;; Save for later any partial line that remains.
936 (when (> (length string
) 0)
937 (process-put proc
'previous-string string
))
939 ;; In earlier versions of server.el (where we used an `emacsserver'
940 ;; process), there could be multiple lines. Nowadays this is not
941 ;; supported any more.
942 (assert (eq (match-end 0) (length string
)))
943 (let ((request (substring string
0 (match-beginning 0)))
944 (coding-system (and (default-value 'enable-multibyte-characters
)
945 (or file-name-coding-system
946 default-file-name-coding-system
)))
947 nowait
; t if emacsclient does not want to wait for us.
948 frame
; Frame opened for the client (if any).
949 display
; Open frame on this display.
950 parent-id
; Window ID for XEmbed
951 dontkill
; t if client should not be killed.
955 frame-parameters
;parameters for newly created frame
956 tty-name
; nil, `window-system', or the tty name.
961 ;; Remove this line from STRING.
962 (setq string
(substring string
(match-end 0)))
964 (mapcar 'server-unquote-arg
(split-string request
" " t
)))
966 (pcase (pop args-left
)
967 ;; -version CLIENT-VERSION: obsolete at birth.
968 (`"-version" (pop args-left
))
970 ;; -nowait: Emacsclient won't wait for a result.
971 (`"-nowait" (setq nowait t
))
973 ;; -current-frame: Don't create frames.
974 (`"-current-frame" (setq use-current-frame t
))
976 ;; -frame-parameters: Set frame parameters
977 (`"-frame-parameters"
978 (let ((alist (pop args-left
)))
980 (setq alist
(decode-coding-string alist coding-system
)))
981 (setq frame-parameters
(car (read-from-string alist
)))))
984 ;; Open X frames on the given display instead of the default.
986 (setq display
(pop args-left
))
987 (if (zerop (length display
)) (setq display nil
)))
990 ;; Open X frame within window ID, via XEmbed.
992 (setq parent-id
(pop args-left
))
993 (if (zerop (length parent-id
)) (setq parent-id nil
)))
995 ;; -window-system: Open a new X frame.
998 (setq tty-name
'window-system
))
1000 ;; -resume: Resume a suspended tty frame.
1002 (let ((terminal (process-get proc
'terminal
)))
1005 (when (eq (terminal-live-p terminal
) t
)
1006 (resume-tty terminal
)))
1009 ;; -suspend: Suspend the client's frame. (In case we
1010 ;; get out of sync, and a C-z sends a SIGTSTP to
1013 (let ((terminal (process-get proc
'terminal
)))
1016 (when (eq (terminal-live-p terminal
) t
)
1017 (suspend-tty terminal
)))
1020 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
1021 ;; (The given comment appears in the server log.)
1026 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1028 (setq tty-name
(pop args-left
)
1029 tty-type
(pop args-left
)
1030 dontkill
(or dontkill
1031 (not use-current-frame
))))
1033 ;; -position LINE[:COLUMN]: Set point to the given
1034 ;; position in the next file.
1036 (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1038 (error "Invalid -position command in client args"))
1039 (let ((arg (pop args-left
)))
1041 (cons (string-to-number (match-string 1 arg
))
1042 (string-to-number (or (match-string 2 arg
)
1045 ;; -file FILENAME: Load the given file.
1047 (let ((file (pop args-left
)))
1049 (setq file
(decode-coding-string file coding-system
)))
1050 (setq file
(expand-file-name file dir
))
1051 (push (cons file filepos
) files
)
1052 (server-log (format "New file: %s %s"
1053 file
(or filepos
"")) proc
))
1056 ;; -eval EXPR: Evaluate a Lisp expression.
1058 (if use-current-frame
1059 (setq use-current-frame
'always
))
1060 (let ((expr (pop args-left
)))
1062 (setq expr
(decode-coding-string expr coding-system
)))
1063 (push (lambda () (server-eval-and-print expr proc
))
1065 (setq filepos nil
)))
1067 ;; -env NAME=VALUE: An environment variable.
1069 (let ((var (pop args-left
)))
1070 ;; XXX Variables should be encoded as in getenv/setenv.
1071 (process-put proc
'env
1072 (cons var
(process-get proc
'env
)))))
1074 ;; -dir DIRNAME: The cwd of the emacsclient process.
1076 (setq dir
(pop args-left
))
1078 (setq dir
(decode-coding-string dir coding-system
)))
1079 (setq dir
(command-line-normalize-file-name dir
)))
1082 (arg (error "Unknown command: %s" arg
))))
1086 ((and use-current-frame
1087 (or (eq use-current-frame
'always
)
1088 ;; We can't use the Emacs daemon's
1091 (null (cdr (frame-list)))
1092 (eq (selected-frame)
1094 (setq tty-name nil tty-type nil
)
1095 (if display
(server-select-display display
)))
1096 ((eq tty-name
'window-system
)
1097 (server-create-window-system-frame display nowait proc
1100 ;; When resuming on a tty, tty-name is nil.
1102 (server-create-tty-frame tty-name tty-type proc
))))
1107 (with-current-buffer (get-buffer-create server-buffer
)
1108 ;; Use the same cwd as the emacsclient, if possible, so
1109 ;; relative file names work correctly, even in `eval'.
1110 (let ((default-directory
1111 (if (and dir
(file-directory-p dir
))
1112 dir default-directory
)))
1113 (server-execute proc files nowait commands
1114 dontkill frame tty-name
)))))
1116 (when (or frame files
)
1117 (server-goto-toplevel proc
))
1119 (server-execute-continuation proc
))))
1121 (error (server-return-error proc err
))))
1123 (defun server-execute (proc files nowait commands dontkill frame tty-name
)
1124 ;; This is run from timers and process-filters, i.e. "asynchronously".
1125 ;; But w.r.t the user, this is not really asynchronous since the timer
1126 ;; is run after 0s and the process-filter is run in response to the
1127 ;; user running `emacsclient'. So it is OK to override the
1128 ;; inhibit-quit flag, which is good since `commands' (as well as
1129 ;; find-file-noselect via the major-mode) can run arbitrary code,
1130 ;; including code that needs to wait.
1135 (server-visit-files files proc nowait
))))
1137 (mapc 'funcall
(nreverse commands
))
1139 ;; Delete the client if necessary.
1142 ;; Client requested nowait; return immediately.
1143 (server-log "Close nowait client" proc
)
1144 (server-delete-client proc
))
1145 ((and (not dontkill
) (null buffers
))
1146 ;; This client is empty; get rid of it immediately.
1147 (server-log "Close empty client" proc
)
1148 (server-delete-client proc
)))
1150 ((or isearch-mode
(minibufferp))
1152 ((and frame
(null buffers
))
1153 (message "%s" (substitute-command-keys
1154 "When done with this frame, type \\[delete-frame]")))
1155 ((not (null buffers
))
1156 (server-switch-buffer (car buffers
) nil
(cdr (car files
)))
1157 (run-hooks 'server-switch-hook
)
1159 (message "%s" (substitute-command-keys
1160 "When done with a buffer, type \\[server-edit]")))))
1161 (when (and frame
(null tty-name
))
1162 (server-unselect-display frame
)))
1164 (when (eq (car err
) 'quit
)
1165 (message "Quit emacsclient request"))
1166 (server-return-error proc err
)))))
1168 (defun server-return-error (proc err
)
1171 proc
(concat "-error " (server-quote-arg
1172 (error-message-string err
))))
1173 (server-log (error-message-string err
) proc
)
1174 ;; Before calling `delete-process', give emacsclient time to
1175 ;; receive the error string and shut down on its own.
1177 (delete-process proc
)))
1179 (defun server-goto-line-column (line-col)
1180 "Move point to the position indicated in LINE-COL.
1181 LINE-COL should be a pair (LINE . COL)."
1183 (goto-char (point-min))
1184 (forward-line (1- (car line-col
)))
1185 (let ((column-number (cdr line-col
)))
1186 (when (> column-number
0)
1187 (move-to-column (1- column-number
))))))
1189 (defun server-visit-files (files proc
&optional nowait
)
1190 "Find FILES and return a list of buffers created.
1191 FILES is an alist whose elements are (FILENAME . FILEPOS)
1192 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1193 PROC is the client that requested this operation.
1194 NOWAIT non-nil means this client is not waiting for the results,
1195 so don't mark these buffers specially, just visit them normally."
1196 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1197 (let ((last-nonmenu-event t
) client-record
)
1198 ;; Restore the current buffer afterward, but not using save-excursion,
1199 ;; because we don't want to save point in this buffer
1200 ;; if it happens to be one of those specified by the server.
1201 (save-current-buffer
1202 (dolist (file files
)
1203 ;; If there is an existing buffer modified or the file is
1204 ;; modified, revert it. If there is an existing buffer with
1205 ;; deleted file, offer to write it.
1206 (let* ((minibuffer-auto-raise (or server-raise-frame
1207 minibuffer-auto-raise
))
1209 (obuf (get-file-buffer filen
)))
1210 (add-to-history 'file-name-history filen
)
1213 (run-hooks 'pre-command-hook
)
1214 (set-buffer (find-file-noselect filen
)))
1216 ;; separately for each file, in sync with post-command hooks,
1217 ;; with the new buffer current:
1218 (run-hooks 'pre-command-hook
)
1219 (cond ((file-exists-p filen
)
1220 (when (not (verify-visited-file-modtime obuf
))
1221 (revert-buffer t nil
)))
1224 (concat "File no longer exists: " filen
1225 ", write buffer to file? "))
1226 (write-file filen
))))
1227 (unless server-buffer-clients
1228 (setq server-existing-buffer t
)))
1229 (server-goto-line-column (cdr file
))
1230 (run-hooks 'server-visit-hook
)
1231 ;; hooks may be specific to current buffer:
1232 (run-hooks 'post-command-hook
))
1234 ;; When the buffer is killed, inform the clients.
1235 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1236 (push proc server-buffer-clients
))
1237 (push (current-buffer) client-record
)))
1239 (process-put proc
'buffers
1240 (nconc (process-get proc
'buffers
) client-record
)))
1243 (defvar server-kill-buffer-running nil
1244 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1246 (defun server-buffer-done (buffer &optional for-killing
)
1247 "Mark BUFFER as \"done\" for its client(s).
1248 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1249 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1250 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1252 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1253 (let ((next-buffer nil
)
1255 (dolist (proc server-clients
)
1256 (let ((buffers (process-get proc
'buffers
)))
1258 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1259 (when buffers
; Ignore bufferless clients.
1260 (setq buffers
(delq buffer buffers
))
1261 ;; Delete all dead buffers from PROC.
1264 (not (buffer-live-p b
))
1265 (setq buffers
(delq b buffers
))))
1266 (process-put proc
'buffers buffers
)
1267 ;; If client now has no pending buffers,
1268 ;; tell it that it is done, and forget it entirely.
1270 (server-log "Close" proc
)
1272 ;; `server-delete-client' might delete the client's
1273 ;; frames, which might change the current buffer. We
1274 ;; don't want that (bug#640).
1275 (save-current-buffer
1276 (server-delete-client proc
))
1277 (server-delete-client proc
))))))
1278 (when (and (bufferp buffer
) (buffer-name buffer
))
1279 ;; We may or may not kill this buffer;
1280 ;; if we do, do not call server-buffer-done recursively
1281 ;; from kill-buffer-hook.
1282 (let ((server-kill-buffer-running t
))
1283 (with-current-buffer buffer
1284 (setq server-buffer-clients nil
)
1285 (run-hooks 'server-done-hook
))
1286 ;; Notice whether server-done-hook killed the buffer.
1287 (if (null (buffer-name buffer
))
1289 ;; Don't bother killing or burying the buffer
1290 ;; when we are called from kill-buffer.
1292 (when (and (not killed
)
1293 server-kill-new-buffers
1294 (with-current-buffer buffer
1295 (not server-existing-buffer
)))
1297 (bury-buffer buffer
)
1298 ;; Prevent kill-buffer from prompting (Bug#3696).
1299 (with-current-buffer buffer
1300 (set-buffer-modified-p nil
))
1301 (kill-buffer buffer
))
1303 (if (server-temp-file-p buffer
)
1305 (with-current-buffer buffer
1306 (set-buffer-modified-p nil
))
1307 (kill-buffer buffer
)
1309 (bury-buffer buffer
)))))))
1310 (list next-buffer killed
)))
1312 (defun server-temp-file-p (&optional buffer
)
1313 "Return non-nil if BUFFER contains a file considered temporary.
1314 These are files whose names suggest they are repeatedly
1315 reused to pass information to another program.
1317 The variable `server-temp-file-regexp' controls which filenames
1318 are considered temporary."
1319 (and (buffer-file-name buffer
)
1320 (string-match-p server-temp-file-regexp
(buffer-file-name buffer
))))
1322 (defun server-done ()
1323 "Offer to save current buffer, mark it as \"done\" for clients.
1324 This kills or buries the buffer, then returns a list
1325 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1326 as a suggestion for what to select next, or nil.
1327 KILLED is t if we killed BUFFER, which happens if it was created
1328 specifically for the clients and did not exist before their request for it."
1329 (when server-buffer-clients
1330 (if (server-temp-file-p)
1331 ;; For a temp file, save, and do make a non-numeric backup
1332 ;; (unless make-backup-files is nil).
1333 (let ((version-control nil
)
1334 (buffer-backed-up nil
))
1336 (when (and (buffer-modified-p)
1338 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1340 (server-buffer-done (current-buffer))))
1342 ;; Ask before killing a server buffer.
1343 ;; It was suggested to release its client instead,
1344 ;; but I think that is dangerous--the client would proceed
1345 ;; using whatever is on disk in that file. -- rms.
1346 (defun server-kill-buffer-query-function ()
1347 "Ask before killing a server buffer."
1348 (or (not server-buffer-clients
)
1350 (dolist (proc server-buffer-clients
)
1351 (when (and (memq proc server-clients
)
1352 (eq (process-status proc
) 'open
))
1355 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1356 (buffer-name (current-buffer))))))
1358 (defun server-kill-emacs-query-function ()
1359 "Ask before exiting Emacs if it has live clients."
1360 (or (not server-clients
)
1362 (dolist (proc server-clients
)
1363 (when (memq t
(mapcar 'buffer-live-p
(process-get
1365 (setq live-client t
)))
1367 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1369 (defun server-kill-buffer ()
1370 "Remove the current buffer from its clients' buffer list.
1371 Designed to be added to `kill-buffer-hook'."
1372 ;; Prevent infinite recursion if user has made server-done-hook
1373 ;; call kill-buffer.
1374 (or server-kill-buffer-running
1375 (and server-buffer-clients
1376 (let ((server-kill-buffer-running t
))
1377 (when server-process
1378 (server-buffer-done (current-buffer) t
))))))
1380 (defun server-edit (&optional arg
)
1381 "Switch to next server editing buffer; say \"Done\" for current buffer.
1382 If a server buffer is current, it is marked \"done\" and optionally saved.
1383 The buffer is also killed if it did not exist before the clients asked for it.
1384 When all of a client's buffers are marked as \"done\", the client is notified.
1386 Temporary files such as MH <draft> files are always saved and backed up,
1387 no questions asked. (The variable `make-backup-files', if nil, still
1388 inhibits a backup; you can set it locally in a particular buffer to
1389 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1390 which filenames are considered temporary.
1392 If invoked with a prefix argument, or if there is no server process running,
1393 starts server process and that is all. Invoked by \\[server-edit]."
1397 (not server-process
)
1398 (memq (process-status server-process
) '(signal exit
)))
1400 (server-clients (apply 'server-switch-buffer
(server-done)))
1401 (t (message "No server editing buffers exist"))))
1403 (defun server-switch-buffer (&optional next-buffer killed-one filepos
)
1404 "Switch to another buffer, preferably one that has a client.
1405 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1407 KILLED-ONE is t in a recursive call if we have already killed one
1408 temp-file server buffer. This means we should avoid the final
1409 \"switch to some other buffer\" since we've already effectively
1412 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1413 visit NEXT-BUFFER in an existing window. If non-nil, it should
1414 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1415 (if (null next-buffer
)
1417 (let ((rest server-clients
))
1418 (while (and rest
(not next-buffer
))
1419 (let ((proc (car rest
)))
1420 ;; Only look at frameless clients, or those in the selected
1422 (when (or (not (process-get proc
'frame
))
1423 (eq (process-get proc
'frame
) (selected-frame)))
1424 (setq next-buffer
(car (process-get proc
'buffers
))))
1425 (setq rest
(cdr rest
)))))
1426 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1427 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1428 ;; (switch-to-buffer (other-buffer))
1429 (message "No server buffers remain to edit")))
1430 (if (not (buffer-live-p next-buffer
))
1431 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1432 ;; and try the next surviving server buffer.
1433 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1434 ;; OK, we know next-buffer is live, let's display and select it.
1435 (if (functionp server-window
)
1436 (funcall server-window next-buffer
)
1437 (let ((win (get-buffer-window next-buffer
0)))
1438 (if (and win
(not server-window
))
1439 ;; The buffer is already displayed: just reuse the
1440 ;; window. If FILEPOS is non-nil, use it to replace the
1441 ;; window's own value of point.
1444 (set-buffer next-buffer
)
1446 (server-goto-line-column filepos
)))
1447 ;; Otherwise, let's find an appropriate window.
1448 (cond ((window-live-p server-window
)
1449 (select-window server-window
))
1450 ((framep server-window
)
1451 (unless (frame-live-p server-window
)
1452 (setq server-window
(make-frame)))
1453 (select-window (frame-selected-window server-window
))))
1454 (when (window-minibuffer-p (selected-window))
1455 (select-window (next-window nil
'nomini
0)))
1456 ;; Move to a non-dedicated window, if we have one.
1457 (when (window-dedicated-p (selected-window))
1459 (get-window-with-predicate
1461 (and (not (window-dedicated-p w
))
1462 (equal (frame-terminal (window-frame w
))
1463 (frame-terminal (selected-frame)))))
1464 'nomini
'visible
(selected-window))))
1466 (switch-to-buffer next-buffer
)
1467 ;; After all the above, we might still have ended up with
1468 ;; a minibuffer/dedicated-window (if there's no other).
1469 (error (pop-to-buffer next-buffer
)))))))
1470 (when server-raise-frame
1471 (select-frame-set-input-focus (window-frame (selected-window))))))
1474 (defun server-save-buffers-kill-terminal (arg)
1475 ;; Called from save-buffers-kill-terminal in files.el.
1476 "Offer to save each buffer, then kill the current client.
1477 With ARG non-nil, silently save all file-visiting buffers, then kill.
1479 If emacsclient was started with a list of filenames to edit, then
1480 only these files will be asked to be saved."
1481 (let ((proc (frame-parameter (selected-frame) 'client
)))
1482 (cond ((eq proc
'nowait
)
1483 ;; Nowait frames have no client buffer list.
1484 (if (cdr (frame-list))
1485 (progn (save-some-buffers arg
)
1487 ;; If we're the last frame standing, kill Emacs.
1488 (save-buffers-kill-emacs arg
)))
1490 (let ((buffers (process-get proc
'buffers
)))
1491 ;; If client is bufferless, emulate a normal Emacs exit
1492 ;; and offer to save all buffers. Otherwise, offer to
1493 ;; save only the buffers belonging to the client.
1496 (lambda () (memq (current-buffer) buffers
))
1498 (server-delete-client proc
)))
1499 (t (error "Invalid client frame")))))
1501 (define-key ctl-x-map
"#" 'server-edit
)
1503 (defun server-unload-function ()
1504 "Unload the server library."
1506 (substitute-key-definition 'server-edit nil ctl-x-map
)
1507 (save-current-buffer
1508 (dolist (buffer (buffer-list))
1510 (remove-hook 'kill-buffer-hook
'server-kill-buffer t
)))
1511 ;; continue standard unloading
1514 (defun server-eval-at (server form
)
1515 "Eval FORM on Emacs Server SERVER."
1516 (let ((auth-file (expand-file-name server server-auth-dir
))
1517 (coding-system-for-read 'binary
)
1518 (coding-system-for-write 'binary
)
1519 address port secret process
)
1520 (unless (file-exists-p auth-file
)
1521 (error "No such server definition: %s" auth-file
))
1523 (insert-file-contents auth-file
)
1524 (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
1525 (error "Invalid auth file"))
1526 (setq address
(match-string 1)
1527 port
(string-to-number (match-string 2)))
1529 (setq secret
(buffer-substring (point) (line-end-position)))
1531 (unless (setq process
(open-network-stream "eval-at" (current-buffer)
1533 (error "Unable to contact the server"))
1534 (set-process-query-on-exit-flag process nil
)
1535 (process-send-string
1537 (concat "-auth " secret
" -eval "
1538 (replace-regexp-in-string
1539 " " "&_" (format "%S" form
))
1541 (while (memq (process-status process
) '(open run
))
1542 (accept-process-output process
0 10))
1543 (goto-char (point-min))
1544 ;; If the result is nil, there's nothing in the buffer. If the
1545 ;; result is non-nil, it's after "-print ".
1546 (when (search-forward "\n-print" nil t
)
1547 (let ((start (point)))
1548 (while (search-forward "&_" nil t
)
1549 (replace-match " " t t
))
1551 (read (current-buffer)))))))
1556 ;;; server.el ends here