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 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 ids for clients 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 ;; Force a new lookup of client (prevents infinite recursion).
254 (setq client
(server-client
255 (if (listp client
) (car client
) client
)))
256 (let ((proc (car client
))
257 (buffers (server-client-get client
'buffers
)))
259 (setq server-clients
(delq client server-clients
))
261 (dolist (buf buffers
)
262 (when (buffer-live-p buf
)
263 (with-current-buffer buf
264 ;; Remove PROC from the clients of each buffer.
265 (setq server-buffer-clients
(delq proc server-buffer-clients
))
266 ;; Kill the buffer if necessary.
267 (when (and (null server-buffer-clients
)
268 (or (and server-kill-new-buffers
269 (not server-existing-buffer
))
270 (server-temp-file-p)))
271 (kill-buffer (current-buffer))))))
273 ;; Delete the client's tty.
274 (let ((terminal (server-client-get client
'terminal
)))
275 (when (eq (terminal-live-p terminal
) t
)
276 (delete-terminal terminal
)))
278 ;; Delete the client's frames.
280 (dolist (frame (frame-list))
281 (if (and (frame-live-p frame
)
282 (equal (car client
) (frame-parameter frame
'client
)))
283 (delete-frame frame
))))
285 ;; Delete the client's process.
286 (if (eq (process-status (car client
)) 'open
)
287 (delete-process (car client
)))
289 (server-log "Deleted" proc
))))
291 (defun server-log (string &optional client
)
292 "If a *server* buffer exists, write STRING to it for logging purposes.
293 If CLIENT is non-nil, add a description of it to the logged
295 (if (get-buffer "*server*")
296 (with-current-buffer "*server*"
297 (goto-char (point-max))
298 (insert (current-time-string)
301 ((listp client
) (format " %s: " (car client
)))
302 (t (format " %s: " client
)))
304 (or (bolp) (newline)))))
306 (defun server-sentinel (proc msg
)
307 "The process sentinel for Emacs server connections."
308 ;; If this is a new client process, set the query-on-exit flag to nil
309 ;; for this process (it isn't inherited from the server process).
310 (when (and (eq (process-status proc
) 'open
)
311 (process-query-on-exit-flag proc
))
312 (set-process-query-on-exit-flag proc nil
))
313 (server-log (format "Status changed to %s: %s" (process-status proc
) msg
) proc
)
314 (server-delete-client proc
))
316 (defun server-handle-delete-frame (frame)
317 "Delete the client connection when the emacsclient frame is deleted."
318 (let ((proc (frame-parameter frame
'client
)))
319 (when (and (frame-live-p frame
)
321 (or (window-system frame
)
322 ;; A terminal device must not yet be deleted if
323 ;; there are other frames on it.
324 (< 0 (let ((frame-num 0))
326 (when (eq (frame-terminal f
)
327 (frame-terminal frame
))
328 (setq frame-num
(1+ frame-num
))))
331 (server-log (format "server-handle-delete-frame, frame %s" frame
) proc
)
332 (server-delete-client proc
'noframe
)))) ; Let delete-frame delete the frame later.
334 (defun server-handle-suspend-tty (terminal)
335 "Notify the emacsclient process to suspend itself when its tty device is suspended."
336 (dolist (proc (server-clients-with 'terminal terminal
))
337 (server-log (format "server-handle-suspend-tty, terminal %s" terminal
) proc
)
339 (server-send-string proc
"-suspend \n")
340 (file-error (condition-case nil
(server-delete-client proc
) (error nil
))))))
342 (defun server-unquote-arg (arg)
343 "Remove &-quotation from ARG.
344 See `server-quote-arg' and `server-process-filter'."
345 (replace-regexp-in-string
354 (defun server-quote-arg (arg)
355 "In ARG, insert a & before each &, each space, each newline, and -.
356 Change spaces to underscores, too, so that the return value never
359 See `server-unquote-arg' and `server-process-filter'."
360 (replace-regexp-in-string
361 "[-&\n ]" (lambda (s)
369 (defun server-send-string (proc string
)
370 "A wrapper around `proc-send-string' for logging."
371 (server-log (concat "Sent " string
) proc
)
372 (process-send-string proc string
))
374 (defun server-ensure-safe-dir (dir)
375 "Make sure DIR is a directory with no race-condition issues.
376 Creates the directory if necessary and makes sure:
377 - there's no symlink involved
379 - it's not readable/writable by anybody else."
380 (setq dir
(directory-file-name dir
))
381 (let ((attrs (file-attributes dir
)))
383 (letf (((default-file-modes) ?
\700)) (make-directory dir
))
384 (setq attrs
(file-attributes dir
)))
385 ;; Check that it's safe for use.
386 (unless (and (eq t
(car attrs
)) (eq (nth 2 attrs
) (user-uid))
387 (zerop (logand ?
\077 (file-modes dir
))))
388 (error "The directory %s is unsafe" dir
))))
391 (defun server-start (&optional leave-dead
)
392 "Allow this Emacs process to be a server for client processes.
393 This starts a server communications subprocess through which
394 client \"editors\" can send your editing commands to this Emacs
395 job. To use the server, set up the program `emacsclient' in the
396 Emacs distribution as your standard \"editor\".
398 Prefix arg LEAVE-DEAD means just kill any existing server
399 communications subprocess."
404 "The current server still has clients; delete them? "))
405 ;; It is safe to get the user id now.
406 (setq server-socket-dir
(or server-socket-dir
407 (format "/tmp/emacs%d" (user-uid))))
408 ;; Make sure there is a safe directory in which to place the socket.
409 (server-ensure-safe-dir server-socket-dir
)
412 (condition-case () (delete-process server-process
) (error nil
)))
413 ;; Delete the socket files made by previous server invocations.
415 (delete-file (expand-file-name server-name server-socket-dir
))
417 ;; If this Emacs already had a server, clear out associated status.
418 (while server-clients
419 (server-delete-client (car server-clients
)))
422 (server-log (message "Server stopped"))
423 (setq server-process nil
))
425 (server-log (message "Restarting server"))
426 (server-log (message "Starting server")))
427 (letf (((default-file-modes) ?
\700))
428 (add-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
429 (add-hook 'delete-frame-functions
'server-handle-delete-frame
)
430 (add-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
431 (add-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
433 (make-network-process
434 :name
"server" :family
'local
:server t
:noquery t
435 :service
(expand-file-name server-name server-socket-dir
)
436 :sentinel
'server-sentinel
:filter
'server-process-filter
437 ;; We must receive file names without being decoded.
438 ;; Those are decoded by server-process-filter according
439 ;; to file-name-coding-system.
440 :coding
'raw-text
))))))
443 (define-minor-mode server-mode
445 With ARG, turn Server mode on if ARG is positive, off otherwise.
446 Server mode runs a process that accepts commands from the
447 `emacsclient' program. See `server-start' and Info node `Emacs server'."
451 ;; Fixme: Should this check for an existing server socket and do
452 ;; nothing if there is one (for multiple Emacs sessions)?
453 (server-start (not server-mode
)))
455 (defun server-process-filter (proc string
)
456 "Process a request from the server to edit some files.
457 PROC is the server process. STRING consists of a sequence of
458 commands prefixed by a dash. Some commands have arguments; these
459 are &-quoted and need to be decoded by `server-unquote-arg'. The
460 filter parses and executes these commands.
462 To illustrate the protocol, here is an example command that
463 emacsclient sends to create a new X frame (note that the whole
464 sequence is sent on a single line):
466 -version 21.3.50 xterm
467 -env HOME /home/lorentey
469 ... lots of other -env commands
473 The server normally sends back the single command `-good-version'
476 The following commands are accepted by the server:
478 `-version CLIENT-VERSION'
479 Check version numbers between server and client, and signal an
480 error if there is a mismatch. The server replies with
481 `-good-version' to confirm the match.
484 An environment variable on the client side.
487 Forbid the creation of new frames.
490 Request that the next frame created should not be
491 associated with this client.
494 Set the display name to open X frames on.
496 `-position LINE[:COLUMN]'
497 Go to the given line and column number
498 in the next file opened.
501 Load the given file in the current frame.
504 Evaluate EXPR as a Lisp expression and return the
505 result in -print commands.
510 `-tty DEVICENAME TYPE'
511 Open a new tty frame at the client.
514 Resume this tty frame. The client sends this string when it
515 gets the SIGCONT signal and it is the foreground process on its
519 Suspend this tty frame. The client sends this string in
520 response to SIGTSTP and SIGTTOU. The server must cease all I/O
521 on this tty until it gets a -resume command.
524 Do nothing, but put the comment in the server
525 log. Useful for debugging.
528 The following commands are accepted by the client:
531 Signals a version match between the client and the server.
534 Describes the process id of the Emacs process;
535 used to forward window change signals to it.
537 `-window-system-unsupported'
538 Signals that the server does not
539 support creating X frames; the client must try again with a tty
543 Print STRING on stdout. Used to send values
547 Signal an error (but continue processing).
550 Suspend this terminal, i.e., stop the client process. Sent
551 when the user presses C-z."
552 (server-log (concat "Received " string
) proc
)
553 (let ((prev (process-get proc
'previous-string
)))
555 (setq string
(concat prev string
))
556 (process-put proc
'previous-string nil
)))
559 (server-add-client proc
)
560 ;; If the input is multiple lines,
561 ;; process each line individually.
562 (while (string-match "\n" string
)
563 (let ((request (substring string
0 (match-beginning 0)))
564 (coding-system (and default-enable-multibyte-characters
565 (or file-name-coding-system
566 default-file-name-coding-system
)))
567 (client (server-client proc
))
569 nowait
; t if emacsclient does not want to wait for us.
570 frame
; The frame that was opened for the client (if any).
571 display
; Open the frame on this display.
572 dontkill
; t if the client should not be killed.
577 ;; Remove this line from STRING.
578 (setq string
(substring string
(match-end 0)))
579 (while (string-match " *[^ ]* " request
)
580 (let ((arg (substring request
(match-beginning 0) (1- (match-end 0)))))
581 (setq request
(substring request
(match-end 0)))
583 ;; -version CLIENT-VERSION:
584 ;; Check version numbers, signal an error if there is a mismatch.
585 ((and (equal "-version" arg
)
586 (string-match "\\([0-9.]+\\) " request
))
587 (let* ((client-version (match-string 1 request
))
588 (truncated-emacs-version
589 (substring emacs-version
0 (length client-version
))))
590 (setq request
(substring request
(match-end 0)))
591 (if (equal client-version truncated-emacs-version
)
593 (server-send-string proc
"-good-version \n")
594 (server-client-set client
'version client-version
))
595 (error (concat "Version mismatch: Emacs is "
596 truncated-emacs-version
597 ", emacsclient is " client-version
)))))
599 ;; -nowait: Emacsclient won't wait for a result.
600 ((equal "-nowait" arg
) (setq nowait t
))
602 ;; -current-frame: Don't create frames.
603 ((equal "-current-frame" arg
) (setq current-frame t
))
606 ;; Open X frames on the given display instead of the default.
607 ((and (equal "-display" arg
) (string-match "\\([^ ]*\\) " request
))
608 (setq display
(match-string 1 request
)
609 request
(substring request
(match-end 0))))
611 ;; -window-system: Open a new X frame.
612 ((equal "-window-system" arg
)
613 (unless (server-client-get client
'version
)
614 (error "Protocol error; make sure to use the correct version of emacsclient"))
615 (unless current-frame
616 (if (fboundp 'x-create-frame
)
617 (let ((params (if nowait
618 ;; Flag frame as client-created, but use a dummy client.
619 ;; This will prevent the frame from being deleted when
620 ;; emacsclient quits while also preventing
621 ;; `server-save-buffers-kill-terminal' from unexpectedly
622 ;; killing emacs on that frame.
623 (list (cons 'client
'nowait
) (cons 'environment env
))
624 (list (cons 'client proc
) (cons 'environment env
)))))
625 (setq frame
(make-frame-on-display
627 (frame-parameter nil
'display
)
629 (error "Please specify display"))
631 (server-log (format "%s created" frame
) proc
)
632 ;; XXX We need to ensure the parameters are
633 ;; really set because Emacs forgets unhandled
634 ;; initialization parameters for X frames at
636 (modify-frame-parameters frame params
)
638 (server-client-set client
'frame frame
)
639 (server-client-set client
'terminal
(frame-terminal frame
))
641 ;; This emacs does not support X.
642 (server-log "Window system unsupported" proc
)
643 (server-send-string proc
"-window-system-unsupported \n")
646 ;; -resume: Resume a suspended tty frame.
647 ((equal "-resume" arg
)
648 (let ((terminal (server-client-get client
'terminal
)))
650 (when (eq (terminal-live-p terminal
) t
)
651 (resume-tty terminal
))))
653 ;; -suspend: Suspend the client's frame. (In case we
654 ;; get out of sync, and a C-z sends a SIGTSTP to
656 ((equal "-suspend" arg
)
657 (let ((terminal (server-client-get client
'terminal
)))
659 (when (eq (terminal-live-p terminal
) t
)
660 (suspend-tty terminal
))))
662 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
663 ;; (The given comment appears in the server log.)
664 ((and (equal "-ignore" arg
) (string-match "\\([^ ]*\\) " request
))
666 request
(substring request
(match-end 0))))
668 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
669 ((and (equal "-tty" arg
) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request
))
670 (let ((tty (server-unquote-arg (match-string 1 request
)))
671 (type (server-unquote-arg (match-string 2 request
))))
672 (setq request
(substring request
(match-end 0)))
673 (unless (server-client-get client
'version
)
674 (error "Protocol error; make sure you use the correct version of emacsclient"))
675 (unless current-frame
676 (server-with-environment env
677 '("LANG" "LC_CTYPE" "LC_ALL"
678 ;; For tgetent(3); list according to ncurses(3).
679 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
680 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
681 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
682 "TERMINFO_DIRS" "TERMPATH")
683 (setq frame
(make-frame-on-tty tty type
684 ;; Ignore nowait here; we always need to clean
685 ;; up opened ttys when the client dies.
687 (environment .
,env
)))))
689 (server-client-set client
'frame frame
)
690 (server-client-set client
'tty
(terminal-name frame
))
691 (server-client-set client
'terminal
(frame-terminal frame
))
693 ;; Reply with our pid.
694 (server-send-string proc
(concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
697 ;; -position LINE: Go to the given line in the next file.
698 ((and (equal "-position" arg
) (string-match "\\(\\+[0-9]+\\) " request
))
699 (setq lineno
(string-to-number (substring (match-string 1 request
) 1))
700 request
(substring request
(match-end 0))))
702 ;; -position LINE:COLUMN: Set point to the given position in the next file.
703 ((and (equal "-position" arg
) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request
))
704 (setq lineno
(string-to-number (match-string 1 request
))
705 columnno
(string-to-number (match-string 2 request
))
706 request
(substring request
(match-end 0))))
708 ;; -file FILENAME: Load the given file.
709 ((and (equal "-file" arg
) (string-match "\\([^ ]+\\) " request
))
710 (let ((file (server-unquote-arg (match-string 1 request
))))
711 (setq request
(substring request
(match-end 0)))
713 (setq file
(decode-coding-string file coding-system
)))
714 (setq file
(command-line-normalize-file-name file
))
715 (push (list file lineno columnno
) files
)
716 (server-log (format "New file: %s (%d:%d)" file lineno columnno
) proc
))
720 ;; -eval EXPR: Evaluate a Lisp expression.
721 ((and (equal "-eval" arg
) (string-match "\\([^ ]+\\) " request
))
722 (let ((expr (server-unquote-arg (match-string 1 request
))))
723 (setq request
(substring request
(match-end 0)))
725 (setq expr
(decode-coding-string expr coding-system
)))
726 (let ((v (eval (car (read-from-string expr
)))))
727 (when (and (not frame
) v
)
729 (let ((standard-output (current-buffer)))
732 proc
(format "-print %s\n"
734 (buffer-substring-no-properties (point-min)
739 ;; -env NAME=VALUE: An environment variable.
740 ((and (equal "-env" arg
) (string-match "\\([^ ]+\\) " request
))
741 (let ((var (server-unquote-arg (match-string 1 request
))))
742 ;; XXX Variables should be encoded as in getenv/setenv.
743 (setq request
(substring request
(match-end 0)))
744 (setq env
(cons var env
))))
747 (t (error "Unknown command: %s" arg
)))))
751 (run-hooks 'pre-command-hook
)
752 (setq buffers
(server-visit-files files client nowait
))
753 (run-hooks 'post-command-hook
))
756 (with-selected-frame frame
757 (switch-to-buffer (or (car buffers
)
758 (get-buffer-create "*scratch*")))
759 (unless inhibit-splash-screen
760 (display-splash-screen))
761 (display-startup-echo-area-message)))
763 ;; Delete the client if necessary.
766 ;; Client requested nowait; return immediately.
767 (server-log "Close nowait client" proc
)
768 (server-delete-client proc
))
769 ((and (not dontkill
) (null buffers
))
770 ;; This client is empty; get rid of it immediately.
771 (server-log "Close empty client" proc
)
772 (server-delete-client proc
)))
774 ((or isearch-mode
(minibufferp))
776 ((and frame
(null buffers
))
777 (message "%s" (substitute-command-keys
778 "When done with this frame, type \\[delete-frame]")))
779 ((not (null buffers
))
780 (server-switch-buffer (car buffers
))
781 (run-hooks 'server-switch-hook
)
783 (message "%s" (substitute-command-keys
784 "When done with a buffer, type \\[server-edit]"))))))))
786 ;; Save for later any partial line that remains.
787 (when (> (length string
) 0)
788 (process-put proc
'previous-string string
)))
790 (error (ignore-errors
792 proc
(concat "-error " (server-quote-arg (error-message-string err
))))
794 (server-log (error-message-string err
) proc
)
795 (delete-process proc
)))))
797 (defun server-goto-line-column (file-line-col)
798 "Move point to the position indicated in FILE-LINE-COL.
799 FILE-LINE-COL should be a three-element list as described in
800 `server-visit-files'."
801 (goto-line (nth 1 file-line-col
))
802 (let ((column-number (nth 2 file-line-col
)))
803 (if (> column-number
0)
804 (move-to-column (1- column-number
)))))
806 (defun server-visit-files (files client
&optional nowait
)
807 "Find FILES and return a list of buffers created.
808 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
809 CLIENT is the client that requested this operation.
810 NOWAIT non-nil means this client is not waiting for the results,
811 so don't mark these buffers specially, just visit them normally."
812 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
813 (let ((last-nonmenu-event t
) client-record
)
814 ;; Restore the current buffer afterward, but not using save-excursion,
815 ;; because we don't want to save point in this buffer
816 ;; if it happens to be one of those specified by the server.
819 ;; If there is an existing buffer modified or the file is
820 ;; modified, revert it. If there is an existing buffer with
821 ;; deleted file, offer to write it.
822 (let* ((filen (car file
))
823 (obuf (get-file-buffer filen
)))
824 (push filen file-name-history
)
825 (if (and obuf
(set-buffer obuf
))
827 (cond ((file-exists-p filen
)
828 (if (not (verify-visited-file-modtime obuf
))
829 (revert-buffer t nil
)))
832 (concat "File no longer exists: " filen
833 ", write buffer to file? "))
834 (write-file filen
))))
835 (setq server-existing-buffer t
)
836 (server-goto-line-column file
))
837 (set-buffer (find-file-noselect filen
))
838 (server-goto-line-column file
)
839 (run-hooks 'server-visit-hook
)))
841 ;; When the buffer is killed, inform the clients.
842 (add-hook 'kill-buffer-hook
'server-kill-buffer nil t
)
843 (push (car client
) server-buffer-clients
))
844 (push (current-buffer) client-record
)))
848 (nconc (server-client-get client
'buffers
) client-record
)))
851 (defun server-buffer-done (buffer &optional for-killing
)
852 "Mark BUFFER as \"done\" for its client(s).
853 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
854 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
855 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
857 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
858 (let ((next-buffer nil
)
860 (dolist (client server-clients
)
861 (let ((buffers (server-client-get client
'buffers
)))
863 (setq next-buffer
(nth 1 (memq buffer buffers
))))
864 (when buffers
; Ignore bufferless clients.
865 (setq buffers
(delq buffer buffers
))
866 ;; Delete all dead buffers from CLIENT.
869 (not (buffer-live-p b
))
870 (setq buffers
(delq b buffers
))))
871 (server-client-set client
'buffers buffers
)
872 ;; If client now has no pending buffers,
873 ;; tell it that it is done, and forget it entirely.
875 (server-log "Close" client
)
876 (server-delete-client client
)))))
877 (if (and (bufferp buffer
) (buffer-name buffer
))
878 ;; We may or may not kill this buffer;
879 ;; if we do, do not call server-buffer-done recursively
880 ;; from kill-buffer-hook.
881 (let ((server-kill-buffer-running t
))
882 (with-current-buffer buffer
883 (setq server-buffer-clients nil
)
884 (run-hooks 'server-done-hook
))
885 ;; Notice whether server-done-hook killed the buffer.
886 (if (null (buffer-name buffer
))
888 ;; Don't bother killing or burying the buffer
889 ;; when we are called from kill-buffer.
891 (when (and (not killed
)
892 server-kill-new-buffers
893 (with-current-buffer buffer
894 (not server-existing-buffer
)))
897 (kill-buffer buffer
))
899 (if (server-temp-file-p buffer
)
903 (bury-buffer buffer
)))))))
904 (list next-buffer killed
)))
906 (defun server-temp-file-p (&optional buffer
)
907 "Return non-nil if BUFFER contains a file considered temporary.
908 These are files whose names suggest they are repeatedly
909 reused to pass information to another program.
911 The variable `server-temp-file-regexp' controls which filenames
912 are considered temporary."
913 (and (buffer-file-name buffer
)
914 (string-match server-temp-file-regexp
(buffer-file-name buffer
))))
916 (defun server-done ()
917 "Offer to save current buffer, mark it as \"done\" for clients.
918 This kills or buries the buffer, then returns a list
919 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
920 as a suggestion for what to select next, or nil.
921 KILLED is t if we killed BUFFER, which happens if it was created
922 specifically for the clients and did not exist before their request for it."
923 (when server-buffer-clients
924 (if (server-temp-file-p)
925 ;; For a temp file, save, and do make a non-numeric backup
926 ;; (unless make-backup-files is nil).
927 (let ((version-control nil
)
928 (buffer-backed-up nil
))
930 (if (and (buffer-modified-p)
932 (y-or-n-p (concat "Save file " buffer-file-name
"? ")))
934 (server-buffer-done (current-buffer))))
936 ;; Ask before killing a server buffer.
937 ;; It was suggested to release its client instead,
938 ;; but I think that is dangerous--the client would proceed
939 ;; using whatever is on disk in that file. -- rms.
940 (defun server-kill-buffer-query-function ()
941 "Ask before killing a server buffer."
942 (or (not server-buffer-clients
)
944 (dolist (proc server-buffer-clients res
)
945 (let ((client (server-client proc
)))
946 (when (and client
(eq (process-status proc
) 'open
))
948 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
949 (buffer-name (current-buffer))))))
951 (defun server-kill-emacs-query-function ()
952 "Ask before exiting Emacs it has live clients."
953 (or (not server-clients
)
955 (dolist (client server-clients live-client
)
956 (if (memq t
(mapcar 'buffer-live-p
(server-client-get
958 (setq live-client t
))))
959 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
961 (defvar server-kill-buffer-running nil
962 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
964 (defun server-kill-buffer ()
965 "Remove the current buffer from its clients' buffer list.
966 Designed to be added to `kill-buffer-hook'."
967 ;; Prevent infinite recursion if user has made server-done-hook
969 (or server-kill-buffer-running
970 (and server-buffer-clients
971 (let ((server-kill-buffer-running t
))
973 (server-buffer-done (current-buffer) t
))))))
975 (defun server-edit (&optional arg
)
976 "Switch to next server editing buffer; say \"Done\" for current buffer.
977 If a server buffer is current, it is marked \"done\" and optionally saved.
978 The buffer is also killed if it did not exist before the clients asked for it.
979 When all of a client's buffers are marked as \"done\", the client is notified.
981 Temporary files such as MH <draft> files are always saved and backed up,
982 no questions asked. (The variable `make-backup-files', if nil, still
983 inhibits a backup; you can set it locally in a particular buffer to
984 prevent a backup for it.) The variable `server-temp-file-regexp' controls
985 which filenames are considered temporary.
987 If invoked with a prefix argument, or if there is no server process running,
988 starts server process and that is all. Invoked by \\[server-edit]."
992 (memq (process-status server-process
) '(signal exit
)))
994 (apply 'server-switch-buffer
(server-done))))
996 (defun server-switch-buffer (&optional next-buffer killed-one
)
997 "Switch to another buffer, preferably one that has a client.
998 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1000 KILLED-ONE is t in a recursive call if we have already killed one
1001 temp-file server buffer. This means we should avoid the final
1002 \"switch to some other buffer\" since we've already effectively
1004 (if (null next-buffer
)
1006 (let ((rest server-clients
))
1007 (while (and rest
(not next-buffer
))
1008 (let ((client (car rest
)))
1009 ;; Only look at frameless clients.
1010 (when (not (server-client-get client
'frame
))
1011 (setq next-buffer
(car (server-client-get client
'buffers
))))
1012 (setq rest
(cdr rest
)))))
1013 (and next-buffer
(server-switch-buffer next-buffer killed-one
))
1014 (unless (or next-buffer killed-one
(window-dedicated-p (selected-window)))
1015 ;; (switch-to-buffer (other-buffer))
1016 (message "No server buffers remain to edit")))
1017 (if (not (buffer-live-p next-buffer
))
1018 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1019 ;; and try the next surviving server buffer.
1020 (apply 'server-switch-buffer
(server-buffer-done next-buffer
))
1021 ;; OK, we know next-buffer is live, let's display and select it.
1022 (if (functionp server-window
)
1023 (funcall server-window next-buffer
)
1024 (let ((win (get-buffer-window next-buffer
0)))
1025 (if (and win
(not server-window
))
1026 ;; The buffer is already displayed: just reuse the window.
1027 (let ((frame (window-frame win
)))
1028 (if (eq (frame-visible-p frame
) 'icon
)
1029 (raise-frame frame
))
1031 (set-buffer next-buffer
))
1032 ;; Otherwise, let's find an appropriate window.
1033 (cond ((and (windowp server-window
)
1034 (window-live-p server-window
))
1035 (select-window server-window
))
1036 ((framep server-window
)
1037 (if (not (frame-live-p server-window
))
1038 (setq server-window
(make-frame)))
1039 (select-window (frame-selected-window server-window
))))
1040 (if (window-minibuffer-p (selected-window))
1041 (select-window (next-window nil
'nomini
0)))
1042 ;; Move to a non-dedicated window, if we have one.
1043 (when (window-dedicated-p (selected-window))
1045 (get-window-with-predicate
1047 (and (not (window-dedicated-p w
))
1048 (equal (frame-terminal (window-frame w
))
1049 (frame-terminal (selected-frame)))))
1050 'nomini
'visible
(selected-window))))
1052 (switch-to-buffer next-buffer
)
1053 ;; After all the above, we might still have ended up with
1054 ;; a minibuffer/dedicated-window (if there's no other).
1055 (error (pop-to-buffer next-buffer
)))))))))
1058 (defun server-save-buffers-kill-terminal (proc &optional arg
)
1059 "Offer to save each buffer, then kill PROC.
1061 With prefix arg, silently save all file-visiting buffers, then kill.
1063 If emacsclient was started with a list of filenames to edit, then
1064 only these files will be asked to be saved."
1065 (let ((buffers (server-client-get proc
'buffers
)))
1066 ;; If client is bufferless, emulate a normal Emacs session
1067 ;; exit and offer to save all buffers. Otherwise, offer to
1068 ;; save only the buffers belonging to the client.
1069 (save-some-buffers arg
1071 (lambda () (memq (current-buffer) buffers
))
1073 (server-delete-client proc
)))
1075 (define-key ctl-x-map
"#" 'server-edit
)
1077 (defun server-unload-hook ()
1078 "Unload the server library."
1080 (remove-hook 'suspend-tty-functions
'server-handle-suspend-tty
)
1081 (remove-hook 'delete-frame-functions
'server-handle-delete-frame
)
1082 (remove-hook 'kill-buffer-query-functions
'server-kill-buffer-query-function
)
1083 (remove-hook 'kill-emacs-query-functions
'server-kill-emacs-query-function
)
1084 (remove-hook 'kill-buffer-hook
'server-kill-buffer
))
1086 (add-hook 'server-unload-hook
'server-unload-hook
)
1090 ;;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1091 ;;; server.el ends here