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 ((oldvalues (make-symbol "oldvalues"))
272 (var (make-symbol "var"))
273 (value (make-symbol "value"))
274 (pair (make-symbol "pair")))
277 (let ((,value (server-getenv-from ,env ,var)))
278 (setq ,oldvalues (cons (cons ,var (getenv ,var)) ,oldvalues))
279 (setenv ,var ,value)))
282 (dolist (,pair ,oldvalues)
283 (setenv (car ,pair) (cdr ,pair)))))))
285 (defun server-delete-client (client &optional noframe)
286 "Delete CLIENT, including its buffers, terminals and frames.
287 If NOFRAME is non-nil, let the frames live. (To be used from
288 `delete-frame-functions'.)"
289 (server-log (concat "server-delete-client" (if noframe " noframe"))
291 ;; Force a new lookup of client (prevents infinite recursion).
292 (setq client (server-client
293 (if (listp client) (car client) client)))
294 (let ((proc (car client))
295 (buffers (server-client-get client 'buffers)))
298 ;; Kill the client's buffers.
299 (dolist (buf buffers)
300 (when (buffer-live-p buf)
301 (with-current-buffer buf
302 ;; Kill the buffer if necessary.
303 (when (and (equal server-buffer-clients
305 (or (and server-kill-new-buffers
306 (not server-existing-buffer))
307 (server-temp-file-p))
308 (not (buffer-modified-p)))
311 (progn (setq server-buffer-clients nil)
312 (kill-buffer (current-buffer))
315 ;; Restore clients if user pressed C-g in `kill-buffer'.
316 (setq server-buffer-clients (list proc)))))))))
318 ;; Delete the client's frames.
320 (dolist (frame (frame-list))
321 (when (and (frame-live-p frame)
322 (equal proc (frame-parameter frame 'client)))
323 ;; Prevent `server-handle-delete-frame' from calling us
325 (set-frame-parameter frame 'client nil)
326 (delete-frame frame))))
328 (setq server-clients (delq client server-clients))
330 ;; Delete the client's tty.
331 (let ((terminal (server-client-get client 'terminal)))
332 (when (eq (terminal-live-p terminal) t)
333 (delete-terminal terminal)))
335 ;; Delete the client's process.
336 (if (eq (process-status (car client)) 'open)
337 (delete-process (car client)))
339 (server-log "Deleted" proc))))
341 (defun server-log (string &optional client)
342 "If a *server* buffer exists, write STRING to it for logging purposes.
343 If CLIENT is non-nil, add a description of it to the logged
345 (when (get-buffer "*server*")
346 (with-current-buffer "*server*"
347 (goto-char (point-max))
348 (insert (current-time-string)
351 ((listp client) (format " %s: " (car client)))
352 (t (format " %s: " client)))
354 (or (bolp) (newline)))))
356 (defun server-sentinel (proc msg)
357 "The process sentinel for Emacs server connections."
358 ;; If this is a new client process, set the query-on-exit flag to nil
359 ;; for this process (it isn't inherited from the server process).
360 (when (and (eq (process-status proc) 'open)
361 (process-query-on-exit-flag proc))
362 (set-process-query-on-exit-flag proc nil))
363 ;; Delete the associated connection file, if applicable.
364 ;; This is actually problematic: the file may have been overwritten by
365 ;; another Emacs server in the mean time, so it's not ours any more.
366 ;; (and (process-contact proc :server)
367 ;; (eq (process-status proc) 'closed)
368 ;; (ignore-errors (delete-file (process-get proc :server-file))))
369 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
370 (server-delete-client proc))
372 (defun server-handle-delete-frame (frame)
373 "Delete the client connection when the emacsclient frame is deleted."
374 (let ((proc (frame-parameter frame 'client)))
375 (when (and (frame-live-p frame)
377 ;; See if this is the last frame for this client.
378 (>= 1 (let ((frame-num 0))
379 (dolist (f (frame-list))
380 (when (eq proc (frame-parameter f 'client))
381 (setq frame-num (1+ frame-num))))
383 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
384 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
386 (defun server-handle-suspend-tty (terminal)
387 "Notify the emacsclient process to suspend itself when its tty device is suspended."
388 (dolist (proc (server-clients-with 'terminal terminal))
389 (server-log (format "server-handle-suspend-tty, terminal %s" terminal) proc)
391 (server-send-string proc "-suspend \n")
392 (file-error (condition-case nil (server-delete-client proc) (error nil))))))
394 (defun server-unquote-arg (arg)
395 "Remove &-quotation from ARG.
396 See `server-quote-arg' and `server-process-filter'."
397 (replace-regexp-in-string
406 (defun server-quote-arg (arg)
407 "In ARG, insert a & before each &, each space, each newline, and -.
408 Change spaces to underscores, too, so that the return value never
411 See `server-unquote-arg' and `server-process-filter'."
412 (replace-regexp-in-string
413 "[-&\n ]" (lambda (s)
421 (defun server-send-string (proc string)
422 "A wrapper around `proc-send-string' for logging."
423 (server-log (concat "Sent " string) proc)
424 (process-send-string proc string))
426 (defun server-ensure-safe-dir (dir)
427 "Make sure DIR is a directory with no race-condition issues.
428 Creates the directory if necessary and makes sure:
429 - there's no symlink involved
431 - it's not readable/writable by anybody else."
432 (setq dir (directory-file-name dir))
433 (let ((attrs (file-attributes dir)))
435 (letf (((default-file-modes) ?\700)) (make-directory dir t))
436 (setq attrs (file-attributes dir)))
437 ;; Check that it's safe for use.
438 (unless (and (eq t (car attrs)) (eql (nth 2 attrs) (user-uid))
439 (or (eq system-type 'windows-nt)
440 (zerop (logand ?\077 (file-modes dir)))))
441 (error "The directory %s is unsafe" dir))))
444 (defun server-start (&optional leave-dead)
445 "Allow this Emacs process to be a server for client processes.
446 This starts a server communications subprocess through which
447 client \"editors\" can send your editing commands to this Emacs
448 job. To use the server, set up the program `emacsclient' in the
449 Emacs distribution as your standard \"editor\".
451 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
452 kill any existing server communications subprocess."
457 "The current server still has clients; delete them? "))
458 ;; It is safe to get the user id now.
459 (setq server-socket-dir (or server-socket-dir
460 (format "/tmp/emacs%d" (user-uid))))
463 (ignore-errors (delete-process server-process)))
464 ;; Delete the socket files made by previous server invocations.
466 (delete-file (expand-file-name server-name server-socket-dir))
468 ;; If this Emacs already had a server, clear out associated status.
469 (while server-clients
470 (server-delete-client (car server-clients)))
471 ;; Now any previous server is properly stopped.
474 (server-log (message "Server stopped"))
475 (setq server-process nil))
476 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
477 (server-file (expand-file-name server-name server-dir)))
478 ;; Make sure there is a safe directory in which to place the socket.
479 (server-ensure-safe-dir server-dir)
480 ;; Remove any leftover socket or authentication file.
481 (ignore-errors (delete-file server-file))
483 (server-log (message "Restarting server")))
484 (letf (((default-file-modes) ?\700))
485 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
486 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
487 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
488 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
490 (apply #'make-network-process
494 :sentinel 'server-sentinel
495 :filter 'server-process-filter
496 ;; We must receive file names without being decoded.
497 ;; Those are decoded by server-process-filter according
498 ;; to file-name-coding-system.
500 ;; The rest of the args depends on the kind of socket used.
504 :host (or server-host 'local)
505 :plist '(:authenticated nil))
508 :plist '(:authenticated t)))))
509 (unless server-process (error "Could not start server process"))
513 ;; The auth key is a 64-byte string of random chars in the
516 collect (+ 33 (random 94)) into auth
517 finally return (concat auth))))
518 (process-put server-process :auth-key auth-key)
519 (with-temp-file server-file
520 (set-buffer-multibyte nil)
521 (setq buffer-file-coding-system 'no-conversion)
522 (insert (format-network-address
523 (process-contact server-process :local))
524 " " (int-to-string (emacs-pid))
525 "\n" auth-key)))))))))
528 (define-minor-mode server-mode
530 With ARG, turn Server mode on if ARG is positive, off otherwise.
531 Server mode runs a process that accepts commands from the
532 `emacsclient' program. See `server-start' and Info node `Emacs server'."
536 ;; Fixme: Should this check for an existing server socket and do
537 ;; nothing if there is one (for multiple Emacs sessions)?
538 (server-start (not server-mode)))
540 (defun* server-process-filter (proc string)
541 "Process a request from the server to edit some files.
542 PROC is the server process. STRING consists of a sequence of
543 commands prefixed by a dash. Some commands have arguments; these
544 are &-quoted and need to be decoded by `server-unquote-arg'. The
545 filter parses and executes these commands.
547 To illustrate the protocol, here is an example command that
548 emacsclient sends to create a new X frame (note that the whole
549 sequence is sent on a single line):
551 -version 21.3.50 xterm
552 -env HOME /home/lorentey
554 ... lots of other -env commands
558 The server normally sends back the single command `-good-version'
561 The following commands are accepted by the server:
564 Authenticate the client using the secret authentication string
567 `-version CLIENT-VERSION'
568 Check version numbers between server and client, and signal an
569 error if there is a mismatch. The server replies with
570 `-good-version' to confirm the match.
573 An environment variable on the client side.
576 The current working directory of the client process.
579 Forbid the creation of new frames.
582 Request that the next frame created should not be
583 associated with this client.
586 Set the display name to open X frames on.
588 `-position LINE[:COLUMN]'
589 Go to the given line and column number
590 in the next file opened.
593 Load the given file in the current frame.
596 Evaluate EXPR as a Lisp expression and return the
597 result in -print commands.
602 `-tty DEVICENAME TYPE'
603 Open a new tty frame at the client.
606 Suspend this tty frame. The client sends this string in
607 response to SIGTSTP and SIGTTOU. The server must cease all I/O
608 on this tty until it gets a -resume command.
611 Resume this tty frame. The client sends this string when it
612 gets the SIGCONT signal and it is the foreground process on its
616 Do nothing, but put the comment in the server
617 log. Useful for debugging.
620 The following commands are accepted by the client:
623 Signals a version match between the client and the server.
626 Describes the process id of the Emacs process;
627 used to forward window change signals to it.
629 `-window-system-unsupported'
630 Signals that the server does not
631 support creating X frames; the client must try again with a tty
635 Print STRING on stdout. Used to send values
639 Signal an error (but continue processing).
642 Suspend this terminal, i.e., stop the client process. Sent
643 when the user presses C-z."
644 (server-log (concat "Received " string) proc)
645 ;; First things first: let's check the authentication
646 (unless (process-get proc :authenticated)
647 (if (and (string-match "-auth \\(.*?\\)\n" string)
648 (equal (match-string 1 string) (process-get proc :auth-key)))
650 (setq string (substring string (match-end 0)))
651 (process-put proc :authenticated t)
652 (server-log "Authentication successful" proc))
653 (server-log "Authentication failed" proc)
655 proc (concat "-error " (server-quote-arg "Authentication failed")))
656 (delete-process proc)
657 ;; We return immediately
658 (return-from server-process-filter)))
659 (when (> (recursion-depth) 0)
660 ;; We're inside a minibuffer already, so if the emacs-client is trying
661 ;; to open a frame on a new display, we might end up with an unusable
662 ;; frame because input from that display will be blocked (until exiting
663 ;; the minibuffer). Better exit this minibuffer right away.
664 ;; Similarly with recursive-edits such as the splash screen.
665 (process-put proc :previous-string string)
666 (run-with-timer 0 nil (lexical-let ((proc proc))
667 (lambda () (server-process-filter proc ""))))
669 (let ((prev (process-get proc 'previous-string)))
671 (setq string (concat prev string))
672 (process-put proc 'previous-string nil)))
675 (server-add-client proc)
676 ;; If the input is multiple lines,
677 ;; process each line individually.
678 (while (string-match "\n" string)
679 (let ((request (substring string 0 (match-beginning 0)))
680 (coding-system (and default-enable-multibyte-characters
681 (or file-name-coding-system
682 default-file-name-coding-system)))
683 (client (server-client proc))
685 nowait ; t if emacsclient does not want to wait for us.
686 frame ; The frame that was opened for the client (if any).
687 display ; Open the frame on this display.
688 dontkill ; t if the client should not be killed.
694 ;; Remove this line from STRING.
695 (setq string (substring string (match-end 0)))
696 (while (string-match " *[^ ]* " request)
697 (let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
698 (setq request (substring request (match-end 0)))
700 ;; -version CLIENT-VERSION:
701 ;; Check version numbers, signal an error if there is a mismatch.
702 ((and (equal "-version" arg)
703 (string-match "\\([0-9.]+\\) " request))
704 (let* ((client-version (match-string 1 request))
705 (truncated-emacs-version
706 (substring emacs-version 0 (length client-version))))
707 (setq request (substring request (match-end 0)))
708 (if (equal client-version truncated-emacs-version)
710 (server-send-string proc "-good-version \n")
711 (server-client-set client 'version client-version))
712 (error (concat "Version mismatch: Emacs is "
713 truncated-emacs-version
714 ", emacsclient is " client-version)))))
716 ;; -nowait: Emacsclient won't wait for a result.
717 ((equal "-nowait" arg) (setq nowait t))
719 ;; -current-frame: Don't create frames.
720 ((equal "-current-frame" arg) (setq current-frame t))
723 ;; Open X frames on the given display instead of the default.
724 ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
725 (setq display (match-string 1 request)
726 request (substring request (match-end 0))))
728 ;; -window-system: Open a new X frame.
729 ((equal "-window-system" arg)
730 (unless (server-client-get client 'version)
731 (error "Protocol error; make sure to use the correct version of emacsclient"))
732 (unless current-frame
733 (if (fboundp 'x-create-frame)
734 (let ((params (if nowait
735 ;; Flag frame as client-created, but use a dummy client.
736 ;; This will prevent the frame from being deleted when
737 ;; emacsclient quits while also preventing
738 ;; `server-save-buffers-kill-terminal' from unexpectedly
739 ;; killing emacs on that frame.
740 (list (cons 'client 'nowait) (cons 'environment env))
741 (list (cons 'client proc) (cons 'environment env)))))
742 (setq frame (make-frame-on-display
744 (frame-parameter nil 'display)
746 (error "Please specify display"))
748 (server-log (format "%s created" frame) proc)
749 ;; XXX We need to ensure the parameters are
750 ;; really set because Emacs forgets unhandled
751 ;; initialization parameters for X frames at
753 (modify-frame-parameters frame params)
755 (server-client-set client 'frame frame)
756 (server-client-set client 'terminal (frame-terminal frame))
758 ;; Display *scratch* by default.
759 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
760 (if dir (setq default-directory dir))
763 ;; This emacs does not support X.
764 (server-log "Window system unsupported" proc)
765 (server-send-string proc "-window-system-unsupported \n")
768 ;; -resume: Resume a suspended tty frame.
769 ((equal "-resume" arg)
770 (let ((terminal (server-client-get client 'terminal)))
772 (when (eq (terminal-live-p terminal) t)
773 (resume-tty terminal))))
775 ;; -suspend: Suspend the client's frame. (In case we
776 ;; get out of sync, and a C-z sends a SIGTSTP to
778 ((equal "-suspend" arg)
779 (let ((terminal (server-client-get client 'terminal)))
781 (when (eq (terminal-live-p terminal) t)
782 (suspend-tty terminal))))
784 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
785 ;; (The given comment appears in the server log.)
786 ((and (equal "-ignore" arg) (string-match "\\([^ ]*\\) " request))
788 request (substring request (match-end 0))))
790 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
791 ((and (equal "-tty" arg) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request))
792 (let ((tty (server-unquote-arg (match-string 1 request)))
793 (type (server-unquote-arg (match-string 2 request))))
794 (setq request (substring request (match-end 0)))
795 (unless (server-client-get client 'version)
796 (error "Protocol error; make sure you use the correct version of emacsclient"))
797 (unless current-frame
798 (server-with-environment env
799 '("LANG" "LC_CTYPE" "LC_ALL"
800 ;; For tgetent(3); list according to ncurses(3).
801 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
802 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
803 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
804 "TERMINFO_DIRS" "TERMPATH")
805 (setq frame (make-frame-on-tty tty type
806 ;; Ignore nowait here; we always need to clean
807 ;; up opened ttys when the client dies.
809 (environment . ,env)))))
811 (server-client-set client 'frame frame)
812 (server-client-set client 'tty (terminal-name frame))
813 (server-client-set client 'terminal (frame-terminal frame))
815 ;; Display *scratch* by default.
816 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
817 (if dir (setq default-directory dir))
819 ;; Reply with our pid.
820 (server-send-string proc (concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
823 ;; -position LINE: Go to the given line in the next file.
824 ((and (equal "-position" arg) (string-match "\\(\\+[0-9]+\\) " request))
825 (setq lineno (string-to-number (substring (match-string 1 request) 1))
826 request (substring request (match-end 0))))
828 ;; -position LINE:COLUMN: Set point to the given position in the next file.
829 ((and (equal "-position" arg) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request))
830 (setq lineno (string-to-number (match-string 1 request))
831 columnno (string-to-number (match-string 2 request))
832 request (substring request (match-end 0))))
834 ;; -file FILENAME: Load the given file.
835 ((and (equal "-file" arg) (string-match "\\([^ ]+\\) " request))
836 (let ((file (server-unquote-arg (match-string 1 request))))
837 (setq request (substring request (match-end 0)))
839 (setq file (decode-coding-string file coding-system)))
840 (setq file (command-line-normalize-file-name file))
841 (push (list file lineno columnno) files)
842 (server-log (format "New file: %s (%d:%d)" file lineno columnno) proc))
846 ;; -eval EXPR: Evaluate a Lisp expression.
847 ((and (equal "-eval" arg) (string-match "\\([^ ]+\\) " request))
848 (let ((expr (server-unquote-arg (match-string 1 request))))
849 (setq request (substring request (match-end 0)))
851 (setq expr (decode-coding-string expr coding-system)))
852 (let ((v (eval (car (read-from-string expr)))))
853 (when (and (not frame) v)
855 (let ((standard-output (current-buffer)))
858 proc (format "-print %s\n"
860 (buffer-substring-no-properties (point-min)
865 ;; -env NAME=VALUE: An environment variable.
866 ((and (equal "-env" arg) (string-match "\\([^ ]+\\) " request))
867 (let ((var (server-unquote-arg (match-string 1 request))))
868 ;; XXX Variables should be encoded as in getenv/setenv.
869 (setq request (substring request (match-end 0)))
870 (setq env (cons var env))))
872 ;; -dir DIRNAME: The cwd of the emacsclient process.
873 ((and (equal "-dir" arg) (string-match "\\([^ ]+\\) " request))
874 (setq dir (server-unquote-arg (match-string 1 request)))
875 (setq request (substring request (match-end 0)))
877 (setq dir (decode-coding-string dir coding-system)))
878 (setq dir (command-line-normalize-file-name dir)))
881 (t (error "Unknown command: %s" arg)))))
885 (run-hooks 'pre-command-hook)
886 (setq buffers (server-visit-files files client nowait))
887 (run-hooks 'post-command-hook))
890 (with-selected-frame frame
891 (display-startup-echo-area-message)
892 (unless inhibit-splash-screen
894 ;; This looks scary because `fancy-splash-screens'
895 ;; will call `recursive-edit' from a process filter.
896 ;; However, that should be safe to do now.
897 (display-splash-screen t)
898 ;; `recursive-edit' will throw an error if Emacs is
899 ;; already doing a recursive edit elsewhere. Catch it
900 ;; here so that we can finish normally.
903 ;; Delete the client if necessary.
906 ;; Client requested nowait; return immediately.
907 (server-log "Close nowait client" proc)
908 (server-delete-client proc))
909 ((and (not dontkill) (null buffers))
910 ;; This client is empty; get rid of it immediately.
911 (server-log "Close empty client" proc)
912 (server-delete-client proc)))
914 ((or isearch-mode (minibufferp))
916 ((and frame (null buffers))
917 (message "%s" (substitute-command-keys
918 "When done with this frame, type \\[delete-frame]")))
919 ((not (null buffers))
920 (server-switch-buffer (car buffers))
921 (run-hooks 'server-switch-hook)
923 (message "%s" (substitute-command-keys
924 "When done with a buffer, type \\[server-edit]"))))))))
926 ;; Save for later any partial line that remains.
927 (when (> (length string) 0)
928 (process-put proc 'previous-string string)))
930 (error (ignore-errors
932 proc (concat "-error " (server-quote-arg (error-message-string err))))
934 (server-log (error-message-string err) proc)
935 (delete-process proc)))))
937 (defun server-goto-line-column (file-line-col)
938 "Move point to the position indicated in FILE-LINE-COL.
939 FILE-LINE-COL should be a three-element list as described in
940 `server-visit-files'."
941 (goto-line (nth 1 file-line-col))
942 (let ((column-number (nth 2 file-line-col)))
943 (if (> column-number 0)
944 (move-to-column (1- column-number)))))
946 (defun server-visit-files (files client &optional nowait)
947 "Find FILES and return a list of buffers created.
948 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
949 CLIENT is the client that requested this operation.
950 NOWAIT non-nil means this client is not waiting for the results,
951 so don't mark these buffers specially, just visit them normally."
952 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
953 (let ((last-nonmenu-event t) client-record)
954 ;; Restore the current buffer afterward, but not using save-excursion,
955 ;; because we don't want to save point in this buffer
956 ;; if it happens to be one of those specified by the server.
959 ;; If there is an existing buffer modified or the file is
960 ;; modified, revert it. If there is an existing buffer with
961 ;; deleted file, offer to write it.
962 (let* ((minibuffer-auto-raise (or server-raise-frame
963 minibuffer-auto-raise))
965 (obuf (get-file-buffer filen)))
966 (add-to-history 'file-name-history filen)
967 (if (and obuf (set-buffer obuf))
969 (cond ((file-exists-p filen)
970 (when (not (verify-visited-file-modtime obuf))
971 (revert-buffer t nil)))
974 (concat "File no longer exists: " filen
975 ", write buffer to file? "))
976 (write-file filen))))
977 (unless server-buffer-clients
978 (setq server-existing-buffer t))
979 (server-goto-line-column file))
980 (set-buffer (find-file-noselect filen))
981 (server-goto-line-column file)
982 (run-hooks 'server-visit-hook)))
984 ;; When the buffer is killed, inform the clients.
985 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
986 (push (car client) server-buffer-clients))
987 (push (current-buffer) client-record)))
991 (nconc (server-client-get client 'buffers) client-record)))
994 (defun server-buffer-done (buffer &optional for-killing)
995 "Mark BUFFER as \"done\" for its client(s).
996 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
997 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
998 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1000 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1001 (let ((next-buffer nil)
1003 (dolist (client server-clients)
1004 (let ((buffers (server-client-get client 'buffers)))
1006 (setq next-buffer (nth 1 (memq buffer buffers))))
1007 (when buffers ; Ignore bufferless clients.
1008 (setq buffers (delq buffer buffers))
1009 ;; Delete all dead buffers from CLIENT.
1012 (not (buffer-live-p b))
1013 (setq buffers (delq b buffers))))
1014 (server-client-set client 'buffers buffers)
1015 ;; If client now has no pending buffers,
1016 ;; tell it that it is done, and forget it entirely.
1018 (server-log "Close" client)
1019 (server-delete-client client)))))
1020 (when (and (bufferp buffer) (buffer-name buffer))
1021 ;; We may or may not kill this buffer;
1022 ;; if we do, do not call server-buffer-done recursively
1023 ;; from kill-buffer-hook.
1024 (let ((server-kill-buffer-running t))
1025 (with-current-buffer buffer
1026 (setq server-buffer-clients nil)
1027 (run-hooks 'server-done-hook))
1028 ;; Notice whether server-done-hook killed the buffer.
1029 (if (null (buffer-name buffer))
1031 ;; Don't bother killing or burying the buffer
1032 ;; when we are called from kill-buffer.
1034 (when (and (not killed)
1035 server-kill-new-buffers
1036 (with-current-buffer buffer
1037 (not server-existing-buffer)))
1039 (bury-buffer buffer)
1040 (kill-buffer buffer))
1042 (if (server-temp-file-p buffer)
1044 (kill-buffer buffer)
1046 (bury-buffer buffer)))))))
1047 (list next-buffer killed)))
1049 (defun server-temp-file-p (&optional buffer)
1050 "Return non-nil if BUFFER contains a file considered temporary.
1051 These are files whose names suggest they are repeatedly
1052 reused to pass information to another program.
1054 The variable `server-temp-file-regexp' controls which filenames
1055 are considered temporary."
1056 (and (buffer-file-name buffer)
1057 (string-match server-temp-file-regexp (buffer-file-name buffer))))
1059 (defun server-done ()
1060 "Offer to save current buffer, mark it as \"done\" for clients.
1061 This kills or buries the buffer, then returns a list
1062 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1063 as a suggestion for what to select next, or nil.
1064 KILLED is t if we killed BUFFER, which happens if it was created
1065 specifically for the clients and did not exist before their request for it."
1066 (when server-buffer-clients
1067 (if (server-temp-file-p)
1068 ;; For a temp file, save, and do make a non-numeric backup
1069 ;; (unless make-backup-files is nil).
1070 (let ((version-control nil)
1071 (buffer-backed-up nil))
1073 (when (and (buffer-modified-p)
1075 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1077 (server-buffer-done (current-buffer))))
1079 ;; Ask before killing a server buffer.
1080 ;; It was suggested to release its client instead,
1081 ;; but I think that is dangerous--the client would proceed
1082 ;; using whatever is on disk in that file. -- rms.
1083 (defun server-kill-buffer-query-function ()
1084 "Ask before killing a server buffer."
1085 (or (not server-buffer-clients)
1087 (dolist (proc server-buffer-clients res)
1088 (let ((client (server-client proc)))
1089 (when (and client (eq (process-status proc) 'open))
1091 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1092 (buffer-name (current-buffer))))))
1094 (defun server-kill-emacs-query-function ()
1095 "Ask before exiting Emacs it has live clients."
1096 (or (not server-clients)
1098 (dolist (client server-clients live-client)
1099 (when (memq t (mapcar 'buffer-live-p (server-client-get
1101 (setq live-client t))))
1102 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1104 (defvar server-kill-buffer-running nil
1105 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1107 (defun server-kill-buffer ()
1108 "Remove the current buffer from its clients' buffer list.
1109 Designed to be added to `kill-buffer-hook'."
1110 ;; Prevent infinite recursion if user has made server-done-hook
1111 ;; call kill-buffer.
1112 (or server-kill-buffer-running
1113 (and server-buffer-clients
1114 (let ((server-kill-buffer-running t))
1115 (when server-process
1116 (server-buffer-done (current-buffer) t))))))
1118 (defun server-edit (&optional arg)
1119 "Switch to next server editing buffer; say \"Done\" for current buffer.
1120 If a server buffer is current, it is marked \"done\" and optionally saved.
1121 The buffer is also killed if it did not exist before the clients asked for it.
1122 When all of a client's buffers are marked as \"done\", the client is notified.
1124 Temporary files such as MH <draft> files are always saved and backed up,
1125 no questions asked. (The variable `make-backup-files', if nil, still
1126 inhibits a backup; you can set it locally in a particular buffer to
1127 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1128 which filenames are considered temporary.
1130 If invoked with a prefix argument, or if there is no server process running,
1131 starts server process and that is all. Invoked by \\[server-edit]."
1135 (not server-process)
1136 (memq (process-status server-process) '(signal exit)))
1138 (server-clients (apply 'server-switch-buffer (server-done)))
1139 (t (message "No server editing buffers exist"))))
1141 (defun server-switch-buffer (&optional next-buffer killed-one)
1142 "Switch to another buffer, preferably one that has a client.
1143 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1145 KILLED-ONE is t in a recursive call if we have already killed one
1146 temp-file server buffer. This means we should avoid the final
1147 \"switch to some other buffer\" since we've already effectively
1149 (if (null next-buffer)
1151 (let ((rest server-clients))
1152 (while (and rest (not next-buffer))
1153 (let ((client (car rest)))
1154 ;; Only look at frameless clients.
1155 (when (not (server-client-get client 'frame))
1156 (setq next-buffer (car (server-client-get client 'buffers))))
1157 (setq rest (cdr rest)))))
1158 (and next-buffer (server-switch-buffer next-buffer killed-one))
1159 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1160 ;; (switch-to-buffer (other-buffer))
1161 (message "No server buffers remain to edit")))
1162 (if (not (buffer-live-p next-buffer))
1163 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1164 ;; and try the next surviving server buffer.
1165 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1166 ;; OK, we know next-buffer is live, let's display and select it.
1167 (if (functionp server-window)
1168 (funcall server-window next-buffer)
1169 (let ((win (get-buffer-window next-buffer 0)))
1170 (if (and win (not server-window))
1171 ;; The buffer is already displayed: just reuse the window.
1174 (set-buffer next-buffer))
1175 ;; Otherwise, let's find an appropriate window.
1176 (cond ((and (windowp server-window)
1177 (window-live-p server-window))
1178 (select-window server-window))
1179 ((framep server-window)
1180 (unless (frame-live-p server-window)
1181 (setq server-window (make-frame)))
1182 (select-window (frame-selected-window server-window))))
1183 (when (window-minibuffer-p (selected-window))
1184 (select-window (next-window nil 'nomini 0)))
1185 ;; Move to a non-dedicated window, if we have one.
1186 (when (window-dedicated-p (selected-window))
1188 (get-window-with-predicate
1190 (and (not (window-dedicated-p w))
1191 (equal (frame-terminal (window-frame w))
1192 (frame-terminal (selected-frame)))))
1193 'nomini 'visible (selected-window))))
1195 (switch-to-buffer next-buffer)
1196 ;; After all the above, we might still have ended up with
1197 ;; a minibuffer/dedicated-window (if there's no other).
1198 (error (pop-to-buffer next-buffer)))))))
1199 (when server-raise-frame
1200 (select-frame-set-input-focus (window-frame (selected-window))))))
1203 (defun server-save-buffers-kill-terminal (proc &optional arg)
1204 "Offer to save each buffer, then kill PROC.
1206 With prefix arg, silently save all file-visiting buffers, then kill.
1208 If emacsclient was started with a list of filenames to edit, then
1209 only these files will be asked to be saved."
1210 (let ((buffers (server-client-get proc 'buffers)))
1211 ;; If client is bufferless, emulate a normal Emacs session
1212 ;; exit and offer to save all buffers. Otherwise, offer to
1213 ;; save only the buffers belonging to the client.
1214 (save-some-buffers arg
1216 (lambda () (memq (current-buffer) buffers))
1218 (server-delete-client proc)))
1220 (define-key ctl-x-map "#" 'server-edit)
1222 (defun server-unload-hook ()
1223 "Unload the server library."
1225 (remove-hook 'suspend-tty-functions 'server-handle-suspend-tty)
1226 (remove-hook 'delete-frame-functions 'server-handle-delete-frame)
1227 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
1228 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
1229 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
1231 (add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
1232 (add-hook 'server-unload-hook 'server-unload-hook)
1236 ;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1237 ;;; server.el ends here