1 ;;; server.el --- Lisp code for GNU Emacs running as server process
3 ;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 ;; 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
10 ;; Changes by peck@sun.com and by rms.
11 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2, or (at your option)
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING. If not, write to the
27 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28 ;; Boston, MA 02110-1301, USA.
32 ;; This Lisp code is run in Emacs when it is to operate as
33 ;; a server for other processes.
35 ;; Load this library and do M-x server-edit to enable Emacs as a server.
36 ;; Emacs opens up a socket for communication with clients. If there are no
37 ;; client buffers to edit, server-edit acts like (switch-to-buffer
40 ;; When some other program runs "the editor" to edit a file,
41 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
42 ;; This program transmits the file names to Emacs through
43 ;; the server subprocess, and Emacs visits them and lets you edit them.
45 ;; Note that any number of clients may dispatch files to Emacs to be edited.
47 ;; When you finish editing a Server buffer, again call server-edit
48 ;; to mark that buffer as done for the client and switch to the next
49 ;; Server buffer. When all the buffers for a client have been edited
50 ;; and exited with server-edit, the client "editor" will return
51 ;; to the program that invoked it.
53 ;; Your editing commands and Emacs's display output go to and from
54 ;; the terminal in the usual way. Thus, server operation is possible
55 ;; only when Emacs can talk to the terminal at the time you invoke
56 ;; the client. This is possible in four cases:
58 ;; 1. On a window system, where Emacs runs in one window and the
59 ;; program that wants to use "the editor" runs in another.
61 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
62 ;; program that wants to use "the editor" runs on another.
64 ;; 3. When the program that wants to use "the editor" is running
65 ;; as a subprocess of Emacs.
67 ;; 4. On a system with job control, when Emacs is suspended, the program
68 ;; that wants to use "the editor" will stop and display
69 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
70 ;; brought into the foreground for editing. When done editing, Emacs is
71 ;; suspended again, and the client program is brought into the foreground.
73 ;; The buffer local variable "server-buffer-clients" lists
74 ;; the clients who are waiting for this buffer to be edited.
75 ;; The global variable "server-clients" lists all the waiting clients,
76 ;; and which files are yet to be edited for each.
80 (eval-when-compile (require 'cl))
83 "Emacs running as a server process."
86 (defcustom server-use-tcp nil
87 "If non-nil, use TCP sockets instead of local sockets."
88 :set #'(lambda (sym val)
89 (unless (featurep 'make-network-process '(:family local))
91 (unless load-in-progress
92 (message "Local sockets unsupported, using TCP sockets")))
94 (set-default sym val))
99 (defcustom server-host nil
100 "The name or IP address to use as host address of the server process.
101 If set, the server accepts remote connections; otherwise it is local."
104 (string :tag "Name or IP address")
105 (const :tag "Local" nil))
107 (put 'server-host 'risky-local-variable t)
109 (defcustom server-auth-dir "~/.emacs.d/server/"
110 "Directory for server authentication files."
114 (put 'server-auth-dir 'risky-local-variable t)
116 (defcustom server-raise-frame t
117 "If non-nil, raise frame when switching to a buffer."
122 (defcustom server-visit-hook nil
123 "Hook run when visiting a file for the Emacs server."
127 (defcustom server-switch-hook nil
128 "Hook run when switching to a buffer for the Emacs server."
132 (defcustom server-done-hook nil
133 "Hook run when done editing a buffer for the Emacs server."
137 (defvar server-process nil
138 "The current server process.")
140 (defvar server-clients nil
141 "List of current server clients.
142 Each element is (PROC PROPERTIES...) where PROC is a process object,
143 and PROPERTIES is an association list of client properties.")
145 (defvar server-buffer-clients nil
146 "List of client processes requesting editing of current buffer.")
147 (make-variable-buffer-local 'server-buffer-clients)
148 ;; Changing major modes should not erase this local.
149 (put 'server-buffer-clients 'permanent-local t)
151 (defcustom server-window nil
152 "Specification of the window to use for selecting Emacs server buffers.
153 If nil, use the selected window.
154 If it is a function, it should take one argument (a buffer) and
155 display and select it. A common value is `pop-to-buffer'.
156 If it is a window, use that.
157 If it is a frame, use the frame's selected window.
159 It is not meaningful to set this to a specific frame or window with Custom.
160 Only programs can do so."
163 :type '(choice (const :tag "Use selected window"
164 :match (lambda (widget value)
165 (not (functionp value)))
167 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
168 (function :tag "Other function")))
170 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
171 "Regexp matching names of temporary files.
172 These are deleted and reused after each edit by the programs that
173 invoke the Emacs server."
177 (defcustom server-kill-new-buffers t
178 "Whether to kill buffers when done with them.
179 If non-nil, kill a buffer unless it already existed before editing
180 it with Emacs server. If nil, kill only buffers as specified by
181 `server-temp-file-regexp'.
182 Please note that only buffers are killed that still have a client,
183 i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
189 (or (assq 'server-buffer-clients minor-mode-alist)
190 (push '(server-buffer-clients " Server") minor-mode-alist))
192 (defvar server-existing-buffer nil
193 "Non-nil means the buffer existed before the server was asked to visit it.
194 This means that the server should not kill the buffer when you say you
195 are done with it in the server.")
196 (make-variable-buffer-local 'server-existing-buffer)
198 (defvar server-name "server")
200 (defvar server-socket-dir nil
201 "The directory in which to place the server socket.
202 Initialized by `server-start'.")
204 (defun server-client (proc)
205 "Return the Emacs client corresponding to PROC.
206 PROC must be a process object.
207 The car of the result is PROC; the cdr is an association list.
208 See `server-client-get' and `server-client-set'."
209 (assq proc server-clients))
211 (defun server-client-get (client property)
212 "Get the value of PROPERTY in CLIENT.
213 CLIENT may be a process object, or a client returned by `server-client'.
214 Return nil if CLIENT has no such property."
215 (or (listp client) (setq client (server-client client)))
216 (cdr (assq property (cdr client))))
218 (defun server-client-set (client property value)
219 "Set the PROPERTY to VALUE in CLIENT, and return VALUE.
220 CLIENT may be a process object, or a client returned by `server-client'."
223 (setq proc (car client))
225 client (server-client client)))
226 (setq p (assq property client))
229 (client (setcdr client (cons (cons property value) (cdr client))))
230 (t (setq server-clients
231 `((,proc (,property . ,value)) . ,server-clients))))
234 (defun server-clients-with (property value)
235 "Return a list of clients with PROPERTY set to VALUE."
237 (dolist (client server-clients result)
238 (when (equal value (server-client-get client property))
239 (setq result (cons (car client) result))))))
241 (defun server-add-client (proc)
242 "Create a client for process PROC, if it doesn't already have one.
243 New clients have no properties."
244 (unless (server-client proc)
245 (setq server-clients (cons (cons proc nil)
248 (defun server-getenv-from (env variable)
249 "Get the value of VARIABLE in ENV.
250 VARIABLE should be a string. Value is nil if VARIABLE is
251 undefined in ENV. Otherwise, value is a string.
253 ENV should be in the same format as `process-environment'."
255 (while (and env (null result))
256 (setq entry (car env)
258 (if (and (> (length entry) (length variable))
259 (eq ?= (aref entry (length variable)))
260 (equal variable (substring entry 0 (length variable))))
261 (setq result (substring entry (+ (length variable) 1)))))
264 (defmacro server-with-environment (env vars &rest body)
265 "Evaluate BODY with environment variables VARS set to those in ENV.
266 The environment variables are then restored to their previous values.
268 VARS should be a list of strings.
269 ENV should be in the same format as `process-environment'."
271 (let ((old-env (make-symbol "old-env"))
272 (var (make-symbol "var"))
273 (value (make-symbol "value"))
274 (pair (make-symbol "pair")))
275 `(let ((,old-env process-environment))
277 (let ((,value (server-getenv-from ,env ,var)))
278 (setq process-environment
279 (cons (if (null ,value)
281 (concat ,var "=" ,value))
282 process-environment))))
285 (setq process-environment ,old-env)))))
287 (defun server-delete-client (client &optional noframe)
288 "Delete CLIENT, including its buffers, terminals and frames.
289 If NOFRAME is non-nil, let the frames live. (To be used from
290 `delete-frame-functions'.)"
291 (server-log (concat "server-delete-client" (if noframe " noframe"))
293 ;; Force a new lookup of client (prevents infinite recursion).
294 (setq client (server-client
295 (if (listp client) (car client) client)))
296 (let ((proc (car client))
297 (buffers (server-client-get client 'buffers)))
300 ;; Kill the client's buffers.
301 (dolist (buf buffers)
302 (when (buffer-live-p buf)
303 (with-current-buffer buf
304 ;; Kill the buffer if necessary.
305 (when (and (equal server-buffer-clients
307 (or (and server-kill-new-buffers
308 (not server-existing-buffer))
309 (server-temp-file-p))
310 (not (buffer-modified-p)))
313 (progn (setq server-buffer-clients nil)
314 (kill-buffer (current-buffer))
317 ;; Restore clients if user pressed C-g in `kill-buffer'.
318 (setq server-buffer-clients (list proc)))))))))
320 ;; Delete the client's frames.
322 (dolist (frame (frame-list))
323 (when (and (frame-live-p frame)
324 (equal proc (frame-parameter frame 'client)))
325 ;; Prevent `server-handle-delete-frame' from calling us
327 (set-frame-parameter frame 'client nil)
328 (delete-frame frame))))
330 (setq server-clients (delq client server-clients))
332 ;; Delete the client's tty.
333 (let ((terminal (server-client-get client 'terminal)))
334 (when (eq (terminal-live-p terminal) t)
335 (delete-terminal terminal)))
337 ;; Delete the client's process.
338 (if (eq (process-status (car client)) 'open)
339 (delete-process (car client)))
341 (server-log "Deleted" proc))))
343 (defun server-log (string &optional client)
344 "If a *server* buffer exists, write STRING to it for logging purposes.
345 If CLIENT is non-nil, add a description of it to the logged
347 (when (get-buffer "*server*")
348 (with-current-buffer "*server*"
349 (goto-char (point-max))
350 (insert (current-time-string)
353 ((listp client) (format " %s: " (car client)))
354 (t (format " %s: " client)))
356 (or (bolp) (newline)))))
358 (defun server-sentinel (proc msg)
359 "The process sentinel for Emacs server connections."
360 ;; If this is a new client process, set the query-on-exit flag to nil
361 ;; for this process (it isn't inherited from the server process).
362 (when (and (eq (process-status proc) 'open)
363 (process-query-on-exit-flag proc))
364 (set-process-query-on-exit-flag proc nil))
365 ;; Delete the associated connection file, if applicable.
366 ;; This is actually problematic: the file may have been overwritten by
367 ;; another Emacs server in the mean time, so it's not ours any more.
368 ;; (and (process-contact proc :server)
369 ;; (eq (process-status proc) 'closed)
370 ;; (ignore-errors (delete-file (process-get proc :server-file))))
371 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
372 (server-delete-client proc))
374 (defun server-handle-delete-frame (frame)
375 "Delete the client connection when the emacsclient frame is deleted."
376 (let ((proc (frame-parameter frame 'client)))
377 (when (and (frame-live-p frame)
379 ;; See if this is the last frame for this client.
380 (>= 1 (let ((frame-num 0))
381 (dolist (f (frame-list))
382 (when (eq proc (frame-parameter f 'client))
383 (setq frame-num (1+ frame-num))))
385 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
386 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
388 (defun server-handle-suspend-tty (terminal)
389 "Notify the emacsclient process to suspend itself when its tty device is suspended."
390 (dolist (proc (server-clients-with 'terminal terminal))
391 (server-log (format "server-handle-suspend-tty, terminal %s" terminal) proc)
393 (server-send-string proc "-suspend \n")
394 (file-error (condition-case nil (server-delete-client proc) (error nil))))))
396 (defun server-unquote-arg (arg)
397 "Remove &-quotation from ARG.
398 See `server-quote-arg' and `server-process-filter'."
399 (replace-regexp-in-string
408 (defun server-quote-arg (arg)
409 "In ARG, insert a & before each &, each space, each newline, and -.
410 Change spaces to underscores, too, so that the return value never
413 See `server-unquote-arg' and `server-process-filter'."
414 (replace-regexp-in-string
415 "[-&\n ]" (lambda (s)
423 (defun server-send-string (proc string)
424 "A wrapper around `proc-send-string' for logging."
425 (server-log (concat "Sent " string) proc)
426 (process-send-string proc string))
428 (defun server-ensure-safe-dir (dir)
429 "Make sure DIR is a directory with no race-condition issues.
430 Creates the directory if necessary and makes sure:
431 - there's no symlink involved
433 - it's not readable/writable by anybody else."
434 (setq dir (directory-file-name dir))
435 (let ((attrs (file-attributes dir)))
437 (letf (((default-file-modes) ?\700)) (make-directory dir t))
438 (setq attrs (file-attributes dir)))
439 ;; Check that it's safe for use.
440 (unless (and (eq t (car attrs)) (eql (nth 2 attrs) (user-uid))
441 (or (eq system-type 'windows-nt)
442 (zerop (logand ?\077 (file-modes dir)))))
443 (error "The directory %s is unsafe" dir))))
446 (defun server-start (&optional leave-dead)
447 "Allow this Emacs process to be a server for client processes.
448 This starts a server communications subprocess through which
449 client \"editors\" can send your editing commands to this Emacs
450 job. To use the server, set up the program `emacsclient' in the
451 Emacs distribution as your standard \"editor\".
453 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
454 kill any existing server communications subprocess."
459 "The current server still has clients; delete them? "))
460 ;; It is safe to get the user id now.
461 (setq server-socket-dir (or server-socket-dir
462 (format "/tmp/emacs%d" (user-uid))))
465 (ignore-errors (delete-process server-process)))
466 ;; Delete the socket files made by previous server invocations.
468 (delete-file (expand-file-name server-name server-socket-dir))
470 ;; If this Emacs already had a server, clear out associated status.
471 (while server-clients
472 (server-delete-client (car server-clients)))
473 ;; Now any previous server is properly stopped.
476 (server-log (message "Server stopped"))
477 (setq server-process nil))
478 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
479 (server-file (expand-file-name server-name server-dir)))
480 ;; Make sure there is a safe directory in which to place the socket.
481 (server-ensure-safe-dir server-dir)
482 ;; Remove any leftover socket or authentication file.
483 (ignore-errors (delete-file server-file))
485 (server-log (message "Restarting server")))
486 (letf (((default-file-modes) ?\700))
487 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
488 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
489 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
490 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
492 (apply #'make-network-process
496 :sentinel 'server-sentinel
497 :filter 'server-process-filter
498 ;; We must receive file names without being decoded.
499 ;; Those are decoded by server-process-filter according
500 ;; to file-name-coding-system.
502 ;; The rest of the args depends on the kind of socket used.
506 :host (or server-host 'local)
507 :plist '(:authenticated nil))
510 :plist '(:authenticated t)))))
511 (unless server-process (error "Could not start server process"))
515 ;; The auth key is a 64-byte string of random chars in the
518 collect (+ 33 (random 94)) into auth
519 finally return (concat auth))))
520 (process-put server-process :auth-key auth-key)
521 (with-temp-file server-file
522 (set-buffer-multibyte nil)
523 (setq buffer-file-coding-system 'no-conversion)
524 (insert (format-network-address
525 (process-contact server-process :local))
526 " " (int-to-string (emacs-pid))
527 "\n" auth-key)))))))))
530 (define-minor-mode server-mode
532 With ARG, turn Server mode on if ARG is positive, off otherwise.
533 Server mode runs a process that accepts commands from the
534 `emacsclient' program. See `server-start' and Info node `Emacs server'."
538 ;; Fixme: Should this check for an existing server socket and do
539 ;; nothing if there is one (for multiple Emacs sessions)?
540 (server-start (not server-mode)))
542 (defun* server-process-filter (proc string)
543 "Process a request from the server to edit some files.
544 PROC is the server process. STRING consists of a sequence of
545 commands prefixed by a dash. Some commands have arguments; these
546 are &-quoted and need to be decoded by `server-unquote-arg'. The
547 filter parses and executes these commands.
549 To illustrate the protocol, here is an example command that
550 emacsclient sends to create a new X frame (note that the whole
551 sequence is sent on a single line):
553 -version 21.3.50 xterm
554 -env HOME /home/lorentey
556 ... lots of other -env commands
560 The server normally sends back the single command `-good-version'
563 The following commands are accepted by the server:
566 Authenticate the client using the secret authentication string
569 `-version CLIENT-VERSION'
570 Check version numbers between server and client, and signal an
571 error if there is a mismatch. The server replies with
572 `-good-version' to confirm the match.
575 An environment variable on the client side.
578 The current working directory of the client process.
581 Forbid the creation of new frames.
584 Request that the next frame created should not be
585 associated with this client.
588 Set the display name to open X frames on.
590 `-position LINE[:COLUMN]'
591 Go to the given line and column number
592 in the next file opened.
595 Load the given file in the current frame.
598 Evaluate EXPR as a Lisp expression and return the
599 result in -print commands.
604 `-tty DEVICENAME TYPE'
605 Open a new tty frame at the client.
608 Suspend this tty frame. The client sends this string in
609 response to SIGTSTP and SIGTTOU. The server must cease all I/O
610 on this tty until it gets a -resume command.
613 Resume this tty frame. The client sends this string when it
614 gets the SIGCONT signal and it is the foreground process on its
618 Do nothing, but put the comment in the server
619 log. Useful for debugging.
622 The following commands are accepted by the client:
625 Signals a version match between the client and the server.
628 Describes the process id of the Emacs process;
629 used to forward window change signals to it.
631 `-window-system-unsupported'
632 Signals that the server does not
633 support creating X frames; the client must try again with a tty
637 Print STRING on stdout. Used to send values
641 Signal an error (but continue processing).
644 Suspend this terminal, i.e., stop the client process. Sent
645 when the user presses C-z."
646 (server-log (concat "Received " string) proc)
647 ;; First things first: let's check the authentication
648 (unless (process-get proc :authenticated)
649 (if (and (string-match "-auth \\(.*?\\)\n" string)
650 (equal (match-string 1 string) (process-get proc :auth-key)))
652 (setq string (substring string (match-end 0)))
653 (process-put proc :authenticated t)
654 (server-log "Authentication successful" proc))
655 (server-log "Authentication failed" proc)
657 proc (concat "-error " (server-quote-arg "Authentication failed")))
658 (delete-process proc)
659 ;; We return immediately
660 (return-from server-process-filter)))
661 (when (> (recursion-depth) 0)
662 ;; We're inside a minibuffer already, so if the emacs-client is trying
663 ;; to open a frame on a new display, we might end up with an unusable
664 ;; frame because input from that display will be blocked (until exiting
665 ;; the minibuffer). Better exit this minibuffer right away.
666 ;; Similarly with recursive-edits such as the splash screen.
667 (process-put proc :previous-string string)
668 (run-with-timer 0 nil (lexical-let ((proc proc))
669 (lambda () (server-process-filter proc ""))))
672 ;; If we're running isearch, we must abort it to allow Emacs to
673 ;; display the buffer and switch to it.
674 (mapc #'(lambda (buffer)
675 (with-current-buffer buffer
676 (when (bound-and-true-p isearch-mode)
679 ;; Signaled by isearch-cancel
680 (quit (message nil)))
681 (let ((prev (process-get proc 'previous-string)))
683 (setq string (concat prev string))
684 (process-put proc 'previous-string nil)))
687 (server-add-client proc)
688 ;; If the input is multiple lines,
689 ;; process each line individually.
690 (while (string-match "\n" string)
691 (let ((request (substring string 0 (match-beginning 0)))
692 (coding-system (and default-enable-multibyte-characters
693 (or file-name-coding-system
694 default-file-name-coding-system)))
695 (client (server-client proc))
697 nowait ; t if emacsclient does not want to wait for us.
698 frame ; The frame that was opened for the client (if any).
699 display ; Open the frame on this display.
700 dontkill ; t if the client should not be killed.
706 ;; Remove this line from STRING.
707 (setq string (substring string (match-end 0)))
708 (while (string-match " *[^ ]* " request)
709 (let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
710 (setq request (substring request (match-end 0)))
712 ;; -version CLIENT-VERSION:
713 ;; Check version numbers, signal an error if there is a mismatch.
714 ((and (equal "-version" arg)
715 (string-match "\\([0-9.]+\\) " request))
716 (let* ((client-version (match-string 1 request))
717 (truncated-emacs-version
718 (substring emacs-version 0 (length client-version))))
719 (setq request (substring request (match-end 0)))
720 (if (equal client-version truncated-emacs-version)
722 (server-send-string proc "-good-version \n")
723 (server-client-set client 'version client-version))
724 (error (concat "Version mismatch: Emacs is "
725 truncated-emacs-version
726 ", emacsclient is " client-version)))))
728 ;; -nowait: Emacsclient won't wait for a result.
729 ((equal "-nowait" arg) (setq nowait t))
731 ;; -current-frame: Don't create frames.
732 ((equal "-current-frame" arg) (setq current-frame t))
735 ;; Open X frames on the given display instead of the default.
736 ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
737 (setq display (match-string 1 request)
738 request (substring request (match-end 0))))
740 ;; -window-system: Open a new X frame.
741 ((equal "-window-system" arg)
742 (unless (server-client-get client 'version)
743 (error "Protocol error; make sure to use the correct version of emacsclient"))
744 (unless current-frame
745 (if (fboundp 'x-create-frame)
746 (let ((params (if nowait
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 (list (cons 'client 'nowait) (cons 'environment env))
753 (list (cons 'client proc) (cons 'environment env)))))
754 (setq frame (make-frame-on-display
756 (frame-parameter nil 'display)
758 (error "Please specify display"))
760 (server-log (format "%s created" frame) proc)
761 ;; XXX We need to ensure the parameters are
762 ;; really set because Emacs forgets unhandled
763 ;; initialization parameters for X frames at
765 (modify-frame-parameters frame params)
767 (server-client-set client 'frame frame)
768 (server-client-set client 'terminal (frame-terminal frame))
770 ;; Display *scratch* by default.
771 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
774 ;; This emacs does not support X.
775 (server-log "Window system unsupported" proc)
776 (server-send-string proc "-window-system-unsupported \n")
779 ;; -resume: Resume a suspended tty frame.
780 ((equal "-resume" arg)
781 (let ((terminal (server-client-get client 'terminal)))
783 (when (eq (terminal-live-p terminal) t)
784 (resume-tty terminal))))
786 ;; -suspend: Suspend the client's frame. (In case we
787 ;; get out of sync, and a C-z sends a SIGTSTP to
789 ((equal "-suspend" arg)
790 (let ((terminal (server-client-get client 'terminal)))
792 (when (eq (terminal-live-p terminal) t)
793 (suspend-tty terminal))))
795 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
796 ;; (The given comment appears in the server log.)
797 ((and (equal "-ignore" arg) (string-match "\\([^ ]*\\) " request))
799 request (substring request (match-end 0))))
801 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
802 ((and (equal "-tty" arg) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request))
803 (let ((tty (server-unquote-arg (match-string 1 request)))
804 (type (server-unquote-arg (match-string 2 request))))
805 (setq request (substring request (match-end 0)))
806 (unless (server-client-get client 'version)
807 (error "Protocol error; make sure you use the correct version of emacsclient"))
808 (unless current-frame
809 (server-with-environment env
810 '("LANG" "LC_CTYPE" "LC_ALL"
811 ;; For tgetent(3); list according to ncurses(3).
812 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
813 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
814 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
815 "TERMINFO_DIRS" "TERMPATH")
816 (setq frame (make-frame-on-tty tty type
817 ;; Ignore nowait here; we always need to clean
818 ;; up opened ttys when the client dies.
820 (environment . ,env)))))
822 (server-client-set client 'frame frame)
823 (server-client-set client 'tty (terminal-name frame))
824 (server-client-set client 'terminal (frame-terminal frame))
826 ;; Display *scratch* by default.
827 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
829 ;; Reply with our pid.
830 (server-send-string proc (concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
833 ;; -position LINE: Go to the given line in the next file.
834 ((and (equal "-position" arg) (string-match "\\(\\+[0-9]+\\) " request))
835 (setq lineno (string-to-number (substring (match-string 1 request) 1))
836 request (substring request (match-end 0))))
838 ;; -position LINE:COLUMN: Set point to the given position in the next file.
839 ((and (equal "-position" arg) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request))
840 (setq lineno (string-to-number (match-string 1 request))
841 columnno (string-to-number (match-string 2 request))
842 request (substring request (match-end 0))))
844 ;; -file FILENAME: Load the given file.
845 ((and (equal "-file" arg) (string-match "\\([^ ]+\\) " request))
846 (let ((file (server-unquote-arg (match-string 1 request))))
847 (setq request (substring request (match-end 0)))
849 (setq file (decode-coding-string file coding-system)))
850 (setq file (command-line-normalize-file-name file))
851 (push (list file lineno columnno) files)
852 (server-log (format "New file: %s (%d:%d)" file lineno columnno) proc))
856 ;; -eval EXPR: Evaluate a Lisp expression.
857 ((and (equal "-eval" arg) (string-match "\\([^ ]+\\) " request))
858 (let ((expr (server-unquote-arg (match-string 1 request))))
859 (setq request (substring request (match-end 0)))
861 (setq expr (decode-coding-string expr coding-system)))
862 (let ((v (eval (car (read-from-string expr)))))
863 (when (and (not frame) v)
865 (let ((standard-output (current-buffer)))
868 proc (format "-print %s\n"
870 (buffer-substring-no-properties (point-min)
875 ;; -env NAME=VALUE: An environment variable.
876 ((and (equal "-env" arg) (string-match "\\([^ ]+\\) " request))
877 (let ((var (server-unquote-arg (match-string 1 request))))
878 ;; XXX Variables should be encoded as in getenv/setenv.
879 (setq request (substring request (match-end 0)))
880 (setq env (cons var env))))
882 ;; -dir DIRNAME: The cwd of the emacsclient process.
883 ((and (equal "-dir" arg) (string-match "\\([^ ]+\\) " request))
884 (setq dir (server-unquote-arg (match-string 1 request)))
885 (setq request (substring request (match-end 0)))
887 (setq dir (decode-coding-string dir coding-system)))
888 (setq dir (command-line-normalize-file-name dir)))
891 (t (error "Unknown command: %s" arg)))))
895 (run-hooks 'pre-command-hook)
896 (setq buffers (server-visit-files files client nowait))
897 (run-hooks 'post-command-hook))
900 (with-selected-frame frame
901 (display-startup-echo-area-message)
902 (unless inhibit-splash-screen
904 ;; This looks scary because `fancy-splash-screens'
905 ;; will call `recursive-edit' from a process filter.
906 ;; However, that should be safe to do now.
907 (display-splash-screen t)
908 ;; `recursive-edit' will throw an error if Emacs is
909 ;; already doing a recursive edit elsewhere. Catch it
910 ;; here so that we can finish normally.
913 ;; Delete the client if necessary.
916 ;; Client requested nowait; return immediately.
917 (server-log "Close nowait client" proc)
918 (server-delete-client proc))
919 ((and (not dontkill) (null buffers))
920 ;; This client is empty; get rid of it immediately.
921 (server-log "Close empty client" proc)
922 (server-delete-client proc)))
924 ((or isearch-mode (minibufferp))
926 ((and frame (null buffers))
927 (message "%s" (substitute-command-keys
928 "When done with this frame, type \\[delete-frame]")))
929 ((not (null buffers))
930 (server-switch-buffer (car buffers))
931 (run-hooks 'server-switch-hook)
933 (message "%s" (substitute-command-keys
934 "When done with a buffer, type \\[server-edit]"))))))))
936 ;; Save for later any partial line that remains.
937 (when (> (length string) 0)
938 (process-put proc 'previous-string string)))
940 (error (ignore-errors
942 proc (concat "-error " (server-quote-arg (error-message-string err))))
944 (server-log (error-message-string err) proc)
945 (delete-process proc)))))
947 (defun server-goto-line-column (file-line-col)
948 "Move point to the position indicated in FILE-LINE-COL.
949 FILE-LINE-COL should be a three-element list as described in
950 `server-visit-files'."
951 (goto-line (nth 1 file-line-col))
952 (let ((column-number (nth 2 file-line-col)))
953 (if (> column-number 0)
954 (move-to-column (1- column-number)))))
956 (defun server-visit-files (files client &optional nowait)
957 "Find FILES and return a list of buffers created.
958 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
959 CLIENT is the client that requested this operation.
960 NOWAIT non-nil means this client is not waiting for the results,
961 so don't mark these buffers specially, just visit them normally."
962 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
963 (let ((last-nonmenu-event t) client-record)
964 ;; Restore the current buffer afterward, but not using save-excursion,
965 ;; because we don't want to save point in this buffer
966 ;; if it happens to be one of those specified by the server.
969 ;; If there is an existing buffer modified or the file is
970 ;; modified, revert it. If there is an existing buffer with
971 ;; deleted file, offer to write it.
972 (let* ((minibuffer-auto-raise (or server-raise-frame
973 minibuffer-auto-raise))
975 (obuf (get-file-buffer filen)))
976 (add-to-history 'file-name-history filen)
977 (if (and obuf (set-buffer obuf))
979 (cond ((file-exists-p filen)
980 (when (not (verify-visited-file-modtime obuf))
981 (revert-buffer t nil)))
984 (concat "File no longer exists: " filen
985 ", write buffer to file? "))
986 (write-file filen))))
987 (unless server-buffer-clients
988 (setq server-existing-buffer t))
989 (server-goto-line-column file))
990 (set-buffer (find-file-noselect filen))
991 (server-goto-line-column file)
992 (run-hooks 'server-visit-hook)))
994 ;; When the buffer is killed, inform the clients.
995 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
996 (push (car client) server-buffer-clients))
997 (push (current-buffer) client-record)))
1001 (nconc (server-client-get client 'buffers) client-record)))
1004 (defun server-buffer-done (buffer &optional for-killing)
1005 "Mark BUFFER as \"done\" for its client(s).
1006 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1007 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1008 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1010 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1011 (let ((next-buffer nil)
1013 (dolist (client server-clients)
1014 (let ((buffers (server-client-get client 'buffers)))
1016 (setq next-buffer (nth 1 (memq buffer buffers))))
1017 (when buffers ; Ignore bufferless clients.
1018 (setq buffers (delq buffer buffers))
1019 ;; Delete all dead buffers from CLIENT.
1022 (not (buffer-live-p b))
1023 (setq buffers (delq b buffers))))
1024 (server-client-set client 'buffers buffers)
1025 ;; If client now has no pending buffers,
1026 ;; tell it that it is done, and forget it entirely.
1028 (server-log "Close" client)
1029 (server-delete-client client)))))
1030 (when (and (bufferp buffer) (buffer-name buffer))
1031 ;; We may or may not kill this buffer;
1032 ;; if we do, do not call server-buffer-done recursively
1033 ;; from kill-buffer-hook.
1034 (let ((server-kill-buffer-running t))
1035 (with-current-buffer buffer
1036 (setq server-buffer-clients nil)
1037 (run-hooks 'server-done-hook))
1038 ;; Notice whether server-done-hook killed the buffer.
1039 (if (null (buffer-name buffer))
1041 ;; Don't bother killing or burying the buffer
1042 ;; when we are called from kill-buffer.
1044 (when (and (not killed)
1045 server-kill-new-buffers
1046 (with-current-buffer buffer
1047 (not server-existing-buffer)))
1049 (bury-buffer buffer)
1050 (kill-buffer buffer))
1052 (if (server-temp-file-p buffer)
1054 (kill-buffer buffer)
1056 (bury-buffer buffer)))))))
1057 (list next-buffer killed)))
1059 (defun server-temp-file-p (&optional buffer)
1060 "Return non-nil if BUFFER contains a file considered temporary.
1061 These are files whose names suggest they are repeatedly
1062 reused to pass information to another program.
1064 The variable `server-temp-file-regexp' controls which filenames
1065 are considered temporary."
1066 (and (buffer-file-name buffer)
1067 (string-match server-temp-file-regexp (buffer-file-name buffer))))
1069 (defun server-done ()
1070 "Offer to save current buffer, mark it as \"done\" for clients.
1071 This kills or buries the buffer, then returns a list
1072 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1073 as a suggestion for what to select next, or nil.
1074 KILLED is t if we killed BUFFER, which happens if it was created
1075 specifically for the clients and did not exist before their request for it."
1076 (when server-buffer-clients
1077 (if (server-temp-file-p)
1078 ;; For a temp file, save, and do make a non-numeric backup
1079 ;; (unless make-backup-files is nil).
1080 (let ((version-control nil)
1081 (buffer-backed-up nil))
1083 (when (and (buffer-modified-p)
1085 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1087 (server-buffer-done (current-buffer))))
1089 ;; Ask before killing a server buffer.
1090 ;; It was suggested to release its client instead,
1091 ;; but I think that is dangerous--the client would proceed
1092 ;; using whatever is on disk in that file. -- rms.
1093 (defun server-kill-buffer-query-function ()
1094 "Ask before killing a server buffer."
1095 (or (not server-buffer-clients)
1097 (dolist (proc server-buffer-clients res)
1098 (let ((client (server-client proc)))
1099 (when (and client (eq (process-status proc) 'open))
1101 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1102 (buffer-name (current-buffer))))))
1104 (defun server-kill-emacs-query-function ()
1105 "Ask before exiting Emacs it has live clients."
1106 (or (not server-clients)
1108 (dolist (client server-clients live-client)
1109 (when (memq t (mapcar 'buffer-live-p (server-client-get
1111 (setq live-client t))))
1112 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1114 (defvar server-kill-buffer-running nil
1115 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1117 (defun server-kill-buffer ()
1118 "Remove the current buffer from its clients' buffer list.
1119 Designed to be added to `kill-buffer-hook'."
1120 ;; Prevent infinite recursion if user has made server-done-hook
1121 ;; call kill-buffer.
1122 (or server-kill-buffer-running
1123 (and server-buffer-clients
1124 (let ((server-kill-buffer-running t))
1125 (when server-process
1126 (server-buffer-done (current-buffer) t))))))
1128 (defun server-edit (&optional arg)
1129 "Switch to next server editing buffer; say \"Done\" for current buffer.
1130 If a server buffer is current, it is marked \"done\" and optionally saved.
1131 The buffer is also killed if it did not exist before the clients asked for it.
1132 When all of a client's buffers are marked as \"done\", the client is notified.
1134 Temporary files such as MH <draft> files are always saved and backed up,
1135 no questions asked. (The variable `make-backup-files', if nil, still
1136 inhibits a backup; you can set it locally in a particular buffer to
1137 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1138 which filenames are considered temporary.
1140 If invoked with a prefix argument, or if there is no server process running,
1141 starts server process and that is all. Invoked by \\[server-edit]."
1145 (not server-process)
1146 (memq (process-status server-process) '(signal exit)))
1148 (server-clients (apply 'server-switch-buffer (server-done)))
1149 (t (message "No server editing buffers exist"))))
1151 (defun server-switch-buffer (&optional next-buffer killed-one)
1152 "Switch to another buffer, preferably one that has a client.
1153 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1155 KILLED-ONE is t in a recursive call if we have already killed one
1156 temp-file server buffer. This means we should avoid the final
1157 \"switch to some other buffer\" since we've already effectively
1159 (if (null next-buffer)
1161 (let ((rest server-clients))
1162 (while (and rest (not next-buffer))
1163 (let ((client (car rest)))
1164 ;; Only look at frameless clients.
1165 (when (not (server-client-get client 'frame))
1166 (setq next-buffer (car (server-client-get client 'buffers))))
1167 (setq rest (cdr rest)))))
1168 (and next-buffer (server-switch-buffer next-buffer killed-one))
1169 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1170 ;; (switch-to-buffer (other-buffer))
1171 (message "No server buffers remain to edit")))
1172 (if (not (buffer-live-p next-buffer))
1173 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1174 ;; and try the next surviving server buffer.
1175 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1176 ;; OK, we know next-buffer is live, let's display and select it.
1177 (if (functionp server-window)
1178 (funcall server-window next-buffer)
1179 (let ((win (get-buffer-window next-buffer 0)))
1180 (if (and win (not server-window))
1181 ;; The buffer is already displayed: just reuse the window.
1184 (set-buffer next-buffer))
1185 ;; Otherwise, let's find an appropriate window.
1186 (cond ((and (windowp server-window)
1187 (window-live-p server-window))
1188 (select-window server-window))
1189 ((framep server-window)
1190 (unless (frame-live-p server-window)
1191 (setq server-window (make-frame)))
1192 (select-window (frame-selected-window server-window))))
1193 (when (window-minibuffer-p (selected-window))
1194 (select-window (next-window nil 'nomini 0)))
1195 ;; Move to a non-dedicated window, if we have one.
1196 (when (window-dedicated-p (selected-window))
1198 (get-window-with-predicate
1200 (and (not (window-dedicated-p w))
1201 (equal (frame-terminal (window-frame w))
1202 (frame-terminal (selected-frame)))))
1203 'nomini 'visible (selected-window))))
1205 (switch-to-buffer next-buffer)
1206 ;; After all the above, we might still have ended up with
1207 ;; a minibuffer/dedicated-window (if there's no other).
1208 (error (pop-to-buffer next-buffer)))))))
1209 (when server-raise-frame
1210 (select-frame-set-input-focus (window-frame (selected-window))))))
1213 (defun server-save-buffers-kill-terminal (proc &optional arg)
1214 "Offer to save each buffer, then kill PROC.
1216 With prefix arg, silently save all file-visiting buffers, then kill.
1218 If emacsclient was started with a list of filenames to edit, then
1219 only these files will be asked to be saved."
1220 (let ((buffers (server-client-get proc 'buffers)))
1221 ;; If client is bufferless, emulate a normal Emacs session
1222 ;; exit and offer to save all buffers. Otherwise, offer to
1223 ;; save only the buffers belonging to the client.
1224 (save-some-buffers arg
1226 (lambda () (memq (current-buffer) buffers))
1228 (server-delete-client proc)))
1230 (define-key ctl-x-map "#" 'server-edit)
1232 (defun server-unload-hook ()
1233 "Unload the server library."
1235 (remove-hook 'suspend-tty-functions 'server-handle-suspend-tty)
1236 (remove-hook 'delete-frame-functions 'server-handle-delete-frame)
1237 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
1238 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
1239 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
1241 (add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
1242 (add-hook 'server-unload-hook 'server-unload-hook)
1246 ;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1247 ;;; server.el ends here