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 a process.")
144 (defvar server-buffer-clients nil
145 "List of client processes requesting editing of current buffer.")
146 (make-variable-buffer-local 'server-buffer-clients
)
147 ;; Changing major modes should not erase this local.
148 (put 'server-buffer-clients
'permanent-local t
)
150 (defcustom server-window nil
151 "Specification of the window to use for selecting Emacs server buffers.
152 If nil, use the selected window.
153 If it is a function, it should take one argument (a buffer) and
154 display and select it. A common value is `pop-to-buffer'.
155 If it is a window, use that.
156 If it is a frame, use the frame's selected window.
158 It is not meaningful to set this to a specific frame or window with Custom.
159 Only programs can do so."
162 :type
'(choice (const :tag
"Use selected window"
163 :match
(lambda (widget value
)
164 (not (functionp value
)))
166 (function-item :tag
"Display in new frame" switch-to-buffer-other-frame
)
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 the Emacs server. If nil, kill only buffers as specified by
181 `server-temp-file-regexp'.
182 Please note that only buffers that still have a client are killed,
183 i.e. buffers visited with \"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-clients-with (property value
)
205 "Return a list of clients with PROPERTY set to VALUE."
207 (dolist (proc server-clients result
)
208 (when (equal value
(process-get proc property
))
209 (push proc result
)))))
211 (defun server-add-client (proc)
212 "Create a client for process PROC, if it doesn't already have one.
213 New clients have no properties."
214 (add-to-list 'server-clients proc
))
216 (defmacro server-with-environment
(env vars
&rest body
)
217 "Evaluate BODY with environment variables VARS set to those in ENV.
218 The environment variables are then restored to their previous values.
220 VARS should be a list of strings.
221 ENV should be in the same format as `process-environment'."
223 (let ((var (make-symbol "var"))
224 (value (make-symbol "value")))
225 `(let ((process-environment process-environment
))
227 (let ((,value
(getenv-internal ,var
,env
)))
228 (push (if (null ,value
)
230 (concat ,var
"=" ,value
))
231 process-environment
)))
234 (defun server-delete-client (proc &optional noframe
)
235 "Delete CLIENT, including its buffers, terminals and frames.
236 If NOFRAME is non-nil, let the frames live. (To be used from
237 `delete-frame-functions'.)"
238 (server-log (concat "server-delete-client" (if noframe
" noframe"))
240 ;; Force a new lookup of client (prevents infinite recursion).
241 (when (memq proc server-clients
)
242 (let ((buffers (process-get proc
'buffers
)))
244 ;; Kill the client's buffers.
245 (dolist (buf buffers
)
246 (when (buffer-live-p buf
)
247 (with-current-buffer buf
248 ;; Kill the buffer if necessary.
249 (when (and (equal server-buffer-clients
251 (or (and server-kill-new-buffers
252 (not server-existing-buffer
))
253 (server-temp-file-p))
254 (not (buffer-modified-p)))
257 (progn (setq server-buffer-clients nil
)
258 (kill-buffer (current-buffer))
261 ;; Restore clients if user pressed C-g in `kill-buffer'.
262 (setq server-buffer-clients
(list proc
)))))))))
264 ;; Delete the client's frames.
266 (dolist (frame (frame-list))
267 (when (and (frame-live-p frame
)
268 (equal proc
(frame-parameter frame
'client
)))
269 ;; Prevent `server-handle-delete-frame' from calling us
271 (set-frame-parameter frame
'client nil
)
272 (delete-frame frame
))))
274 (setq server-clients
(delq proc server-clients
))
276 ;; Delete the client's tty.
277 (let ((terminal (process-get proc
'terminal
)))
278 ;; Only delete the terminal if it is non-nil.
279 (when (and terminal
(eq (terminal-live-p terminal
) t
))
280 (delete-terminal terminal
)))
282 ;; Delete the client's process.
283 (if (eq (process-status proc
) 'open
)
284 (delete-process proc
))
286 (server-log "Deleted" proc
))))
288 (defun server-log (string &optional client
)
289 "If a *server* buffer exists, write STRING to it for logging purposes.
290 If CLIENT is non-nil, add a description of it to the logged
292 (when (get-buffer "*server*")
293 (with-current-buffer "*server*"
294 (goto-char (point-max))
295 (insert (current-time-string)
298 ((listp client
) (format " %s: " (car client
)))
299 (t (format " %s: " client
)))
301 (or (bolp) (newline)))))
303 (defun server-sentinel (proc msg
)
304 "The process sentinel for Emacs server connections."
305 ;; If this is a new client process, set the query-on-exit flag to nil
306 ;; for this process (it isn't inherited from the server process).
307 (when (and (eq (process-status proc
) 'open
)
308 (process-query-on-exit-flag proc
))
309 (set-process-query-on-exit-flag proc nil
))
310 ;; Delete the associated connection file, if applicable.
311 ;; This is actually problematic: the file may have been overwritten by
312 ;; another Emacs server in the mean time, so it's not ours any more.
313 ;; (and (process-contact proc :server)
314 ;; (eq (process-status proc) 'closed)
315 ;; (ignore-errors (delete-file (process-get proc :server-file))))
316 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
317 (server-delete-client proc
))
319 (defun server-select-display (display)
320 ;; If the current frame is on `display' we're all set.
321 (unless (equal (frame-parameter (selected-frame) 'display
) display
)
322 ;; Otherwise, look for an existing frame there and select it.
323 (dolist (frame (frame-list))
324 (when (equal (frame-parameter frame
'display
) display
)
325 (select-frame frame
)))
326 ;; If there's no frame on that display yet, create and select one.
327 (unless (equal (frame-parameter (selected-frame) 'display
) display
)
328 (let* ((buffer (generate-new-buffer " *server-dummy*"))
329 (frame (make-frame-on-display
331 ;; Make it display (and remember) some dummy buffer, so
332 ;; we can detect later if the frame is in use or not.
333 `((server-dummmy-buffer .
,buffer
)
334 ;; This frame may be deleted later (see
335 ;; server-unselect-display) so we want it to be as
336 ;; unobtrusive as possible.
337 (visibility . nil
)))))
339 (set-window-buffer (selected-window) buffer
)
342 (defun server-unselect-display (frame)
343 (when (frame-live-p frame
)
344 ;; If the temporary frame is in use (displays something real), make it
345 ;; visible. If not (which can happen if the user's customizations call
346 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
347 ;; the last real frame is deleted.
348 (if (and (eq (frame-first-window frame
)
349 (next-window (frame-first-window frame
) 'nomini
))
350 (eq (window-buffer (frame-first-window frame
))
351 (frame-parameter frame
'server-dummy-buffer
)))
352 ;; The temp frame still only shows one buffer, and that is the
353 ;; internal temp buffer.
355 (set-frame-parameter frame
'visibility t
))
356 (kill-buffer (frame-parameter frame
'server-dummy-buffer
))
357 (set-frame-parameter frame
'server-dummy-buffer nil
)))
359 (defun server-handle-delete-frame (frame)
360 "Delete the client connection when the emacsclient frame is deleted."
361 (let ((proc (frame-parameter frame
'client
)))
362 (when (and (frame-live-p frame
)
364 ;; See if this is the last frame for this client.
365 (>= 1 (let ((frame-num 0))
366 (dolist (f (frame-list))
367 (when (eq proc
(frame-parameter f
'client
))
368 (setq frame-num
(1+ frame-num
))))
370 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
371 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
373 (defun server-handle-suspend-tty (terminal)
374 "Notify the emacsclient process to suspend itself when its tty device is suspended."
375 (dolist (proc (server-clients-with 'terminal terminal
))
376 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
) proc
)
378 (server-send-string proc
"-suspend \n")
379 (file-error ;The pipe/socket was closed.
380 (ignore-errors (server-delete-client proc
))))))
382 (defun server-unquote-arg (arg)
383 "Remove &-quotation from ARG.
384 See `server-quote-arg' and `server-process-filter'."
385 (replace-regexp-in-string
394 (defun server-quote-arg (arg)
395 "In ARG, insert a & before each &, each space, each newline, and -.
396 Change spaces to underscores, too, so that the return value never
399 See `server-unquote-arg' and `server-process-filter'."
400 (replace-regexp-in-string
401 "[-&\n ]" (lambda (s)
409 (defun server-send-string (proc string
)
410 "A wrapper around `proc-send-string' for logging."
411 (server-log (concat "Sent " string
) proc
)
412 (process-send-string proc string
))
414 (defun server-ensure-safe-dir (dir)
415 "Make sure DIR is a directory with no race-condition issues.
416 Creates the directory if necessary and makes sure:
417 - there's no symlink involved
419 - it's not readable/writable by anybody else."
420 (setq dir
(directory-file-name dir
))
421 (let ((attrs (file-attributes dir
)))
423 (letf (((default-file-modes) ?
\700)) (make-directory dir t
))
424 (setq attrs
(file-attributes dir
)))
425 ;; Check that it's safe for use.
426 (unless (and (eq t
(car attrs
)) (eql (nth 2 attrs
) (user-uid))
427 (or (eq system-type
'windows-nt
)
428 (zerop (logand ?
\077 (file-modes dir
)))))
429 (error "The directory %s is unsafe" dir
))))
432 (defun server-start (&optional leave-dead
)
433 "Allow this Emacs process to be a server for client processes.
434 This starts a server communications subprocess through which
435 client \"editors\" can send your editing commands to this Emacs
436 job. To use the server, set up the program `emacsclient' in the
437 Emacs distribution as your standard \"editor\".
439 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
440 kill any existing server communications subprocess."
445 "The current server still has clients; delete them? "))
446 ;; It is safe to get the user id now.
447 (setq server-socket-dir
(or server-socket-dir
448 (format "/tmp/emacs%d" (user-uid))))
451 (ignore-errors (delete-process server-process
)))
452 ;; Delete the socket files made by previous server invocations.
454 (delete-file (expand-file-name server-name server-socket-dir
))
456 ;; If this Emacs already had a server, clear out associated status.
457 (while server-clients
458 (server-delete-client (car server-clients
)))
459 ;; Now any previous server is properly stopped.
462 (server-log (message "Server stopped"))
463 (setq server-process nil
))
464 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir
))
465 (server-file (expand-file-name server-name server-dir
)))
466 ;; Make sure there is a safe directory in which to place the socket.
467 (server-ensure-safe-dir server-dir
)
468 ;; Remove any leftover socket or authentication file.
469 (ignore-errors (delete-file server-file
))
471 (server-log (message "Restarting server")))
472 (letf (((default-file-modes) ?
\700))
473 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
474 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
475 (add-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
476 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
478 (apply #'make-network-process
482 :sentinel
'server-sentinel
483 :filter
'server-process-filter
484 ;; We must receive file names without being decoded.
485 ;; Those are decoded by server-process-filter according
486 ;; to file-name-coding-system.
488 ;; The rest of the args depends on the kind of socket used.
492 :host
(or server-host
'local
)
493 :plist
'(:authenticated nil
))
496 :plist
'(:authenticated t
)))))
497 (unless server-process
(error "Could not start server process"))
501 ;; The auth key is a 64-byte string of random chars in the
504 collect
(+ 33 (random 94)) into auth
505 finally return
(concat auth
))))
506 (process-put server-process
:auth-key auth-key
)
507 (with-temp-file server-file
508 (set-buffer-multibyte nil
)
509 (setq buffer-file-coding-system
'no-conversion
)
510 (insert (format-network-address
511 (process-contact server-process
:local
))
512 " " (int-to-string (emacs-pid))
513 "\n" auth-key
)))))))))
515 (defun server-running-p (&optional name
)
516 "Test whether server NAME is running."
518 (list (if current-prefix-arg
519 (read-string "Server name: " nil nil server-name
))))
520 (unless name
(setq name server-name
))
524 (make-network-process
525 :name
"server-client-test" :family
'local
:server nil
:noquery t
526 :service
(expand-file-name name server-socket-dir
)))
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-eval-and-print (expr proc
)
544 "Eval EXPR and send the result back to client PROC."
545 (let ((v (eval (car (read-from-string expr
)))))
548 (let ((standard-output (current-buffer)))
550 (let ((text (buffer-substring-no-properties
551 (point-min) (point-max))))
553 proc
(format "-print %s\n"
554 (server-quote-arg text
)))))))))
556 (defun server-create-tty-frame (tty type proc
)
558 (server-with-environment (process-get proc
'env
)
559 '("LANG" "LC_CTYPE" "LC_ALL"
560 ;; For tgetent(3); list according to ncurses(3).
561 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
562 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
563 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
564 "TERMINFO_DIRS" "TERMPATH"
566 "COLORFGBG" "COLORTERM")
567 (make-frame-on-tty tty type
568 ;; Ignore nowait here; we always need to
569 ;; clean up opened ttys when the client dies.
571 (environment .
,(process-get proc
'env
)))))))
573 ;; ttys don't use the `display' parameter, but callproc.c does to set
574 ;; the DISPLAY environment on subprocesses.
575 (set-frame-parameter frame
'display
576 (getenv-internal "DISPLAY" (process-get proc
'env
)))
578 (process-put proc
'frame frame
)
579 (process-put proc
'terminal
(frame-terminal frame
))
581 ;; Display *scratch* by default.
582 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
584 ;; Reply with our pid.
585 (server-send-string proc
(concat "-emacs-pid "
586 (number-to-string (emacs-pid)) "\n"))
589 (defun server-create-window-system-frame (display nowait proc
)
590 (if (not (fboundp 'make-frame-on-display
))
592 ;; This emacs does not support X.
593 (server-log "Window system unsupported" proc
)
594 (server-send-string proc
"-window-system-unsupported \n")
596 ;; Flag frame as client-created, but use a dummy client.
597 ;; This will prevent the frame from being deleted when
598 ;; emacsclient quits while also preventing
599 ;; `server-save-buffers-kill-terminal' from unexpectedly
600 ;; killing emacs on that frame.
601 (let* ((params `((client .
,(if nowait
'nowait proc
))
602 (environment .
,(process-get proc
'env
))))
603 (frame (make-frame-on-display
605 (frame-parameter nil
'display
)
607 (error "Please specify display"))
609 (server-log (format "%s created" frame
) proc
)
610 ;; XXX We need to ensure the parameters are
611 ;; really set because Emacs forgets unhandled
612 ;; initialization parameters for X frames at
614 (modify-frame-parameters frame params
)
616 (process-put proc
'frame frame
)
617 (process-put proc
'terminal
(frame-terminal frame
))
619 ;; Display *scratch* by default.
620 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
624 (defun server-goto-toplevel (proc)
626 ;; If we're running isearch, we must abort it to allow Emacs to
627 ;; display the buffer and switch to it.
628 (dolist (buffer (buffer-list))
629 (with-current-buffer buffer
630 (when (bound-and-true-p isearch-mode
)
632 ;; Signaled by isearch-cancel.
633 (quit (message nil
)))
634 (when (> (recursion-depth) 0)
635 ;; We're inside a minibuffer already, so if the emacs-client is trying
636 ;; to open a frame on a new display, we might end up with an unusable
637 ;; frame because input from that display will be blocked (until exiting
638 ;; the minibuffer). Better exit this minibuffer right away.
639 ;; Similarly with recursive-edits such as the splash screen.
640 (run-with-timer 0 nil
(lexical-let ((proc proc
))
641 (lambda () (server-execute-continuation proc
))))
644 ;; We use various special properties on process objects:
645 ;; - `env' stores the info about the environment of the emacsclient process.
646 ;; - `continuation' is a no-arg function that we need to execute. It contains
647 ;; commands we wanted to execute in some earlier invocation of the process
648 ;; filter but that we somehow were unable to process at that time
649 ;; (e.g. because we first need to throw to the toplevel).
651 (defun server-execute-continuation (proc)
652 (let ((continuation (process-get proc
'continuation
)))
653 (process-put proc
'continuation nil
)
654 (if continuation
(ignore-errors (funcall continuation
)))))
656 (defun* server-process-filter
(proc string
)
657 "Process a request from the server to edit some files.
658 PROC is the server process. STRING consists of a sequence of
659 commands prefixed by a dash. Some commands have arguments; these
660 are &-quoted and need to be decoded by `server-unquote-arg'. The
661 filter parses and executes these commands.
663 To illustrate the protocol, here is an example command that
664 emacsclient sends to create a new X frame (note that the whole
665 sequence is sent on a single line):
667 -env HOME /home/lorentey
669 ... lots of other -env commands
673 The following commands are accepted by the server:
676 Authenticate the client using the secret authentication string
680 An environment variable on the client side.
683 The current working directory of the client process.
686 Forbid the creation of new frames.
689 Request that the next frame created should not be
690 associated with this client.
693 Set the display name to open X frames on.
695 `-position LINE[:COLUMN]'
696 Go to the given line and column number
697 in the next file opened.
700 Load the given file in the current frame.
703 Evaluate EXPR as a Lisp expression and return the
704 result in -print commands.
709 `-tty DEVICENAME TYPE'
710 Open a new tty frame at the client.
713 Suspend this tty frame. The client sends this string in
714 response to SIGTSTP and SIGTTOU. The server must cease all I/O
715 on this tty until it gets a -resume command.
718 Resume this tty frame. The client sends this string when it
719 gets the SIGCONT signal and it is the foreground process on its
723 Do nothing, but put the comment in the server
724 log. Useful for debugging.
727 The following commands are accepted by the client:
730 Describes the process id of the Emacs process;
731 used to forward window change signals to it.
733 `-window-system-unsupported'
734 Signals that the server does not
735 support creating X frames; the client must try again with a tty
739 Print STRING on stdout. Used to send values
743 Signal an error (but continue processing).
746 Suspend this terminal, i.e., stop the client process. Sent
747 when the user presses C-z."
748 (server-log (concat "Received " string
) proc
)
749 ;; First things first: let's check the authentication
750 (unless (process-get proc
:authenticated
)
751 (if (and (string-match "-auth \\(.*?\\)\n" string
)
752 (equal (match-string 1 string
) (process-get proc
:auth-key
)))
754 (setq string
(substring string
(match-end 0)))
755 (process-put proc
:authenticated t
)
756 (server-log "Authentication successful" proc
))
757 (server-log "Authentication failed" proc
)
759 proc
(concat "-error " (server-quote-arg "Authentication failed")))
760 (delete-process proc
)
761 ;; We return immediately
762 (return-from server-process-filter
)))
763 (let ((prev (process-get proc
'previous-string
)))
765 (setq string
(concat prev string
))
766 (process-put proc
'previous-string nil
)))
769 (server-add-client proc
)
770 (if (not (string-match "\n" string
))
771 ;; Save for later any partial line that remains.
772 (when (> (length string
) 0)
773 (process-put proc
'previous-string string
))
775 ;; In earlier versions of server.el (where we used an `emacsserver'
776 ;; process), there could be multiple lines. Nowadays this is not
777 ;; supported any more.
778 (assert (eq (match-end 0) (length string
)))
779 (let ((request (substring string
0 (match-beginning 0)))
780 (coding-system (and default-enable-multibyte-characters
781 (or file-name-coding-system
782 default-file-name-coding-system
)))
783 nowait
; t if emacsclient does not want to wait for us.
784 frame
; The frame that was opened for the client (if any).
785 display
; Open the frame on this display.
786 dontkill
; t if the client should not be killed.
789 (tty-name nil
) ;nil, `window-system', or the tty name.
794 ;; Remove this line from STRING.
795 (setq string
(substring string
(match-end 0)))
796 (while (string-match " *[^ ]* " request
)
797 (let ((arg (substring request
(match-beginning 0)
798 (1- (match-end 0)))))
799 (setq request
(substring request
(match-end 0)))
801 ;; -version CLIENT-VERSION: obsolete at birth.
802 ((and (equal "-version" arg
) (string-match "[^ ]+ " request
))
803 (setq request
(substring request
(match-end 0))))
805 ;; -nowait: Emacsclient won't wait for a result.
806 ((equal "-nowait" arg
) (setq nowait t
))
808 ;; -current-frame: Don't create frames.
809 ((equal "-current-frame" arg
) (setq tty-name nil
))
812 ;; Open X frames on the given display instead of the default.
813 ((and (equal "-display" arg
)
814 (string-match "\\([^ ]*\\) " request
))
815 (setq display
(match-string 1 request
)
816 request
(substring request
(match-end 0))))
818 ;; -window-system: Open a new X frame.
819 ((equal "-window-system" arg
)
821 (setq tty-name
'window-system
))
823 ;; -resume: Resume a suspended tty frame.
824 ((equal "-resume" arg
)
825 (lexical-let ((terminal (process-get proc
'terminal
)))
828 (when (eq (terminal-live-p terminal
) t
)
829 (resume-tty terminal
)))
832 ;; -suspend: Suspend the client's frame. (In case we
833 ;; get out of sync, and a C-z sends a SIGTSTP to
835 ((equal "-suspend" arg
)
836 (lexical-let ((terminal (process-get proc
'terminal
)))
839 (when (eq (terminal-live-p terminal
) t
)
840 (suspend-tty terminal
)))
843 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
844 ;; (The given comment appears in the server log.)
845 ((and (equal "-ignore" arg
) (string-match "[^ ]* " request
))
847 request
(substring request
(match-end 0))))
849 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
850 ((and (equal "-tty" arg
)
851 (string-match "\\([^ ]*\\) \\([^ ]*\\) " request
))
852 (setq tty-name
(match-string 1 request
))
853 (setq tty-type
(match-string 2 request
))
855 (setq request
(substring request
(match-end 0))))
857 ;; -position LINE[:COLUMN]: Set point to the given
858 ;; position in the next file.
859 ((and (equal "-position" arg
)
860 (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)? "
862 (setq lineno
(string-to-number (match-string 1 request
))
863 columnno
(if (null (match-end 2)) 0
864 (string-to-number (match-string 2 request
)))
865 request
(substring request
(match-end 0))))
867 ;; -file FILENAME: Load the given file.
868 ((and (equal "-file" arg
)
869 (string-match "\\([^ ]+\\) " request
))
870 (let ((file (server-unquote-arg (match-string 1 request
))))
871 (setq request
(substring request
(match-end 0)))
873 (setq file
(decode-coding-string file coding-system
)))
874 (setq file
(command-line-normalize-file-name file
))
875 (push (list file lineno columnno
) files
)
876 (server-log (format "New file: %s (%d:%d)"
877 file lineno columnno
) proc
))
881 ;; -eval EXPR: Evaluate a Lisp expression.
882 ((and (equal "-eval" arg
)
883 (string-match "\\([^ ]+\\) " request
))
884 (lexical-let ((expr (server-unquote-arg
885 (match-string 1 request
))))
886 (setq request
(substring request
(match-end 0)))
888 (setq expr
(decode-coding-string expr coding-system
)))
889 (push (lambda () (server-eval-and-print expr proc
))
894 ;; -env NAME=VALUE: An environment variable.
895 ((and (equal "-env" arg
) (string-match "\\([^ ]+\\) " request
))
896 (let ((var (server-unquote-arg (match-string 1 request
))))
897 ;; XXX Variables should be encoded as in getenv/setenv.
898 (setq request
(substring request
(match-end 0)))
899 (process-put proc
'env
900 (cons var
(process-get proc
'env
)))))
902 ;; -dir DIRNAME: The cwd of the emacsclient process.
903 ((and (equal "-dir" arg
) (string-match "\\([^ ]+\\) " request
))
904 (setq dir
(server-unquote-arg (match-string 1 request
)))
905 (setq request
(substring request
(match-end 0)))
907 (setq dir
(decode-coding-string dir coding-system
)))
908 (setq dir
(command-line-normalize-file-name dir
)))
911 (t (error "Unknown command: %s" arg
)))))
915 ((nil) (if display
(server-select-display display
)))
917 (server-create-window-system-frame display nowait proc
))
918 (t (server-create-tty-frame tty-name tty-type proc
))))
920 (process-put proc
'continuation
921 (lexical-let ((proc proc
)
929 (server-execute proc files nowait commands
930 dontkill frame tty-name
))))
932 (when (or frame files
)
933 (server-goto-toplevel proc
))
935 (server-execute-continuation proc
))))
937 (error (server-return-error proc err
))))
939 (defun server-execute (proc files nowait commands dontkill frame tty-name
)
943 (run-hooks 'pre-command-hook
)
944 (prog1 (server-visit-files files proc nowait
)
945 (run-hooks 'post-command-hook
)))))
947 (mapc 'funcall
(nreverse commands
))
949 ;; Delete the client if necessary.
952 ;; Client requested nowait; return immediately.
953 (server-log "Close nowait client" proc
)
954 (server-delete-client proc
))
955 ((and (not dontkill
) (null buffers
))
956 ;; This client is empty; get rid of it immediately.
957 (server-log "Close empty client" proc
)
958 (server-delete-client proc
)))
960 ((or isearch-mode
(minibufferp))
962 ((and frame
(null buffers
))
963 (message "%s" (substitute-command-keys
964 "When done with this frame, type \\[delete-frame]")))
965 ((not (null buffers
))
966 (server-switch-buffer (car buffers
))
967 (run-hooks 'server-switch-hook
)
969 (message "%s" (substitute-command-keys
970 "When done with a buffer, type \\[server-edit]")))))
971 (when (and frame
(null tty-name
))
972 (server-unselect-display frame
)))
973 (error (server-return-error proc err
))))
975 (defun server-return-error (proc err
)
978 proc
(concat "-error " (server-quote-arg
979 (error-message-string err
))))
980 (server-log (error-message-string err
) proc
)
981 (delete-process proc
)))
983 (defun server-goto-line-column (file-line-col)
984 "Move point to the position indicated in FILE-LINE-COL.
985 FILE-LINE-COL should be a three-element list as described in
986 `server-visit-files'."
987 (goto-line (nth 1 file-line-col
))
988 (let ((column-number (nth 2 file-line-col
)))
989 (if (> column-number
0)
990 (move-to-column (1- column-number
)))))
992 (defun server-visit-files (files proc
&optional nowait
)
993 "Find FILES and return a list of buffers created.
994 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
995 PROC is the client that requested this operation.
996 NOWAIT non-nil means this client is not waiting for the results,
997 so don't mark these buffers specially, just visit them normally."
998 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
999 (let ((last-nonmenu-event t
) client-record
)
1000 ;; Restore the current buffer afterward, but not using save-excursion,
1001 ;; because we don't want to save point in this buffer
1002 ;; if it happens to be one of those specified by the server.
1003 (save-current-buffer
1004 (dolist (file files
)
1005 ;; If there is an existing buffer modified or the file is
1006 ;; modified, revert it. If there is an existing buffer with
1007 ;; deleted file, offer to write it.
1008 (let* ((minibuffer-auto-raise (or server-raise-frame
1009 minibuffer-auto-raise
))
1011 (obuf (get-file-buffer filen
)))
1012 (add-to-history 'file-name-history filen
)
1013 (if (and obuf
(set-buffer obuf
))
1015 (cond ((file-exists-p filen
)
1016 (when (not (verify-visited-file-modtime obuf
))
1017 (revert-buffer t nil
)))
1020 (concat "File no longer exists: " filen
1021 ", write buffer to file? "))
1022 (write-file filen
))))
1023 (unless server-buffer-clients
1024 (setq server-existing-buffer t
))
1025 (server-goto-line-column file
))
1026 (set-buffer (find-file-noselect filen
))
1027 (server-goto-line-column file
)
1028 (run-hooks 'server-visit-hook
)))
1030 ;; When the buffer is killed, inform the clients.
1031 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
1032 (push proc server-buffer-clients
))
1033 (push (current-buffer) client-record
)))
1035 (process-put proc
'buffers
1036 (nconc (process-get proc
'buffers
) client-record
)))
1039 (defun server-buffer-done (buffer &optional for-killing
)
1040 "Mark BUFFER as \"done\" for its client(s).
1041 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1042 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1043 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1045 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1046 (let ((next-buffer nil
)
1048 (dolist (proc server-clients
)
1049 (let ((buffers (process-get proc
'buffers
)))
1051 (setq next-buffer
(nth 1 (memq buffer buffers
))))
1052 (when buffers
; Ignore bufferless clients.
1053 (setq buffers
(delq buffer buffers
))
1054 ;; Delete all dead buffers from PROC.
1057 (not (buffer-live-p b
))
1058 (setq buffers
(delq b buffers
))))
1059 (process-put proc
'buffers buffers
)
1060 ;; If client now has no pending buffers,
1061 ;; tell it that it is done, and forget it entirely.
1063 (server-log "Close" proc
)
1064 (server-delete-client proc
)))))
1065 (when (and (bufferp buffer
) (buffer-name buffer
))
1066 ;; We may or may not kill this buffer;
1067 ;; if we do, do not call server-buffer-done recursively
1068 ;; from kill-buffer-hook.
1069 (let ((server-kill-buffer-running t
))
1070 (with-current-buffer buffer
1071 (setq server-buffer-clients nil
)
1072 (run-hooks 'server-done-hook
))
1073 ;; Notice whether server-done-hook killed the buffer.
1074 (if (null (buffer-name buffer
))
1076 ;; Don't bother killing or burying the buffer
1077 ;; when we are called from kill-buffer.
1079 (when (and (not killed
)
1080 server-kill-new-buffers
1081 (with-current-buffer buffer
1082 (not server-existing-buffer
)))
1084 (bury-buffer buffer
)
1085 (kill-buffer buffer
))
1087 (if (server-temp-file-p buffer
)
1089 (kill-buffer buffer
)
1091 (bury-buffer buffer
)))))))
1092 (list next-buffer killed
)))
1094 (defun server-temp-file-p (&optional buffer
)
1095 "Return non-nil if BUFFER contains a file considered temporary.
1096 These are files whose names suggest they are repeatedly
1097 reused to pass information to another program.
1099 The variable `server-temp-file-regexp' controls which filenames
1100 are considered temporary."
1101 (and (buffer-file-name buffer
)
1102 (string-match server-temp-file-regexp
(buffer-file-name buffer
))))
1104 (defun server-done ()
1105 "Offer to save current buffer, mark it as \"done\" for clients.
1106 This kills or buries the buffer, then returns a list
1107 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1108 as a suggestion for what to select next, or nil.
1109 KILLED is t if we killed BUFFER, which happens if it was created
1110 specifically for the clients and did not exist before their request for it."
1111 (when server-buffer-clients
1112 (if (server-temp-file-p)
1113 ;; For a temp file, save, and do make a non-numeric backup
1114 ;; (unless make-backup-files is nil).
1115 (let ((version-control nil
)
1116 (buffer-backed-up nil
))
1118 (when (and (buffer-modified-p)
1120 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
1122 (server-buffer-done (current-buffer))))
1124 ;; Ask before killing a server buffer.
1125 ;; It was suggested to release its client instead,
1126 ;; but I think that is dangerous--the client would proceed
1127 ;; using whatever is on disk in that file. -- rms.
1128 (defun server-kill-buffer-query-function ()
1129 "Ask before killing a server buffer."
1130 (or (not server-buffer-clients
)
1132 (dolist (proc server-buffer-clients res
)
1133 (when (and (memq proc server-clients
)
1134 (eq (process-status proc
) 'open
))
1136 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1137 (buffer-name (current-buffer))))))
1139 (defun server-kill-emacs-query-function ()
1140 "Ask before exiting Emacs it has live clients."
1141 (or (not server-clients
)
1143 (dolist (proc server-clients live-client
)
1144 (when (memq t
(mapcar 'buffer-live-p
(process-get
1146 (setq live-client t
))))
1147 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1149 (defvar server-kill-buffer-running nil
1150 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1152 (defun server-kill-buffer ()
1153 "Remove the current buffer from its clients' buffer list.
1154 Designed to be added to `kill-buffer-hook'."
1155 ;; Prevent infinite recursion if user has made server-done-hook
1156 ;; call kill-buffer.
1157 (or server-kill-buffer-running
1158 (and server-buffer-clients
1159 (let ((server-kill-buffer-running t
))
1160 (when server-process
1161 (server-buffer-done (current-buffer) t
))))))
1163 (defun server-edit (&optional arg
)
1164 "Switch to next server editing buffer; say \"Done\" for current buffer.
1165 If a server buffer is current, it is marked \"done\" and optionally saved.
1166 The buffer is also killed if it did not exist before the clients asked for it.
1167 When all of a client's buffers are marked as \"done\", the client is notified.
1169 Temporary files such as MH <draft> files are always saved and backed up,
1170 no questions asked. (The variable `make-backup-files', if nil, still
1171 inhibits a backup; you can set it locally in a particular buffer to
1172 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1173 which filenames are considered temporary.
1175 If invoked with a prefix argument, or if there is no server process running,
1176 starts server process and that is all. Invoked by \\[server-edit]."
1180 (not server-process
)
1181 (memq (process-status server-process
) '(signal exit
)))
1183 (server-clients (apply 'server-switch-buffer
(server-done)))
1184 (t (message "No server editing buffers exist"))))
1186 (defun server-switch-buffer (&optional next-buffer killed-one
)
1187 "Switch to another buffer, preferably one that has a client.
1188 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1190 KILLED-ONE is t in a recursive call if we have already killed one
1191 temp-file server buffer. This means we should avoid the final
1192 \"switch to some other buffer\" since we've already effectively
1194 (if (null next-buffer
)
1196 (let ((rest server-clients
))
1197 (while (and rest
(not next-buffer
))
1198 (let ((proc (car rest
)))
1199 ;; Only look at frameless clients.
1200 (when (not (process-get proc
'frame
))
1201 (setq next-buffer
(car (process-get proc
'buffers
))))
1202 (setq rest
(cdr rest
)))))
1203 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1204 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1205 ;; (switch-to-buffer (other-buffer))
1206 (message "No server buffers remain to edit")))
1207 (if (not (buffer-live-p next-buffer
))
1208 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1209 ;; and try the next surviving server buffer.
1210 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1211 ;; OK, we know next-buffer is live, let's display and select it.
1212 (if (functionp server-window
)
1213 (funcall server-window next-buffer
)
1214 (let ((win (get-buffer-window next-buffer
0)))
1215 (if (and win
(not server-window
))
1216 ;; The buffer is already displayed: just reuse the window.
1219 (set-buffer next-buffer
))
1220 ;; Otherwise, let's find an appropriate window.
1221 (cond ((window-live-p server-window
)
1222 (select-window server-window
))
1223 ((framep server-window
)
1224 (unless (frame-live-p server-window
)
1225 (setq server-window
(make-frame)))
1226 (select-window (frame-selected-window server-window
))))
1227 (when (window-minibuffer-p (selected-window))
1228 (select-window (next-window nil
'nomini
0)))
1229 ;; Move to a non-dedicated window, if we have one.
1230 (when (window-dedicated-p (selected-window))
1232 (get-window-with-predicate
1234 (and (not (window-dedicated-p w
))
1235 (equal (frame-terminal (window-frame w
))
1236 (frame-terminal (selected-frame)))))
1237 'nomini
'visible
(selected-window))))
1239 (switch-to-buffer next-buffer
)
1240 ;; After all the above, we might still have ended up with
1241 ;; a minibuffer/dedicated-window (if there's no other).
1242 (error (pop-to-buffer next-buffer
)))))))
1243 (when server-raise-frame
1244 (select-frame-set-input-focus (window-frame (selected-window))))))
1247 (defun server-save-buffers-kill-terminal (proc &optional arg
)
1248 "Offer to save each buffer, then kill PROC.
1250 With prefix arg, silently save all file-visiting buffers, then kill.
1252 If emacsclient was started with a list of filenames to edit, then
1253 only these files will be asked to be saved."
1254 (let ((buffers (process-get proc
'buffers
)))
1255 ;; If client is bufferless, emulate a normal Emacs session
1256 ;; exit and offer to save all buffers. Otherwise, offer to
1257 ;; save only the buffers belonging to the client.
1258 (save-some-buffers arg
1260 (lambda () (memq (current-buffer) buffers
))
1262 (server-delete-client proc
)))
1264 (define-key ctl-x-map
"#" 'server-edit
)
1266 (defun server-unload-hook ()
1267 "Unload the server library."
1269 (remove-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
1270 (remove-hook 'delete-frame-functions
'server-handle-delete-frame
)
1271 (remove-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
1272 (remove-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
1273 (remove-hook 'kill-buffer-hook
'server-kill-buffer
))
1275 (add-hook 'kill-emacs-hook
(lambda () (server-mode -
1))) ;Cleanup upon exit.
1276 (add-hook 'server-unload-hook
'server-unload-hook
)
1280 ;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1281 ;;; server.el ends here