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 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-visit-hook nil
87 "*Hook run when visiting a file for the Emacs server."
91 (defcustom server-switch-hook nil
92 "*Hook run when switching to a buffer for the Emacs server."
96 (defcustom server-done-hook nil
97 "*Hook run when done editing a buffer for the Emacs server."
101 (defvar server-process nil
102 "The current server process.")
104 (defvar server-clients nil
105 "List of current server clients.
106 Each element is (PROC PROPERTIES...) where PROC is a process object,
107 and PROPERTIES is an association list of client properties.")
109 (defvar server-buffer-clients nil
110 "List of client processes requesting editing of current buffer.")
111 (make-variable-buffer-local 'server-buffer-clients
)
112 ;; Changing major modes should not erase this local.
113 (put 'server-buffer-clients
'permanent-local t
)
115 (defcustom server-window nil
116 "*Specification of the window to use for selecting Emacs server buffers.
117 If nil, use the selected window.
118 If it is a function, it should take one argument (a buffer) and
119 display and select it. A common value is `pop-to-buffer'.
120 If it is a window, use that.
121 If it is a frame, use the frame's selected window.
123 It is not meaningful to set this to a specific frame or window with Custom.
124 Only programs can do so."
127 :type
'(choice (const :tag
"Use selected window"
128 :match
(lambda (widget value
)
129 (not (functionp value
)))
131 (function-item :tag
"Use pop-to-buffer" pop-to-buffer
)
132 (function :tag
"Other function")))
134 (defcustom server-temp-file-regexp
"^/tmp/Re\\|/draft$"
135 "*Regexp matching names of temporary files.
136 These are deleted and reused after each edit by the programs that
137 invoke the Emacs server."
141 (defcustom server-kill-new-buffers t
142 "*Whether to kill buffers when done with them.
143 If non-nil, kill a buffer unless it already existed before editing
144 it with Emacs server. If nil, kill only buffers as specified by
145 `server-temp-file-regexp'.
146 Please note that only buffers are killed that still have a client,
147 i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
153 (or (assq 'server-buffer-clients minor-mode-alist
)
154 (setq minor-mode-alist
(cons '(server-buffer-clients " Server") minor-mode-alist
)))
156 (defvar server-existing-buffer nil
157 "Non-nil means the buffer existed before the server was asked to visit it.
158 This means that the server should not kill the buffer when you say you
159 are done with it in the server.")
160 (make-variable-buffer-local 'server-existing-buffer
)
162 (defvar server-name
"server")
164 (defvar server-socket-dir nil
165 "The directory in which to place the server socket.
166 Initialized by `server-start'.")
168 (defun server-client (proc)
169 "Return the Emacs client corresponding to PROC.
170 PROC must be a process object.
171 The car of the result is PROC; the cdr is an association list.
172 See `server-client-get' and `server-client-set'."
173 (assq proc server-clients
))
175 (defun server-client-get (client property
)
176 "Get the value of PROPERTY in CLIENT.
177 CLIENT may be a process object, or a client returned by `server-client'.
178 Return nil if CLIENT has no such property."
179 (or (listp client
) (setq client
(server-client client
)))
180 (cdr (assq property
(cdr client
))))
182 (defun server-client-set (client property value
)
183 "Set the PROPERTY to VALUE in CLIENT, and return VALUE.
184 CLIENT may be a process object, or a client returned by `server-client'."
187 (setq proc
(car client
))
189 client
(server-client client
)))
190 (setq p
(assq property client
))
193 (client (setcdr client
(cons (cons property value
) (cdr client
))))
194 (t (setq server-clients
195 `((,proc
(,property .
,value
)) .
,server-clients
))))
198 (defun server-clients-with (property value
)
199 "Return a list of clients with PROPERTY set to VALUE."
201 (dolist (client server-clients result
)
202 (when (equal value
(server-client-get client property
))
203 (setq result
(cons (car client
) result
))))))
205 (defun server-add-client (proc)
206 "Create a client for process PROC, if it doesn't already have one.
207 New clients have no properties."
208 (unless (server-client proc
)
209 (setq server-clients
(cons (cons proc nil
)
212 (defun server-getenv-from (env variable
)
213 "Get the value of VARIABLE in ENV.
214 VARIABLE should be a string. Value is nil if VARIABLE is
215 undefined in ENV. Otherwise, value is a string.
217 ENV should be in the same format as `process-environment'."
219 (while (and env
(null result
))
220 (setq entry
(car env
)
222 (if (and (> (length entry
) (length variable
))
223 (eq ?
= (aref entry
(length variable
)))
224 (equal variable
(substring entry
0 (length variable
))))
225 (setq result
(substring entry
(+ (length variable
) 1)))))
228 (defmacro server-with-environment
(env vars
&rest body
)
229 "Evaluate BODY with environment variables VARS set to those in ENV.
230 The environment variables are then restored to their previous values.
232 VARS should be a list of strings.
233 ENV should be in the same format as `process-environment'."
235 (let ((oldvalues (make-symbol "oldvalues"))
236 (var (make-symbol "var"))
237 (value (make-symbol "value"))
238 (pair (make-symbol "pair")))
241 (let ((,value
(server-getenv-from ,env
,var
)))
242 (setq ,oldvalues
(cons (cons ,var
(getenv ,var
)) ,oldvalues
))
243 (setenv ,var
,value
)))
246 (dolist (,pair
,oldvalues
)
247 (setenv (car ,pair
) (cdr ,pair
)))))))
249 (defun server-delete-client (client &optional noframe
)
250 "Delete CLIENT, including its buffers, terminals and frames.
251 If NOFRAME is non-nil, let the frames live. (To be used from
252 `delete-frame-functions'.)"
253 (server-log (concat "server-delete-client" (if noframe
" noframe"))
255 ;; Force a new lookup of client (prevents infinite recursion).
256 (setq client
(server-client
257 (if (listp client
) (car client
) client
)))
258 (let ((proc (car client
))
259 (buffers (server-client-get client
'buffers
)))
262 ;; Kill the client's buffers.
263 (dolist (buf buffers
)
264 (when (buffer-live-p buf
)
265 (with-current-buffer buf
266 ;; Kill the buffer if necessary.
267 (when (and (equal server-buffer-clients
269 (or (and server-kill-new-buffers
270 (not server-existing-buffer
))
271 (server-temp-file-p))
272 (not (buffer-modified-p)))
275 (progn (setq server-buffer-clients nil
)
276 (kill-buffer (current-buffer))
279 ;; Restore clients if user pressed C-g in `kill-buffer'.
280 (setq server-buffer-clients
(list proc
)))))))))
282 ;; Delete the client's frames.
284 (dolist (frame (frame-list))
285 (when (and (frame-live-p frame
)
286 (equal proc
(frame-parameter frame
'client
)))
287 ;; Prevent `server-handle-delete-frame' from calling us
289 (set-frame-parameter frame
'client nil
)
290 (delete-frame frame
))))
292 (setq server-clients
(delq client server-clients
))
294 ;; Delete the client's tty.
295 (let ((terminal (server-client-get client
'terminal
)))
296 (when (eq (terminal-live-p terminal
) t
)
297 (delete-terminal terminal
)))
299 ;; Delete the client's process.
300 (if (eq (process-status (car client
)) 'open
)
301 (delete-process (car client
)))
303 (server-log "Deleted" proc
))))
305 (defun server-log (string &optional client
)
306 "If a *server* buffer exists, write STRING to it for logging purposes.
307 If CLIENT is non-nil, add a description of it to the logged
309 (if (get-buffer "*server*")
310 (with-current-buffer "*server*"
311 (goto-char (point-max))
312 (insert (current-time-string)
315 ((listp client
) (format " %s: " (car client
)))
316 (t (format " %s: " client
)))
318 (or (bolp) (newline)))))
320 (defun server-sentinel (proc msg
)
321 "The process sentinel for Emacs server connections."
322 ;; If this is a new client process, set the query-on-exit flag to nil
323 ;; for this process (it isn't inherited from the server process).
324 (when (and (eq (process-status proc
) 'open
)
325 (process-query-on-exit-flag proc
))
326 (set-process-query-on-exit-flag proc nil
))
327 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
328 (server-delete-client proc
))
330 (defun server-handle-delete-frame (frame)
331 "Delete the client connection when the emacsclient frame is deleted."
332 (let ((proc (frame-parameter frame
'client
)))
333 (when (and (frame-live-p frame
)
335 ;; See if this is the last frame for this client.
336 (>= 1 (let ((frame-num 0))
337 (dolist (f (frame-list))
338 (when (eq proc
(frame-parameter f
'client
))
339 (setq frame-num
(1+ frame-num
))))
341 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
342 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
344 (defun server-handle-suspend-tty (terminal)
345 "Notify the emacsclient process to suspend itself when its tty device is suspended."
346 (dolist (proc (server-clients-with 'terminal terminal
))
347 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
) proc
)
349 (server-send-string proc
"-suspend \n")
350 (file-error (condition-case nil
(server-delete-client proc
) (error nil
))))))
352 (defun server-unquote-arg (arg)
353 "Remove &-quotation from ARG.
354 See `server-quote-arg' and `server-process-filter'."
355 (replace-regexp-in-string
364 (defun server-quote-arg (arg)
365 "In ARG, insert a & before each &, each space, each newline, and -.
366 Change spaces to underscores, too, so that the return value never
369 See `server-unquote-arg' and `server-process-filter'."
370 (replace-regexp-in-string
371 "[-&\n ]" (lambda (s)
379 (defun server-send-string (proc string
)
380 "A wrapper around `proc-send-string' for logging."
381 (server-log (concat "Sent " string
) proc
)
382 (process-send-string proc string
))
384 (defun server-ensure-safe-dir (dir)
385 "Make sure DIR is a directory with no race-condition issues.
386 Creates the directory if necessary and makes sure:
387 - there's no symlink involved
389 - it's not readable/writable by anybody else."
390 (setq dir
(directory-file-name dir
))
391 (let ((attrs (file-attributes dir
)))
393 (letf (((default-file-modes) ?
\700)) (make-directory dir
))
394 (setq attrs
(file-attributes dir
)))
395 ;; Check that it's safe for use.
396 (unless (and (eq t
(car attrs
)) (eq (nth 2 attrs
) (user-uid))
397 (zerop (logand ?
\077 (file-modes dir
))))
398 (error "The directory %s is unsafe" dir
))))
401 (defun server-start (&optional leave-dead
)
402 "Allow this Emacs process to be a server for client processes.
403 This starts a server communications subprocess through which
404 client \"editors\" can send your editing commands to this Emacs
405 job. To use the server, set up the program `emacsclient' in the
406 Emacs distribution as your standard \"editor\".
408 Prefix arg LEAVE-DEAD means just kill any existing server
409 communications subprocess."
414 "The current server still has clients; delete them? "))
415 ;; It is safe to get the user id now.
416 (setq server-socket-dir
(or server-socket-dir
417 (format "/tmp/emacs%d" (user-uid))))
418 ;; Make sure there is a safe directory in which to place the socket.
419 (server-ensure-safe-dir server-socket-dir
)
422 (condition-case () (delete-process server-process
) (error nil
)))
423 ;; Delete the socket files made by previous server invocations.
425 (delete-file (expand-file-name server-name server-socket-dir
))
427 ;; If this Emacs already had a server, clear out associated status.
428 (while server-clients
429 (server-delete-client (car server-clients
)))
432 (server-log (message "Server stopped"))
433 (setq server-process nil
))
435 (server-log (message "Restarting server"))
436 (server-log (message "Starting server")))
437 (letf (((default-file-modes) ?
\700))
438 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
439 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
440 (add-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
441 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
443 (make-network-process
444 :name
"server" :family
'local
:server t
:noquery t
445 :service
(expand-file-name server-name server-socket-dir
)
446 :sentinel
'server-sentinel
:filter
'server-process-filter
447 ;; We must receive file names without being decoded.
448 ;; Those are decoded by server-process-filter according
449 ;; to file-name-coding-system.
450 :coding
'raw-text
))))))
453 (define-minor-mode server-mode
455 With ARG, turn Server mode on if ARG is positive, off otherwise.
456 Server mode runs a process that accepts commands from the
457 `emacsclient' program. See `server-start' and Info node `Emacs server'."
461 ;; Fixme: Should this check for an existing server socket and do
462 ;; nothing if there is one (for multiple Emacs sessions)?
463 (server-start (not server-mode
)))
465 (defun server-process-filter (proc string
)
466 "Process a request from the server to edit some files.
467 PROC is the server process. STRING consists of a sequence of
468 commands prefixed by a dash. Some commands have arguments; these
469 are &-quoted and need to be decoded by `server-unquote-arg'. The
470 filter parses and executes these commands.
472 To illustrate the protocol, here is an example command that
473 emacsclient sends to create a new X frame (note that the whole
474 sequence is sent on a single line):
476 -version 21.3.50 xterm
477 -env HOME /home/lorentey
479 ... lots of other -env commands
483 The server normally sends back the single command `-good-version'
486 The following commands are accepted by the server:
488 `-version CLIENT-VERSION'
489 Check version numbers between server and client, and signal an
490 error if there is a mismatch. The server replies with
491 `-good-version' to confirm the match.
494 An environment variable on the client side.
497 Forbid the creation of new frames.
500 Request that the next frame created should not be
501 associated with this client.
504 Set the display name to open X frames on.
506 `-position LINE[:COLUMN]'
507 Go to the given line and column number
508 in the next file opened.
511 Load the given file in the current frame.
514 Evaluate EXPR as a Lisp expression and return the
515 result in -print commands.
520 `-tty DEVICENAME TYPE'
521 Open a new tty frame at the client.
524 Resume this tty frame. The client sends this string when it
525 gets the SIGCONT signal and it is the foreground process on its
529 Suspend this tty frame. The client sends this string in
530 response to SIGTSTP and SIGTTOU. The server must cease all I/O
531 on this tty until it gets a -resume command.
534 Do nothing, but put the comment in the server
535 log. Useful for debugging.
538 The following commands are accepted by the client:
541 Signals a version match between the client and the server.
544 Describes the process id of the Emacs process;
545 used to forward window change signals to it.
547 `-window-system-unsupported'
548 Signals that the server does not
549 support creating X frames; the client must try again with a tty
553 Print STRING on stdout. Used to send values
557 Signal an error (but continue processing).
560 Suspend this terminal, i.e., stop the client process. Sent
561 when the user presses C-z."
562 (server-log (concat "Received " string
) proc
)
563 (let ((prev (process-get proc
'previous-string
)))
565 (setq string
(concat prev string
))
566 (process-put proc
'previous-string nil
)))
569 (server-add-client proc
)
570 ;; If the input is multiple lines,
571 ;; process each line individually.
572 (while (string-match "\n" string
)
573 (let ((request (substring string
0 (match-beginning 0)))
574 (coding-system (and default-enable-multibyte-characters
575 (or file-name-coding-system
576 default-file-name-coding-system
)))
577 (client (server-client proc
))
579 nowait
; t if emacsclient does not want to wait for us.
580 frame
; The frame that was opened for the client (if any).
581 display
; Open the frame on this display.
582 dontkill
; t if the client should not be killed.
587 ;; Remove this line from STRING.
588 (setq string
(substring string
(match-end 0)))
589 (while (string-match " *[^ ]* " request
)
590 (let ((arg (substring request
(match-beginning 0) (1- (match-end 0)))))
591 (setq request
(substring request
(match-end 0)))
593 ;; -version CLIENT-VERSION:
594 ;; Check version numbers, signal an error if there is a mismatch.
595 ((and (equal "-version" arg
)
596 (string-match "\\([0-9.]+\\) " request
))
597 (let* ((client-version (match-string 1 request
))
598 (truncated-emacs-version
599 (substring emacs-version
0 (length client-version
))))
600 (setq request
(substring request
(match-end 0)))
601 (if (equal client-version truncated-emacs-version
)
603 (server-send-string proc
"-good-version \n")
604 (server-client-set client
'version client-version
))
605 (error (concat "Version mismatch: Emacs is "
606 truncated-emacs-version
607 ", emacsclient is " client-version
)))))
609 ;; -nowait: Emacsclient won't wait for a result.
610 ((equal "-nowait" arg
) (setq nowait t
))
612 ;; -current-frame: Don't create frames.
613 ((equal "-current-frame" arg
) (setq current-frame t
))
616 ;; Open X frames on the given display instead of the default.
617 ((and (equal "-display" arg
) (string-match "\\([^ ]*\\) " request
))
618 (setq display
(match-string 1 request
)
619 request
(substring request
(match-end 0))))
621 ;; -window-system: Open a new X frame.
622 ((equal "-window-system" arg
)
623 (unless (server-client-get client
'version
)
624 (error "Protocol error; make sure to use the correct version of emacsclient"))
625 (unless current-frame
626 (if (fboundp 'x-create-frame
)
627 (let ((params (if nowait
628 ;; Flag frame as client-created, but use a dummy client.
629 ;; This will prevent the frame from being deleted when
630 ;; emacsclient quits while also preventing
631 ;; `server-save-buffers-kill-terminal' from unexpectedly
632 ;; killing emacs on that frame.
633 (list (cons 'client
'nowait
) (cons 'environment env
))
634 (list (cons 'client proc
) (cons 'environment env
)))))
635 (setq frame
(make-frame-on-display
637 (frame-parameter nil
'display
)
639 (error "Please specify display"))
641 (server-log (format "%s created" frame
) proc
)
642 ;; XXX We need to ensure the parameters are
643 ;; really set because Emacs forgets unhandled
644 ;; initialization parameters for X frames at
646 (modify-frame-parameters frame params
)
648 (server-client-set client
'frame frame
)
649 (server-client-set client
'terminal
(frame-terminal frame
))
651 ;; Display *scratch* by default.
652 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
655 ;; This emacs does not support X.
656 (server-log "Window system unsupported" proc
)
657 (server-send-string proc
"-window-system-unsupported \n")
660 ;; -resume: Resume a suspended tty frame.
661 ((equal "-resume" arg
)
662 (let ((terminal (server-client-get client
'terminal
)))
664 (when (eq (terminal-live-p terminal
) t
)
665 (resume-tty terminal
))))
667 ;; -suspend: Suspend the client's frame. (In case we
668 ;; get out of sync, and a C-z sends a SIGTSTP to
670 ((equal "-suspend" arg
)
671 (let ((terminal (server-client-get client
'terminal
)))
673 (when (eq (terminal-live-p terminal
) t
)
674 (suspend-tty terminal
))))
676 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
677 ;; (The given comment appears in the server log.)
678 ((and (equal "-ignore" arg
) (string-match "\\([^ ]*\\) " request
))
680 request
(substring request
(match-end 0))))
682 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
683 ((and (equal "-tty" arg
) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request
))
684 (let ((tty (server-unquote-arg (match-string 1 request
)))
685 (type (server-unquote-arg (match-string 2 request
))))
686 (setq request
(substring request
(match-end 0)))
687 (unless (server-client-get client
'version
)
688 (error "Protocol error; make sure you use the correct version of emacsclient"))
689 (unless current-frame
690 (server-with-environment env
691 '("LANG" "LC_CTYPE" "LC_ALL"
692 ;; For tgetent(3); list according to ncurses(3).
693 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
694 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
695 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
696 "TERMINFO_DIRS" "TERMPATH")
697 (setq frame
(make-frame-on-tty tty type
698 ;; Ignore nowait here; we always need to clean
699 ;; up opened ttys when the client dies.
701 (environment .
,env
)))))
703 (server-client-set client
'frame frame
)
704 (server-client-set client
'tty
(terminal-name frame
))
705 (server-client-set client
'terminal
(frame-terminal frame
))
707 ;; Display *scratch* by default.
708 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord
)
710 ;; Reply with our pid.
711 (server-send-string proc
(concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
714 ;; -position LINE: Go to the given line in the next file.
715 ((and (equal "-position" arg
) (string-match "\\(\\+[0-9]+\\) " request
))
716 (setq lineno
(string-to-number (substring (match-string 1 request
) 1))
717 request
(substring request
(match-end 0))))
719 ;; -position LINE:COLUMN: Set point to the given position in the next file.
720 ((and (equal "-position" arg
) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request
))
721 (setq lineno
(string-to-number (match-string 1 request
))
722 columnno
(string-to-number (match-string 2 request
))
723 request
(substring request
(match-end 0))))
725 ;; -file FILENAME: Load the given file.
726 ((and (equal "-file" arg
) (string-match "\\([^ ]+\\) " request
))
727 (let ((file (server-unquote-arg (match-string 1 request
))))
728 (setq request
(substring request
(match-end 0)))
730 (setq file
(decode-coding-string file coding-system
)))
731 (setq file
(command-line-normalize-file-name file
))
732 (push (list file lineno columnno
) files
)
733 (server-log (format "New file: %s (%d:%d)" file lineno columnno
) proc
))
737 ;; -eval EXPR: Evaluate a Lisp expression.
738 ((and (equal "-eval" arg
) (string-match "\\([^ ]+\\) " request
))
739 (let ((expr (server-unquote-arg (match-string 1 request
))))
740 (setq request
(substring request
(match-end 0)))
742 (setq expr
(decode-coding-string expr coding-system
)))
743 (let ((v (eval (car (read-from-string expr
)))))
744 (when (and (not frame
) v
)
746 (let ((standard-output (current-buffer)))
749 proc
(format "-print %s\n"
751 (buffer-substring-no-properties (point-min)
756 ;; -env NAME=VALUE: An environment variable.
757 ((and (equal "-env" arg
) (string-match "\\([^ ]+\\) " request
))
758 (let ((var (server-unquote-arg (match-string 1 request
))))
759 ;; XXX Variables should be encoded as in getenv/setenv.
760 (setq request
(substring request
(match-end 0)))
761 (setq env
(cons var env
))))
764 (t (error "Unknown command: %s" arg
)))))
768 (run-hooks 'pre-command-hook
)
769 (setq buffers
(server-visit-files files client nowait
))
770 (run-hooks 'post-command-hook
))
773 (with-selected-frame frame
774 (display-startup-echo-area-message)
775 (unless inhibit-splash-screen
777 ;; This looks scary because `fancy-splash-screens'
778 ;; will call `recursive-edit' from a process filter.
779 ;; However, that should be safe to do now.
780 (display-splash-screen)
781 ;; `recursive-edit' will throw an error if Emacs is
782 ;; already doing a recursive edit elsewhere. Catch it
783 ;; here so that we can finish normally.
786 ;; Delete the client if necessary.
789 ;; Client requested nowait; return immediately.
790 (server-log "Close nowait client" proc
)
791 (server-delete-client proc
))
792 ((and (not dontkill
) (null buffers
))
793 ;; This client is empty; get rid of it immediately.
794 (server-log "Close empty client" proc
)
795 (server-delete-client proc
)))
797 ((or isearch-mode
(minibufferp))
799 ((and frame
(null buffers
))
800 (message "%s" (substitute-command-keys
801 "When done with this frame, type \\[delete-frame]")))
802 ((not (null buffers
))
803 (server-switch-buffer (car buffers
))
804 (run-hooks 'server-switch-hook
)
806 (message "%s" (substitute-command-keys
807 "When done with a buffer, type \\[server-edit]"))))))))
809 ;; Save for later any partial line that remains.
810 (when (> (length string
) 0)
811 (process-put proc
'previous-string string
)))
813 (error (ignore-errors
815 proc
(concat "-error " (server-quote-arg (error-message-string err
))))
817 (server-log (error-message-string err
) proc
)
818 (delete-process proc
)))))
820 (defun server-goto-line-column (file-line-col)
821 "Move point to the position indicated in FILE-LINE-COL.
822 FILE-LINE-COL should be a three-element list as described in
823 `server-visit-files'."
824 (goto-line (nth 1 file-line-col
))
825 (let ((column-number (nth 2 file-line-col
)))
826 (if (> column-number
0)
827 (move-to-column (1- column-number
)))))
829 (defun server-visit-files (files client
&optional nowait
)
830 "Find FILES and return a list of buffers created.
831 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
832 CLIENT is the client that requested this operation.
833 NOWAIT non-nil means this client is not waiting for the results,
834 so don't mark these buffers specially, just visit them normally."
835 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
836 (let ((last-nonmenu-event t
) client-record
)
837 ;; Restore the current buffer afterward, but not using save-excursion,
838 ;; because we don't want to save point in this buffer
839 ;; if it happens to be one of those specified by the server.
842 ;; If there is an existing buffer modified or the file is
843 ;; modified, revert it. If there is an existing buffer with
844 ;; deleted file, offer to write it.
845 (let* ((filen (car file
))
846 (obuf (get-file-buffer filen
)))
847 (push filen file-name-history
)
848 (if (and obuf
(set-buffer obuf
))
850 (cond ((file-exists-p filen
)
851 (if (not (verify-visited-file-modtime obuf
))
852 (revert-buffer t nil
)))
855 (concat "File no longer exists: " filen
856 ", write buffer to file? "))
857 (write-file filen
))))
858 (unless server-buffer-clients
859 (setq server-existing-buffer t
))
860 (server-goto-line-column file
))
861 (set-buffer (find-file-noselect filen
))
862 (server-goto-line-column file
)
863 (run-hooks 'server-visit-hook
)))
865 ;; When the buffer is killed, inform the clients.
866 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
867 (push (car client
) server-buffer-clients
))
868 (push (current-buffer) client-record
)))
872 (nconc (server-client-get client
'buffers
) client-record
)))
875 (defun server-buffer-done (buffer &optional for-killing
)
876 "Mark BUFFER as \"done\" for its client(s).
877 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
878 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
879 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
881 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
882 (let ((next-buffer nil
)
884 (dolist (client server-clients
)
885 (let ((buffers (server-client-get client
'buffers
)))
887 (setq next-buffer
(nth 1 (memq buffer buffers
))))
888 (when buffers
; Ignore bufferless clients.
889 (setq buffers
(delq buffer buffers
))
890 ;; Delete all dead buffers from CLIENT.
893 (not (buffer-live-p b
))
894 (setq buffers
(delq b buffers
))))
895 (server-client-set client
'buffers buffers
)
896 ;; If client now has no pending buffers,
897 ;; tell it that it is done, and forget it entirely.
899 (server-log "Close" client
)
900 (server-delete-client client
)))))
901 (if (and (bufferp buffer
) (buffer-name buffer
))
902 ;; We may or may not kill this buffer;
903 ;; if we do, do not call server-buffer-done recursively
904 ;; from kill-buffer-hook.
905 (let ((server-kill-buffer-running t
))
906 (with-current-buffer buffer
907 (setq server-buffer-clients nil
)
908 (run-hooks 'server-done-hook
))
909 ;; Notice whether server-done-hook killed the buffer.
910 (if (null (buffer-name buffer
))
912 ;; Don't bother killing or burying the buffer
913 ;; when we are called from kill-buffer.
915 (when (and (not killed
)
916 server-kill-new-buffers
917 (with-current-buffer buffer
918 (not server-existing-buffer
)))
921 (kill-buffer buffer
))
923 (if (server-temp-file-p buffer
)
927 (bury-buffer buffer
)))))))
928 (list next-buffer killed
)))
930 (defun server-temp-file-p (&optional buffer
)
931 "Return non-nil if BUFFER contains a file considered temporary.
932 These are files whose names suggest they are repeatedly
933 reused to pass information to another program.
935 The variable `server-temp-file-regexp' controls which filenames
936 are considered temporary."
937 (and (buffer-file-name buffer
)
938 (string-match server-temp-file-regexp
(buffer-file-name buffer
))))
940 (defun server-done ()
941 "Offer to save current buffer, mark it as \"done\" for clients.
942 This kills or buries the buffer, then returns a list
943 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
944 as a suggestion for what to select next, or nil.
945 KILLED is t if we killed BUFFER, which happens if it was created
946 specifically for the clients and did not exist before their request for it."
947 (when server-buffer-clients
948 (if (server-temp-file-p)
949 ;; For a temp file, save, and do make a non-numeric backup
950 ;; (unless make-backup-files is nil).
951 (let ((version-control nil
)
952 (buffer-backed-up nil
))
954 (if (and (buffer-modified-p)
956 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
958 (server-buffer-done (current-buffer))))
960 ;; Ask before killing a server buffer.
961 ;; It was suggested to release its client instead,
962 ;; but I think that is dangerous--the client would proceed
963 ;; using whatever is on disk in that file. -- rms.
964 (defun server-kill-buffer-query-function ()
965 "Ask before killing a server buffer."
966 (or (not server-buffer-clients
)
968 (dolist (proc server-buffer-clients res
)
969 (let ((client (server-client proc
)))
970 (when (and client
(eq (process-status proc
) 'open
))
972 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
973 (buffer-name (current-buffer))))))
975 (defun server-kill-emacs-query-function ()
976 "Ask before exiting Emacs it has live clients."
977 (or (not server-clients
)
979 (dolist (client server-clients live-client
)
980 (if (memq t
(mapcar 'buffer-live-p
(server-client-get
982 (setq live-client t
))))
983 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
985 (defvar server-kill-buffer-running nil
986 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
988 (defun server-kill-buffer ()
989 "Remove the current buffer from its clients' buffer list.
990 Designed to be added to `kill-buffer-hook'."
991 ;; Prevent infinite recursion if user has made server-done-hook
993 (or server-kill-buffer-running
994 (and server-buffer-clients
995 (let ((server-kill-buffer-running t
))
997 (server-buffer-done (current-buffer) t
))))))
999 (defun server-edit (&optional arg
)
1000 "Switch to next server editing buffer; say \"Done\" for current buffer.
1001 If a server buffer is current, it is marked \"done\" and optionally saved.
1002 The buffer is also killed if it did not exist before the clients asked for it.
1003 When all of a client's buffers are marked as \"done\", the client is notified.
1005 Temporary files such as MH <draft> files are always saved and backed up,
1006 no questions asked. (The variable `make-backup-files', if nil, still
1007 inhibits a backup; you can set it locally in a particular buffer to
1008 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1009 which filenames are considered temporary.
1011 If invoked with a prefix argument, or if there is no server process running,
1012 starts server process and that is all. Invoked by \\[server-edit]."
1015 (not server-process
)
1016 (memq (process-status server-process
) '(signal exit
)))
1018 (apply 'server-switch-buffer
(server-done))))
1020 (defun server-switch-buffer (&optional next-buffer killed-one
)
1021 "Switch to another buffer, preferably one that has a client.
1022 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1024 KILLED-ONE is t in a recursive call if we have already killed one
1025 temp-file server buffer. This means we should avoid the final
1026 \"switch to some other buffer\" since we've already effectively
1028 (if (null next-buffer
)
1030 (let ((rest server-clients
))
1031 (while (and rest
(not next-buffer
))
1032 (let ((client (car rest
)))
1033 ;; Only look at frameless clients.
1034 (when (not (server-client-get client
'frame
))
1035 (setq next-buffer
(car (server-client-get client
'buffers
))))
1036 (setq rest
(cdr rest
)))))
1037 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1038 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1039 ;; (switch-to-buffer (other-buffer))
1040 (message "No server buffers remain to edit")))
1041 (if (not (buffer-live-p next-buffer
))
1042 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1043 ;; and try the next surviving server buffer.
1044 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1045 ;; OK, we know next-buffer is live, let's display and select it.
1046 (if (functionp server-window
)
1047 (funcall server-window next-buffer
)
1048 (let ((win (get-buffer-window next-buffer
0)))
1049 (if (and win
(not server-window
))
1050 ;; The buffer is already displayed: just reuse the window.
1051 (let ((frame (window-frame win
)))
1052 (if (eq (frame-visible-p frame
) 'icon
)
1053 (raise-frame frame
))
1055 (set-buffer next-buffer
))
1056 ;; Otherwise, let's find an appropriate window.
1057 (cond ((and (windowp server-window
)
1058 (window-live-p server-window
))
1059 (select-window server-window
))
1060 ((framep server-window
)
1061 (if (not (frame-live-p server-window
))
1062 (setq server-window
(make-frame)))
1063 (select-window (frame-selected-window server-window
))))
1064 (if (window-minibuffer-p (selected-window))
1065 (select-window (next-window nil
'nomini
0)))
1066 ;; Move to a non-dedicated window, if we have one.
1067 (when (window-dedicated-p (selected-window))
1069 (get-window-with-predicate
1071 (and (not (window-dedicated-p w
))
1072 (equal (frame-terminal (window-frame w
))
1073 (frame-terminal (selected-frame)))))
1074 'nomini
'visible
(selected-window))))
1076 (switch-to-buffer next-buffer
)
1077 ;; After all the above, we might still have ended up with
1078 ;; a minibuffer/dedicated-window (if there's no other).
1079 (error (pop-to-buffer next-buffer
)))))))))
1082 (defun server-save-buffers-kill-terminal (proc &optional arg
)
1083 "Offer to save each buffer, then kill PROC.
1085 With prefix arg, silently save all file-visiting buffers, then kill.
1087 If emacsclient was started with a list of filenames to edit, then
1088 only these files will be asked to be saved."
1089 (let ((buffers (server-client-get proc
'buffers
)))
1090 ;; If client is bufferless, emulate a normal Emacs session
1091 ;; exit and offer to save all buffers. Otherwise, offer to
1092 ;; save only the buffers belonging to the client.
1093 (save-some-buffers arg
1095 (lambda () (memq (current-buffer) buffers
))
1097 (server-delete-client proc
)))
1099 (define-key ctl-x-map
"#" 'server-edit
)
1101 (defun server-unload-hook ()
1102 "Unload the server library."
1104 (remove-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
1105 (remove-hook 'delete-frame-functions
'server-handle-delete-frame
)
1106 (remove-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
1107 (remove-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
1108 (remove-hook 'kill-buffer-hook
'server-kill-buffer
))
1110 (add-hook 'server-unload-hook
'server-unload-hook
)
1114 ;;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1115 ;;; server.el ends here