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 3, 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
(concat user-emacs-directory
"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
"Display in new frame" switch-to-buffer-other-frame
)
168 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
169 (function :tag
"Other function")))
171 (defcustom server-temp-file-regexp
"^/tmp/Re\\|/draft$"
172 "Regexp matching names of temporary files.
173 These are deleted and reused after each edit by the programs that
174 invoke the Emacs server."
178 (defcustom server-kill-new-buffers t
179 "Whether to kill buffers when done with them.
180 If non-nil, kill a buffer unless it already existed before editing
181 it with Emacs server. If nil, kill only buffers as specified by
182 `server-temp-file-regexp'.
183 Please note that only buffers are killed that still have a client,
184 i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
190 (or (assq 'server-buffer-clients minor-mode-alist
)
191 (push '(server-buffer-clients " Server") minor-mode-alist
))
193 (defvar server-existing-buffer nil
194 "Non-nil means the buffer existed before the server was asked to visit it.
195 This means that the server should not kill the buffer when you say you
196 are done with it in the server.")
197 (make-variable-buffer-local 'server-existing-buffer
)
199 (defvar server-name
"server")
201 (defvar server-socket-dir nil
202 "The directory in which to place the server socket.
203 Initialized by `server-start'.")
205 (defun server-client (proc)
206 "Return the Emacs client corresponding to PROC.
207 PROC must be a process object.
208 The car of the result is PROC; the cdr is an association list.
209 See `server-client-get' and `server-client-set'."
210 (assq proc server-clients
))
212 (defun server-client-get (client property
)
213 "Get the value of PROPERTY in CLIENT.
214 CLIENT may be a process object, or a client returned by `server-client'.
215 Return nil if CLIENT has no such property."
216 (or (listp client
) (setq client
(server-client client
)))
217 (cdr (assq property
(cdr client
))))
219 (defun server-client-set (client property value
)
220 "Set the PROPERTY to VALUE in CLIENT, and return VALUE.
221 CLIENT may be a process object, or a client returned by `server-client'."
224 (setq proc
(car client
))
226 client
(server-client client
)))
227 (setq p
(assq property client
))
230 (client (setcdr client
(cons (cons property value
) (cdr client
))))
231 (t (setq server-clients
232 `((,proc
(,property .
,value
)) .
,server-clients
))))
235 (defun server-clients-with (property value
)
236 "Return a list of clients with PROPERTY set to VALUE."
238 (dolist (client server-clients result
)
239 (when (equal value
(server-client-get client property
))
240 (setq result
(cons (car client
) result
))))))
242 (defun server-add-client (proc)
243 "Create a client for process PROC, if it doesn't already have one.
244 New clients have no properties."
245 (unless (server-client proc
)
246 (setq server-clients
(cons (cons proc nil
)
249 (defun server-getenv-from (env variable
)
250 "Get the value of VARIABLE in ENV.
251 VARIABLE should be a string. Value is nil if VARIABLE is
252 undefined in ENV. Otherwise, value is a string.
254 ENV should be in the same format as `process-environment'."
256 (while (and env
(null result
))
257 (setq entry
(car env
)
259 (if (and (> (length entry
) (length variable
))
260 (eq ?
= (aref entry
(length variable
)))
261 (equal variable
(substring entry
0 (length variable
))))
262 (setq result
(substring entry
(+ (length variable
) 1)))))
265 (defmacro server-with-environment
(env vars
&rest body
)
266 "Evaluate BODY with environment variables VARS set to those in ENV.
267 The environment variables are then restored to their previous values.
269 VARS should be a list of strings.
270 ENV should be in the same format as `process-environment'."
272 (let ((old-env (make-symbol "old-env"))
273 (var (make-symbol "var"))
274 (value (make-symbol "value"))
275 (pair (make-symbol "pair")))
276 `(let ((,old-env process-environment
))
278 (let ((,value
(server-getenv-from ,env
,var
)))
279 (setq process-environment
280 (cons (if (null ,value
)
282 (concat ,var
"=" ,value
))
283 process-environment
))))
286 (setq process-environment
,old-env
)))))
288 (defun server-delete-client (client &optional noframe
)
289 "Delete CLIENT, including its buffers, terminals and frames.
290 If NOFRAME is non-nil, let the frames live. (To be used from
291 `delete-frame-functions'.)"
292 (server-log (concat "server-delete-client" (if noframe
" noframe"))
294 ;; Force a new lookup of client (prevents infinite recursion).
295 (setq client
(server-client
296 (if (listp client
) (car client
) client
)))
297 (let ((proc (car client
))
298 (buffers (server-client-get client
'buffers
)))
301 ;; Kill the client's buffers.
302 (dolist (buf buffers
)
303 (when (buffer-live-p buf
)
304 (with-current-buffer buf
305 ;; Kill the buffer if necessary.
306 (when (and (equal server-buffer-clients
308 (or (and server-kill-new-buffers
309 (not server-existing-buffer
))
310 (server-temp-file-p))
311 (not (buffer-modified-p)))
314 (progn (setq server-buffer-clients nil
)
315 (kill-buffer (current-buffer))
318 ;; Restore clients if user pressed C-g in `kill-buffer'.
319 (setq server-buffer-clients
(list proc
)))))))))
321 ;; Delete the client's frames.
323 (dolist (frame (frame-list))
324 (when (and (frame-live-p frame
)
325 (equal proc
(frame-parameter frame
'client
)))
326 ;; Prevent `server-handle-delete-frame' from calling us
328 (set-frame-parameter frame
'client nil
)
329 (delete-frame frame
))))
331 (setq server-clients
(delq client server-clients
))
333 ;; Delete the client's tty.
334 (let ((terminal (server-client-get client
'terminal
)))
335 (when (eq (terminal-live-p terminal
) t
)
336 (delete-terminal terminal
)))
338 ;; Delete the client's process.
339 (if (eq (process-status (car client
)) 'open
)
340 (delete-process (car client
)))
342 (server-log "Deleted" proc
))))
344 (defun server-log (string &optional client
)
345 "If a *server* buffer exists, write STRING to it for logging purposes.
346 If CLIENT is non-nil, add a description of it to the logged
348 (when (get-buffer "*server*")
349 (with-current-buffer "*server*"
350 (goto-char (point-max))
351 (insert (current-time-string)
354 ((listp client
) (format " %s: " (car client
)))
355 (t (format " %s: " client
)))
357 (or (bolp) (newline)))))
359 (defun server-sentinel (proc msg
)
360 "The process sentinel for Emacs server connections."
361 ;; If this is a new client process, set the query-on-exit flag to nil
362 ;; for this process (it isn't inherited from the server process).
363 (when (and (eq (process-status proc
) 'open
)
364 (process-query-on-exit-flag proc
))
365 (set-process-query-on-exit-flag proc nil
))
366 ;; Delete the associated connection file, if applicable.
367 ;; This is actually problematic: the file may have been overwritten by
368 ;; another Emacs server in the mean time, so it's not ours any more.
369 ;; (and (process-contact proc :server)
370 ;; (eq (process-status proc) 'closed)
371 ;; (ignore-errors (delete-file (process-get proc :server-file))))
372 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
373 (server-delete-client proc
))
375 (defun server-handle-delete-frame (frame)
376 "Delete the client connection when the emacsclient frame is deleted."
377 (let ((proc (frame-parameter frame
'client
)))
378 (when (and (frame-live-p frame
)
380 ;; See if this is the last frame for this client.
381 (>= 1 (let ((frame-num 0))
382 (dolist (f (frame-list))
383 (when (eq proc
(frame-parameter f
'client
))
384 (setq frame-num
(1+ frame-num
))))
386 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
387 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
389 (defun server-handle-suspend-tty (terminal)
390 "Notify the emacsclient process to suspend itself when its tty device is suspended."
391 (dolist (proc (server-clients-with 'terminal terminal
))
392 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
) proc
)
394 (server-send-string proc
"-suspend \n")
395 (file-error (condition-case nil
(server-delete-client proc
) (error nil
))))))
397 (defun server-unquote-arg (arg)
398 "Remove &-quotation from ARG.
399 See `server-quote-arg' and `server-process-filter'."
400 (replace-regexp-in-string
409 (defun server-quote-arg (arg)
410 "In ARG, insert a & before each &, each space, each newline, and -.
411 Change spaces to underscores, too, so that the return value never
414 See `server-unquote-arg' and `server-process-filter'."
415 (replace-regexp-in-string
416 "[-&\n ]" (lambda (s)
424 (defun server-send-string (proc string
)
425 "A wrapper around `proc-send-string' for logging."
426 (server-log (concat "Sent " string
) proc
)
427 (process-send-string proc string
))
429 (defun server-ensure-safe-dir (dir)
430 "Make sure DIR is a directory with no race-condition issues.
431 Creates the directory if necessary and makes sure:
432 - there's no symlink involved
434 - it's not readable/writable by anybody else."
435 (setq dir
(directory-file-name dir
))
436 (let ((attrs (file-attributes dir
)))
438 (letf (((default-file-modes) ?
\700)) (make-directory dir t
))
439 (setq attrs
(file-attributes dir
)))
440 ;; Check that it's safe for use.
441 (unless (and (eq t
(car attrs
)) (eql (nth 2 attrs
) (user-uid))
442 (or (eq system-type
'windows-nt
)
443 (zerop (logand ?
\077 (file-modes dir
)))))
444 (error "The directory %s is unsafe" dir
))))
447 (defun server-start (&optional leave-dead
)
448 "Allow this Emacs process to be a server for client processes.
449 This starts a server communications subprocess through which
450 client \"editors\" can send your editing commands to this Emacs
451 job. To use the server, set up the program `emacsclient' in the
452 Emacs distribution as your standard \"editor\".
454 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
455 kill any existing server communications subprocess."
460 "The current server still has clients; delete them? "))
461 ;; It is safe to get the user id now.
462 (setq server-socket-dir
(or server-socket-dir
463 (format "/tmp/emacs%d" (user-uid))))
466 (ignore-errors (delete-process server-process
)))
467 ;; Delete the socket files made by previous server invocations.
469 (delete-file (expand-file-name server-name server-socket-dir
))
471 ;; If this Emacs already had a server, clear out associated status.
472 (while server-clients
473 (server-delete-client (car server-clients
)))
474 ;; Now any previous server is properly stopped.
477 (server-log (message "Server stopped"))
478 (setq server-process nil
))
479 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
480 (server-file (expand-file-name server-name server-dir
)))
481 ;; Make sure there is a safe directory in which to place the socket.
482 (server-ensure-safe-dir server-dir
)
483 ;; Remove any leftover socket or authentication file.
484 (ignore-errors (delete-file server-file
))
486 (server-log (message "Restarting server")))
487 (letf (((default-file-modes) ?
\700))
488 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
489 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
490 (add-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
491 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
493 (apply #'make-network-process
497 :sentinel
'server-sentinel
498 :filter
'server-process-filter
499 ;; We must receive file names without being decoded.
500 ;; Those are decoded by server-process-filter according
501 ;; to file-name-coding-system.
503 ;; The rest of the args depends on the kind of socket used.
507 :host
(or server-host
'local
)
508 :plist
'(:authenticated nil
))
511 :plist
'(:authenticated t
)))))
512 (unless server-process
(error "Could not start server process"))
516 ;; The auth key is a 64-byte string of random chars in the
519 collect
(+ 33 (random 94)) into auth
520 finally return
(concat auth
))))
521 (process-put server-process
:auth-key auth-key
)
522 (with-temp-file server-file
523 (set-buffer-multibyte nil
)
524 (setq buffer-file-coding-system
'no-conversion
)
525 (insert (format-network-address
526 (process-contact server-process
:local
))
527 " " (int-to-string (emacs-pid))
528 "\n" auth-key
)))))))))
531 (define-minor-mode server-mode
533 With ARG, turn Server mode on if ARG is positive, off otherwise.
534 Server mode runs a process that accepts commands from the
535 `emacsclient' program. See `server-start' and Info node `Emacs server'."
539 ;; Fixme: Should this check for an existing server socket and do
540 ;; nothing if there is one (for multiple Emacs sessions)?
541 (server-start (not server-mode
)))
543 (defun* server-process-filter
(proc string
)
544 "Process a request from the server to edit some files.
545 PROC is the server process. STRING consists of a sequence of
546 commands prefixed by a dash. Some commands have arguments; these
547 are &-quoted and need to be decoded by `server-unquote-arg'. The
548 filter parses and executes these commands.
550 To illustrate the protocol, here is an example command that
551 emacsclient sends to create a new X frame (note that the whole
552 sequence is sent on a single line):
554 -version 21.3.50 xterm
555 -env HOME /home/lorentey
557 ... lots of other -env commands
561 The server normally sends back the single command `-good-version'
564 The following commands are accepted by the server:
567 Authenticate the client using the secret authentication string
570 `-version CLIENT-VERSION'
571 Check version numbers between server and client, and signal an
572 error if there is a mismatch. The server replies with
573 `-good-version' to confirm the match.
576 An environment variable on the client side.
579 The current working directory of the client process.
582 Forbid the creation of new frames.
585 Request that the next frame created should not be
586 associated with this client.
589 Set the display name to open X frames on.
591 `-position LINE[:COLUMN]'
592 Go to the given line and column number
593 in the next file opened.
596 Load the given file in the current frame.
599 Evaluate EXPR as a Lisp expression and return the
600 result in -print commands.
605 `-tty DEVICENAME TYPE'
606 Open a new tty frame at the client.
609 Suspend this tty frame. The client sends this string in
610 response to SIGTSTP and SIGTTOU. The server must cease all I/O
611 on this tty until it gets a -resume command.
614 Resume this tty frame. The client sends this string when it
615 gets the SIGCONT signal and it is the foreground process on its
619 Do nothing, but put the comment in the server
620 log. Useful for debugging.
623 The following commands are accepted by the client:
626 Signals a version match between the client and the server.
629 Describes the process id of the Emacs process;
630 used to forward window change signals to it.
632 `-window-system-unsupported'
633 Signals that the server does not
634 support creating X frames; the client must try again with a tty
638 Print STRING on stdout. Used to send values
642 Signal an error (but continue processing).
645 Suspend this terminal, i.e., stop the client process. Sent
646 when the user presses C-z."
647 (server-log (concat "Received " string
) proc
)
648 ;; First things first: let's check the authentication
649 (unless (process-get proc
:authenticated
)
650 (if (and (string-match "-auth \\(.*?\\)\n" string
)
651 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
653 (setq string
(substring string
(match-end 0)))
654 (process-put proc
:authenticated t
)
655 (server-log "Authentication successful" proc
))
656 (server-log "Authentication failed" proc
)
658 proc
(concat "-error " (server-quote-arg "Authentication failed")))
659 (delete-process proc
)
660 ;; We return immediately
661 (return-from server-process-filter
)))
662 (when (> (recursion-depth) 0)
663 ;; We're inside a minibuffer already, so if the emacs-client is trying
664 ;; to open a frame on a new display, we might end up with an unusable
665 ;; frame because input from that display will be blocked (until exiting
666 ;; the minibuffer). Better exit this minibuffer right away.
667 ;; Similarly with recursive-edits such as the splash screen.
668 (process-put proc
:previous-string string
)
669 (run-with-timer 0 nil
(lexical-let ((proc proc
))
670 (lambda () (server-process-filter proc
""))))
673 ;; If we're running isearch, we must abort it to allow Emacs to
674 ;; display the buffer and switch to it.
675 (mapc #'(lambda (buffer)
676 (with-current-buffer buffer
677 (when (bound-and-true-p isearch-mode
)
680 ;; Signaled by isearch-cancel
681 (quit (message nil
)))
682 (let ((prev (process-get proc
'previous-string
)))
684 (setq string
(concat prev string
))
685 (process-put proc
'previous-string nil
)))
688 (server-add-client proc
)
689 ;; If the input is multiple lines,
690 ;; process each line individually.
691 (while (string-match "\n" string
)
692 (let ((request (substring string
0 (match-beginning 0)))
693 (coding-system (and default-enable-multibyte-characters
694 (or file-name-coding-system
695 default-file-name-coding-system
)))
696 (client (server-client proc
))
698 nowait
; t if emacsclient does not want to wait for us.
699 frame
; The frame that was opened for the client (if any).
700 display
; Open the frame on this display.
701 dontkill
; t if the client should not be killed.
707 ;; Remove this line from STRING.
708 (setq string
(substring string
(match-end 0)))
709 (while (string-match " *[^ ]* " request
)
710 (let ((arg (substring request
(match-beginning 0) (1- (match-end 0)))))
711 (setq request
(substring request
(match-end 0)))
713 ;; -version CLIENT-VERSION:
714 ;; Check version numbers, signal an error if there is a mismatch.
715 ((and (equal "-version" arg
)
716 (string-match "\\([0-9.]+\\) " request
))
717 (let* ((client-version (match-string 1 request
))
718 (truncated-emacs-version
719 (substring emacs-version
0 (length client-version
))))
720 (setq request
(substring request
(match-end 0)))
721 (if (equal client-version truncated-emacs-version
)
723 (server-send-string proc
"-good-version \n")
724 (server-client-set client
'version client-version
))
725 (error (concat "Version mismatch: Emacs is "
726 truncated-emacs-version
727 ", emacsclient is " client-version
)))))
729 ;; -nowait: Emacsclient won't wait for a result.
730 ((equal "-nowait" arg
) (setq nowait t
))
732 ;; -current-frame: Don't create frames.
733 ((equal "-current-frame" arg
) (setq current-frame t
))
736 ;; Open X frames on the given display instead of the default.
737 ((and (equal "-display" arg
) (string-match "\\([^ ]*\\) " request
))
738 (setq display
(match-string 1 request
)
739 request
(substring request
(match-end 0))))
741 ;; -window-system: Open a new X frame.
742 ((equal "-window-system" arg
)
743 (unless (server-client-get client
'version
)
744 (error "Protocol error; make sure to use the correct version of emacsclient"))
745 (unless current-frame
746 (if (fboundp 'x-create-frame
)
747 (let ((params (if nowait
748 ;; Flag frame as client-created, but use a dummy client.
749 ;; This will prevent the frame from being deleted when
750 ;; emacsclient quits while also preventing
751 ;; `server-save-buffers-kill-terminal' from unexpectedly
752 ;; killing emacs on that frame.
753 (list (cons 'client
'nowait
) (cons 'environment env
))
754 (list (cons 'client proc
) (cons 'environment env
)))))
755 (setq frame
(make-frame-on-display
757 (frame-parameter nil
'display
)
759 (error "Please specify display"))
761 (server-log (format "%s created" frame
) proc
)
762 ;; XXX We need to ensure the parameters are
763 ;; really set because Emacs forgets unhandled
764 ;; initialization parameters for X frames at
766 (modify-frame-parameters frame params
)
767 (set-frame-parameter frame
'display-environment-variable
768 (server-getenv-from env
"DISPLAY"))
770 (server-client-set client
'frame frame
)
771 (server-client-set client
'terminal
(frame-terminal frame
))
773 ;; Display *scratch* by default.
774 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
777 ;; This emacs does not support X.
778 (server-log "Window system unsupported" proc
)
779 (server-send-string proc
"-window-system-unsupported \n")
782 ;; -resume: Resume a suspended tty frame.
783 ((equal "-resume" arg
)
784 (let ((terminal (server-client-get client
'terminal
)))
786 (when (eq (terminal-live-p terminal
) t
)
787 (resume-tty terminal
))))
789 ;; -suspend: Suspend the client's frame. (In case we
790 ;; get out of sync, and a C-z sends a SIGTSTP to
792 ((equal "-suspend" arg
)
793 (let ((terminal (server-client-get client
'terminal
)))
795 (when (eq (terminal-live-p terminal
) t
)
796 (suspend-tty terminal
))))
798 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
799 ;; (The given comment appears in the server log.)
800 ((and (equal "-ignore" arg
) (string-match "\\([^ ]*\\) " request
))
802 request
(substring request
(match-end 0))))
804 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
805 ((and (equal "-tty" arg
) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request
))
806 (let ((tty (server-unquote-arg (match-string 1 request
)))
807 (type (server-unquote-arg (match-string 2 request
))))
808 (setq request
(substring request
(match-end 0)))
809 (unless (server-client-get client
'version
)
810 (error "Protocol error; make sure you use the correct version of emacsclient"))
811 (unless current-frame
812 (server-with-environment env
813 '("LANG" "LC_CTYPE" "LC_ALL"
814 ;; For tgetent(3); list according to ncurses(3).
815 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
816 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
817 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
818 "TERMINFO_DIRS" "TERMPATH"
820 "COLORFGBG" "COLORTERM")
821 (setq frame
(make-frame-on-tty tty type
822 ;; Ignore nowait here; we always need to clean
823 ;; up opened ttys when the client dies.
825 (environment .
,env
)))))
827 (set-frame-parameter frame
'display-environment-variable
828 (server-getenv-from env
"DISPLAY"))
830 (server-client-set client
'frame frame
)
831 (server-client-set client
'tty
(terminal-name frame
))
832 (server-client-set client
'terminal
(frame-terminal frame
))
834 ;; Display *scratch* by default.
835 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
837 ;; Reply with our pid.
838 (server-send-string proc
(concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
841 ;; -position LINE: Go to the given line in the next file.
842 ((and (equal "-position" arg
) (string-match "\\(\\+[0-9]+\\) " request
))
843 (setq lineno
(string-to-number (substring (match-string 1 request
) 1))
844 request
(substring request
(match-end 0))))
846 ;; -position LINE:COLUMN: Set point to the given position in the next file.
847 ((and (equal "-position" arg
) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request
))
848 (setq lineno
(string-to-number (match-string 1 request
))
849 columnno
(string-to-number (match-string 2 request
))
850 request
(substring request
(match-end 0))))
852 ;; -file FILENAME: Load the given file.
853 ((and (equal "-file" arg
) (string-match "\\([^ ]+\\) " request
))
854 (let ((file (server-unquote-arg (match-string 1 request
))))
855 (setq request
(substring request
(match-end 0)))
857 (setq file
(decode-coding-string file coding-system
)))
858 (setq file
(command-line-normalize-file-name file
))
859 (push (list file lineno columnno
) files
)
860 (server-log (format "New file: %s (%d:%d)" file lineno columnno
) proc
))
864 ;; -eval EXPR: Evaluate a Lisp expression.
865 ((and (equal "-eval" arg
) (string-match "\\([^ ]+\\) " request
))
866 (let ((expr (server-unquote-arg (match-string 1 request
))))
867 (setq request
(substring request
(match-end 0)))
869 (setq expr
(decode-coding-string expr coding-system
)))
870 (let ((v (eval (car (read-from-string expr
)))))
871 (when (and (not frame
) v
)
873 (let ((standard-output (current-buffer)))
876 proc
(format "-print %s\n"
878 (buffer-substring-no-properties (point-min)
883 ;; -env NAME=VALUE: An environment variable.
884 ((and (equal "-env" arg
) (string-match "\\([^ ]+\\) " request
))
885 (let ((var (server-unquote-arg (match-string 1 request
))))
886 ;; XXX Variables should be encoded as in getenv/setenv.
887 (setq request
(substring request
(match-end 0)))
888 (setq env
(cons var env
))))
890 ;; -dir DIRNAME: The cwd of the emacsclient process.
891 ((and (equal "-dir" arg
) (string-match "\\([^ ]+\\) " request
))
892 (setq dir
(server-unquote-arg (match-string 1 request
)))
893 (setq request
(substring request
(match-end 0)))
895 (setq dir
(decode-coding-string dir coding-system
)))
896 (setq dir
(command-line-normalize-file-name dir
)))
899 (t (error "Unknown command: %s" arg
)))))
903 (run-hooks 'pre-command-hook
)
904 (setq buffers
(server-visit-files files client nowait
))
905 (run-hooks 'post-command-hook
))
907 ;; Delete the client if necessary.
910 ;; Client requested nowait; return immediately.
911 (server-log "Close nowait client" proc
)
912 (server-delete-client proc
))
913 ((and (not dontkill
) (null buffers
))
914 ;; This client is empty; get rid of it immediately.
915 (server-log "Close empty client" proc
)
916 (server-delete-client proc
)))
918 ((or isearch-mode
(minibufferp))
920 ((and frame
(null buffers
))
921 (message "%s" (substitute-command-keys
922 "When done with this frame, type \\[delete-frame]")))
923 ((not (null buffers
))
924 (server-switch-buffer (car buffers
))
925 (run-hooks 'server-switch-hook
)
927 (message "%s" (substitute-command-keys
928 "When done with a buffer, type \\[server-edit]"))))))))
930 ;; Save for later any partial line that remains.
931 (when (> (length string
) 0)
932 (process-put proc
'previous-string string
)))
934 (error (ignore-errors
936 proc
(concat "-error " (server-quote-arg (error-message-string err
))))
938 (server-log (error-message-string err
) proc
)
939 (delete-process proc
)))))
941 (defun server-goto-line-column (file-line-col)
942 "Move point to the position indicated in FILE-LINE-COL.
943 FILE-LINE-COL should be a three-element list as described in
944 `server-visit-files'."
945 (goto-line (nth 1 file-line-col
))
946 (let ((column-number (nth 2 file-line-col
)))
947 (if (> column-number
0)
948 (move-to-column (1- column-number
)))))
950 (defun server-visit-files (files client
&optional nowait
)
951 "Find FILES and return a list of buffers created.
952 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
953 CLIENT is the client that requested this operation.
954 NOWAIT non-nil means this client is not waiting for the results,
955 so don't mark these buffers specially, just visit them normally."
956 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
957 (let ((last-nonmenu-event t
) client-record
)
958 ;; Restore the current buffer afterward, but not using save-excursion,
959 ;; because we don't want to save point in this buffer
960 ;; if it happens to be one of those specified by the server.
963 ;; If there is an existing buffer modified or the file is
964 ;; modified, revert it. If there is an existing buffer with
965 ;; deleted file, offer to write it.
966 (let* ((minibuffer-auto-raise (or server-raise-frame
967 minibuffer-auto-raise
))
969 (obuf (get-file-buffer filen
)))
970 (add-to-history 'file-name-history filen
)
971 (if (and obuf
(set-buffer obuf
))
973 (cond ((file-exists-p filen
)
974 (when (not (verify-visited-file-modtime obuf
))
975 (revert-buffer t nil
)))
978 (concat "File no longer exists: " filen
979 ", write buffer to file? "))
980 (write-file filen
))))
981 (unless server-buffer-clients
982 (setq server-existing-buffer t
))
983 (server-goto-line-column file
))
984 (set-buffer (find-file-noselect filen
))
985 (server-goto-line-column file
)
986 (run-hooks 'server-visit-hook
)))
988 ;; When the buffer is killed, inform the clients.
989 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
990 (push (car client
) server-buffer-clients
))
991 (push (current-buffer) client-record
)))
995 (nconc (server-client-get client
'buffers
) client-record
)))
998 (defun server-buffer-done (buffer &optional for-killing
)
999 "Mark BUFFER as \"done\" for its client(s).
1000 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1001 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1002 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1004 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1005 (let ((next-buffer nil
)
1007 (dolist (client server-clients
)
1008 (let ((buffers (server-client-get client
'buffers
)))
1010 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1011 (when buffers
; Ignore bufferless clients.
1012 (setq buffers
(delq buffer buffers
))
1013 ;; Delete all dead buffers from CLIENT.
1016 (not (buffer-live-p b
))
1017 (setq buffers
(delq b buffers
))))
1018 (server-client-set client
'buffers buffers
)
1019 ;; If client now has no pending buffers,
1020 ;; tell it that it is done, and forget it entirely.
1022 (server-log "Close" client
)
1023 (server-delete-client client
)))))
1024 (when (and (bufferp buffer
) (buffer-name buffer
))
1025 ;; We may or may not kill this buffer;
1026 ;; if we do, do not call server-buffer-done recursively
1027 ;; from kill-buffer-hook.
1028 (let ((server-kill-buffer-running t
))
1029 (with-current-buffer buffer
1030 (setq server-buffer-clients nil
)
1031 (run-hooks 'server-done-hook
))
1032 ;; Notice whether server-done-hook killed the buffer.
1033 (if (null (buffer-name buffer
))
1035 ;; Don't bother killing or burying the buffer
1036 ;; when we are called from kill-buffer.
1038 (when (and (not killed
)
1039 server-kill-new-buffers
1040 (with-current-buffer buffer
1041 (not server-existing-buffer
)))
1043 (bury-buffer buffer
)
1044 (kill-buffer buffer
))
1046 (if (server-temp-file-p buffer
)
1048 (kill-buffer buffer
)
1050 (bury-buffer buffer
)))))))
1051 (list next-buffer killed
)))
1053 (defun server-temp-file-p (&optional buffer
)
1054 "Return non-nil if BUFFER contains a file considered temporary.
1055 These are files whose names suggest they are repeatedly
1056 reused to pass information to another program.
1058 The variable `server-temp-file-regexp' controls which filenames
1059 are considered temporary."
1060 (and (buffer-file-name buffer
)
1061 (string-match server-temp-file-regexp
(buffer-file-name buffer
))))
1063 (defun server-done ()
1064 "Offer to save current buffer, mark it as \"done\" for clients.
1065 This kills or buries the buffer, then returns a list
1066 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1067 as a suggestion for what to select next, or nil.
1068 KILLED is t if we killed BUFFER, which happens if it was created
1069 specifically for the clients and did not exist before their request for it."
1070 (when server-buffer-clients
1071 (if (server-temp-file-p)
1072 ;; For a temp file, save, and do make a non-numeric backup
1073 ;; (unless make-backup-files is nil).
1074 (let ((version-control nil
)
1075 (buffer-backed-up nil
))
1077 (when (and (buffer-modified-p)
1079 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1081 (server-buffer-done (current-buffer))))
1083 ;; Ask before killing a server buffer.
1084 ;; It was suggested to release its client instead,
1085 ;; but I think that is dangerous--the client would proceed
1086 ;; using whatever is on disk in that file. -- rms.
1087 (defun server-kill-buffer-query-function ()
1088 "Ask before killing a server buffer."
1089 (or (not server-buffer-clients
)
1091 (dolist (proc server-buffer-clients res
)
1092 (let ((client (server-client proc
)))
1093 (when (and client
(eq (process-status proc
) 'open
))
1095 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1096 (buffer-name (current-buffer))))))
1098 (defun server-kill-emacs-query-function ()
1099 "Ask before exiting Emacs it has live clients."
1100 (or (not server-clients
)
1102 (dolist (client server-clients live-client
)
1103 (when (memq t
(mapcar 'buffer-live-p
(server-client-get
1105 (setq live-client t
))))
1106 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1108 (defvar server-kill-buffer-running nil
1109 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1111 (defun server-kill-buffer ()
1112 "Remove the current buffer from its clients' buffer list.
1113 Designed to be added to `kill-buffer-hook'."
1114 ;; Prevent infinite recursion if user has made server-done-hook
1115 ;; call kill-buffer.
1116 (or server-kill-buffer-running
1117 (and server-buffer-clients
1118 (let ((server-kill-buffer-running t
))
1119 (when server-process
1120 (server-buffer-done (current-buffer) t
))))))
1122 (defun server-edit (&optional arg
)
1123 "Switch to next server editing buffer; say \"Done\" for current buffer.
1124 If a server buffer is current, it is marked \"done\" and optionally saved.
1125 The buffer is also killed if it did not exist before the clients asked for it.
1126 When all of a client's buffers are marked as \"done\", the client is notified.
1128 Temporary files such as MH <draft> files are always saved and backed up,
1129 no questions asked. (The variable `make-backup-files', if nil, still
1130 inhibits a backup; you can set it locally in a particular buffer to
1131 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1132 which filenames are considered temporary.
1134 If invoked with a prefix argument, or if there is no server process running,
1135 starts server process and that is all. Invoked by \\[server-edit]."
1139 (not server-process
)
1140 (memq (process-status server-process
) '(signal exit
)))
1142 (server-clients (apply 'server-switch-buffer
(server-done)))
1143 (t (message "No server editing buffers exist"))))
1145 (defun server-switch-buffer (&optional next-buffer killed-one
)
1146 "Switch to another buffer, preferably one that has a client.
1147 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1149 KILLED-ONE is t in a recursive call if we have already killed one
1150 temp-file server buffer. This means we should avoid the final
1151 \"switch to some other buffer\" since we've already effectively
1153 (if (null next-buffer
)
1155 (let ((rest server-clients
))
1156 (while (and rest
(not next-buffer
))
1157 (let ((client (car rest
)))
1158 ;; Only look at frameless clients.
1159 (when (not (server-client-get client
'frame
))
1160 (setq next-buffer
(car (server-client-get client
'buffers
))))
1161 (setq rest
(cdr rest
)))))
1162 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1163 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1164 ;; (switch-to-buffer (other-buffer))
1165 (message "No server buffers remain to edit")))
1166 (if (not (buffer-live-p next-buffer
))
1167 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1168 ;; and try the next surviving server buffer.
1169 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1170 ;; OK, we know next-buffer is live, let's display and select it.
1171 (if (functionp server-window
)
1172 (funcall server-window next-buffer
)
1173 (let ((win (get-buffer-window next-buffer
0)))
1174 (if (and win
(not server-window
))
1175 ;; The buffer is already displayed: just reuse the window.
1178 (set-buffer next-buffer
))
1179 ;; Otherwise, let's find an appropriate window.
1180 (cond ((window-live-p server-window
)
1181 (select-window server-window
))
1182 ((framep server-window
)
1183 (unless (frame-live-p server-window
)
1184 (setq server-window
(make-frame)))
1185 (select-window (frame-selected-window server-window
))))
1186 (when (window-minibuffer-p (selected-window))
1187 (select-window (next-window nil
'nomini
0)))
1188 ;; Move to a non-dedicated window, if we have one.
1189 (when (window-dedicated-p (selected-window))
1191 (get-window-with-predicate
1193 (and (not (window-dedicated-p w
))
1194 (equal (frame-terminal (window-frame w
))
1195 (frame-terminal (selected-frame)))))
1196 'nomini
'visible
(selected-window))))
1198 (switch-to-buffer next-buffer
)
1199 ;; After all the above, we might still have ended up with
1200 ;; a minibuffer/dedicated-window (if there's no other).
1201 (error (pop-to-buffer next-buffer
)))))))
1202 (when server-raise-frame
1203 (select-frame-set-input-focus (window-frame (selected-window))))))
1206 (defun server-save-buffers-kill-terminal (proc &optional arg
)
1207 "Offer to save each buffer, then kill PROC.
1209 With prefix arg, silently save all file-visiting buffers, then kill.
1211 If emacsclient was started with a list of filenames to edit, then
1212 only these files will be asked to be saved."
1213 (let ((buffers (server-client-get proc
'buffers
)))
1214 ;; If client is bufferless, emulate a normal Emacs session
1215 ;; exit and offer to save all buffers. Otherwise, offer to
1216 ;; save only the buffers belonging to the client.
1217 (save-some-buffers arg
1219 (lambda () (memq (current-buffer) buffers
))
1221 (server-delete-client proc
)))
1223 (define-key ctl-x-map
"#" 'server-edit
)
1225 (defun server-unload-hook ()
1226 "Unload the server library."
1228 (remove-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
1229 (remove-hook 'delete-frame-functions
'server-handle-delete-frame
)
1230 (remove-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
1231 (remove-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
1232 (remove-hook 'kill-buffer-hook
'server-kill-buffer
))
1234 (add-hook 'kill-emacs-hook
(lambda () (server-mode -
1))) ;Cleanup upon exit.
1235 (add-hook 'server-unload-hook
'server-unload-hook
)
1239 ;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1240 ;;; server.el ends here