Add comment.
[bpt/emacs.git] / lisp / server.el
1 ;;; server.el --- Lisp code for GNU Emacs running as server process
2
3 ;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 ;; 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
7 ;; Maintainer: FSF
8 ;; Keywords: processes
9
10 ;; Changes by peck@sun.com and by rms.
11 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
12
13 ;; This file is part of GNU Emacs.
14
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 of the License, or
18 ;; (at your option) any later version.
19
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.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27
28 ;;; Commentary:
29
30 ;; This Lisp code is run in Emacs when it is to operate as
31 ;; a server for other processes.
32
33 ;; Load this library and do M-x server-edit to enable Emacs as a server.
34 ;; Emacs opens up a socket for communication with clients. If there are no
35 ;; client buffers to edit, server-edit acts like (switch-to-buffer
36 ;; (other-buffer))
37
38 ;; When some other program runs "the editor" to edit a file,
39 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
40 ;; This program transmits the file names to Emacs through
41 ;; the server subprocess, and Emacs visits them and lets you edit them.
42
43 ;; Note that any number of clients may dispatch files to Emacs to be edited.
44
45 ;; When you finish editing a Server buffer, again call server-edit
46 ;; to mark that buffer as done for the client and switch to the next
47 ;; Server buffer. When all the buffers for a client have been edited
48 ;; and exited with server-edit, the client "editor" will return
49 ;; to the program that invoked it.
50
51 ;; Your editing commands and Emacs's display output go to and from
52 ;; the terminal in the usual way. Thus, server operation is possible
53 ;; only when Emacs can talk to the terminal at the time you invoke
54 ;; the client. This is possible in four cases:
55
56 ;; 1. On a window system, where Emacs runs in one window and the
57 ;; program that wants to use "the editor" runs in another.
58
59 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
60 ;; program that wants to use "the editor" runs on another.
61
62 ;; 3. When the program that wants to use "the editor" is running
63 ;; as a subprocess of Emacs.
64
65 ;; 4. On a system with job control, when Emacs is suspended, the program
66 ;; that wants to use "the editor" will stop and display
67 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
68 ;; brought into the foreground for editing. When done editing, Emacs is
69 ;; suspended again, and the client program is brought into the foreground.
70
71 ;; The buffer local variable "server-buffer-clients" lists
72 ;; the clients who are waiting for this buffer to be edited.
73 ;; The global variable "server-clients" lists all the waiting clients,
74 ;; and which files are yet to be edited for each.
75
76 ;; Todo:
77
78 ;; - handle command-line-args-left.
79 ;; - move most of the args processing and decision making from emacsclient.c
80 ;; to here.
81 ;; - fix up handling of the client's environment (place it in the terminal?).
82
83 ;;; Code:
84
85 (eval-when-compile (require 'cl))
86
87 (defgroup server nil
88 "Emacs running as a server process."
89 :group 'external)
90
91 (defcustom server-use-tcp nil
92 "If non-nil, use TCP sockets instead of local sockets."
93 :set #'(lambda (sym val)
94 (unless (featurep 'make-network-process '(:family local))
95 (setq val t)
96 (unless load-in-progress
97 (message "Local sockets unsupported, using TCP sockets")))
98 (when val (random t))
99 (set-default sym val))
100 :group 'server
101 :type 'boolean
102 :version "22.1")
103
104 (defcustom server-host nil
105 "The name or IP address to use as host address of the server process.
106 If set, the server accepts remote connections; otherwise it is local."
107 :group 'server
108 :type '(choice
109 (string :tag "Name or IP address")
110 (const :tag "Local" nil))
111 :version "22.1")
112 (put 'server-host 'risky-local-variable t)
113
114 (defcustom server-auth-dir (locate-user-emacs-file "server/")
115 "Directory for server authentication files."
116 :group 'server
117 :type 'directory
118 :version "22.1")
119 (put 'server-auth-dir 'risky-local-variable t)
120
121 (defcustom server-raise-frame t
122 "If non-nil, raise frame when switching to a buffer."
123 :group 'server
124 :type 'boolean
125 :version "22.1")
126
127 (defcustom server-visit-hook nil
128 "Hook run when visiting a file for the Emacs server."
129 :group 'server
130 :type 'hook)
131
132 (defcustom server-switch-hook nil
133 "Hook run when switching to a buffer for the Emacs server."
134 :group 'server
135 :type 'hook)
136
137 (defcustom server-done-hook nil
138 "Hook run when done editing a buffer for the Emacs server."
139 :group 'server
140 :type 'hook)
141
142 (defvar server-process nil
143 "The current server process.")
144
145 (defvar server-clients nil
146 "List of current server clients.
147 Each element is a process.")
148
149 (defvar server-buffer-clients nil
150 "List of client processes requesting editing of current buffer.")
151 (make-variable-buffer-local 'server-buffer-clients)
152 ;; Changing major modes should not erase this local.
153 (put 'server-buffer-clients 'permanent-local t)
154
155 (defcustom server-window nil
156 "Specification of the window to use for selecting Emacs server buffers.
157 If nil, use the selected window.
158 If it is a function, it should take one argument (a buffer) and
159 display and select it. A common value is `pop-to-buffer'.
160 If it is a window, use that.
161 If it is a frame, use the frame's selected window.
162
163 It is not meaningful to set this to a specific frame or window with Custom.
164 Only programs can do so."
165 :group 'server
166 :version "22.1"
167 :type '(choice (const :tag "Use selected window"
168 :match (lambda (widget value)
169 (not (functionp value)))
170 nil)
171 (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
172 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
173 (function :tag "Other function")))
174
175 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
176 "Regexp matching names of temporary files.
177 These are deleted and reused after each edit by the programs that
178 invoke the Emacs server."
179 :group 'server
180 :type 'regexp)
181
182 (defcustom server-kill-new-buffers t
183 "Whether to kill buffers when done with them.
184 If non-nil, kill a buffer unless it already existed before editing
185 it with the Emacs server. If nil, kill only buffers as specified by
186 `server-temp-file-regexp'.
187 Please note that only buffers that still have a client are killed,
188 i.e. buffers visited with \"emacsclient --no-wait\" are never killed
189 in this way."
190 :group 'server
191 :type 'boolean
192 :version "21.1")
193
194 (or (assq 'server-buffer-clients minor-mode-alist)
195 (push '(server-buffer-clients " Server") minor-mode-alist))
196
197 (defvar server-existing-buffer nil
198 "Non-nil means the buffer existed before the server was asked to visit it.
199 This means that the server should not kill the buffer when you say you
200 are done with it in the server.")
201 (make-variable-buffer-local 'server-existing-buffer)
202
203 (defcustom server-name "server"
204 "The name of the Emacs server, if this Emacs process creates one.
205 The command `server-start' makes use of this. It should not be
206 changed while a server is running."
207 :group 'server
208 :type 'string
209 :version "23.1")
210
211 ;; We do not use `temporary-file-directory' here, because emacsclient
212 ;; does not read the init file.
213 (defvar server-socket-dir
214 (and (featurep 'make-network-process '(:family local))
215 (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
216 "The directory in which to place the server socket.
217 If local sockets are not supported, this is nil.")
218
219 (defun server-clients-with (property value)
220 "Return a list of clients with PROPERTY set to VALUE."
221 (let (result)
222 (dolist (proc server-clients result)
223 (when (equal value (process-get proc property))
224 (push proc result)))))
225
226 (defun server-add-client (proc)
227 "Create a client for process PROC, if it doesn't already have one.
228 New clients have no properties."
229 (add-to-list 'server-clients proc))
230
231 (defmacro server-with-environment (env vars &rest body)
232 "Evaluate BODY with environment variables VARS set to those in ENV.
233 The environment variables are then restored to their previous values.
234
235 VARS should be a list of strings.
236 ENV should be in the same format as `process-environment'."
237 (declare (indent 2))
238 (let ((var (make-symbol "var"))
239 (value (make-symbol "value")))
240 `(let ((process-environment process-environment))
241 (dolist (,var ,vars)
242 (let ((,value (getenv-internal ,var ,env)))
243 (push (if (null ,value)
244 ,var
245 (concat ,var "=" ,value))
246 process-environment)))
247 (progn ,@body))))
248
249 (defun server-delete-client (proc &optional noframe)
250 "Delete PROC, including its buffers, terminals and frames.
251 If NOFRAME is non-nil, let the frames live.
252 Updates `server-clients'."
253 (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
254 ;; Force a new lookup of client (prevents infinite recursion).
255 (when (memq proc server-clients)
256 (let ((buffers (process-get proc 'buffers)))
257
258 ;; Kill the client's buffers.
259 (dolist (buf buffers)
260 (when (buffer-live-p buf)
261 (with-current-buffer buf
262 ;; Kill the buffer if necessary.
263 (when (and (equal server-buffer-clients
264 (list proc))
265 (or (and server-kill-new-buffers
266 (not server-existing-buffer))
267 (server-temp-file-p))
268 (not (buffer-modified-p)))
269 (let (flag)
270 (unwind-protect
271 (progn (setq server-buffer-clients nil)
272 (kill-buffer (current-buffer))
273 (setq flag t))
274 (unless flag
275 ;; Restore clients if user pressed C-g in `kill-buffer'.
276 (setq server-buffer-clients (list proc)))))))))
277
278 ;; Delete the client's frames.
279 (unless noframe
280 (dolist (frame (frame-list))
281 (when (and (frame-live-p frame)
282 (equal proc (frame-parameter frame 'client)))
283 ;; Prevent `server-handle-delete-frame' from calling us
284 ;; recursively.
285 (set-frame-parameter frame 'client nil)
286 (delete-frame frame))))
287
288 (setq server-clients (delq proc server-clients))
289
290 ;; Delete the client's tty.
291 (let ((terminal (process-get proc 'terminal)))
292 ;; Only delete the terminal if it is non-nil.
293 (when (and terminal (eq (terminal-live-p terminal) t))
294 (delete-terminal terminal)))
295
296 ;; Delete the client's process.
297 (if (eq (process-status proc) 'open)
298 (delete-process proc))
299
300 (server-log "Deleted" proc))))
301
302 (defvar server-log-time-function 'current-time-string
303 "Function to generate timestamps for `server-buffer'.")
304
305 (defconst server-buffer " *server*"
306 "Buffer used internally by Emacs's server.
307 One use is to log the I/O for debugging purposes (see `server-log'),
308 the other is to provide a current buffer in which the process filter can
309 safely let-bind buffer-local variables like `default-directory'.")
310
311 (defvar server-log nil
312 "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
313
314 (defun server-log (string &optional client)
315 "If `server-log' is non-nil, log STRING to `server-buffer'.
316 If CLIENT is non-nil, add a description of it to the logged message."
317 (when server-log
318 (with-current-buffer (get-buffer-create server-buffer)
319 (goto-char (point-max))
320 (insert (funcall server-log-time-function)
321 (cond
322 ((null client) " ")
323 ((listp client) (format " %s: " (car client)))
324 (t (format " %s: " client)))
325 string)
326 (or (bolp) (newline)))))
327
328 (defun server-sentinel (proc msg)
329 "The process sentinel for Emacs server connections."
330 ;; If this is a new client process, set the query-on-exit flag to nil
331 ;; for this process (it isn't inherited from the server process).
332 (when (and (eq (process-status proc) 'open)
333 (process-query-on-exit-flag proc))
334 (set-process-query-on-exit-flag proc nil))
335 ;; Delete the associated connection file, if applicable.
336 ;; Although there's no 100% guarantee that the file is owned by the
337 ;; running Emacs instance, server-start uses server-running-p to check
338 ;; for possible servers before doing anything, so it *should* be ours.
339 (and (process-contact proc :server)
340 (eq (process-status proc) 'closed)
341 (ignore-errors (delete-file (process-get proc :server-file))))
342 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
343 (server-delete-client proc))
344
345 (defun server-select-display (display)
346 ;; If the current frame is on `display' we're all set.
347 ;; Similarly if we are unable to open frames on other displays, there's
348 ;; nothing more we can do.
349 (unless (or (not (fboundp 'make-frame-on-display))
350 (equal (frame-parameter (selected-frame) 'display) display))
351 ;; Otherwise, look for an existing frame there and select it.
352 (dolist (frame (frame-list))
353 (when (equal (frame-parameter frame 'display) display)
354 (select-frame frame)))
355 ;; If there's no frame on that display yet, create and select one.
356 (unless (equal (frame-parameter (selected-frame) 'display) display)
357 (let* ((buffer (generate-new-buffer " *server-dummy*"))
358 (frame (make-frame-on-display
359 display
360 ;; Make it display (and remember) some dummy buffer, so
361 ;; we can detect later if the frame is in use or not.
362 `((server-dummy-buffer . ,buffer)
363 ;; This frame may be deleted later (see
364 ;; server-unselect-display) so we want it to be as
365 ;; unobtrusive as possible.
366 (visibility . nil)))))
367 (select-frame frame)
368 (set-window-buffer (selected-window) buffer)
369 frame))))
370
371 (defun server-unselect-display (frame)
372 (when (frame-live-p frame)
373 ;; If the temporary frame is in use (displays something real), make it
374 ;; visible. If not (which can happen if the user's customizations call
375 ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
376 ;; the last real frame is deleted.
377 (if (and (eq (frame-first-window frame)
378 (next-window (frame-first-window frame) 'nomini))
379 (eq (window-buffer (frame-first-window frame))
380 (frame-parameter frame 'server-dummy-buffer)))
381 ;; The temp frame still only shows one buffer, and that is the
382 ;; internal temp buffer.
383 (delete-frame frame)
384 (set-frame-parameter frame 'visibility t))
385 (kill-buffer (frame-parameter frame 'server-dummy-buffer))
386 (set-frame-parameter frame 'server-dummy-buffer nil)))
387
388 (defun server-handle-delete-frame (frame)
389 "Delete the client connection when the emacsclient frame is deleted.
390 \(To be used from `delete-frame-functions'.)"
391 (let ((proc (frame-parameter frame 'client)))
392 (when (and (frame-live-p frame)
393 proc
394 ;; See if this is the last frame for this client.
395 (>= 1 (let ((frame-num 0))
396 (dolist (f (frame-list))
397 (when (eq proc (frame-parameter f 'client))
398 (setq frame-num (1+ frame-num))))
399 frame-num)))
400 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
401 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
402
403 (defun server-handle-suspend-tty (terminal)
404 "Notify the emacsclient process to suspend itself when its tty device is suspended."
405 (dolist (proc (server-clients-with 'terminal terminal))
406 (server-log (format "server-handle-suspend-tty, terminal %s" terminal) proc)
407 (condition-case err
408 (server-send-string proc "-suspend \n")
409 (file-error ;The pipe/socket was closed.
410 (ignore-errors (server-delete-client proc))))))
411
412 (defun server-unquote-arg (arg)
413 "Remove &-quotation from ARG.
414 See `server-quote-arg' and `server-process-filter'."
415 (replace-regexp-in-string
416 "&." (lambda (s)
417 (case (aref s 1)
418 (?& "&")
419 (?- "-")
420 (?n "\n")
421 (t " ")))
422 arg t t))
423
424 (defun server-quote-arg (arg)
425 "In ARG, insert a & before each &, each space, each newline, and -.
426 Change spaces to underscores, too, so that the return value never
427 contains a space.
428
429 See `server-unquote-arg' and `server-process-filter'."
430 (replace-regexp-in-string
431 "[-&\n ]" (lambda (s)
432 (case (aref s 0)
433 (?& "&&")
434 (?- "&-")
435 (?\n "&n")
436 (?\s "&_")))
437 arg t t))
438
439 (defun server-send-string (proc string)
440 "A wrapper around `process-send-string' for logging."
441 (server-log (concat "Sent " string) proc)
442 (process-send-string proc string))
443
444 (defun server-ensure-safe-dir (dir)
445 "Make sure DIR is a directory with no race-condition issues.
446 Creates the directory if necessary and makes sure:
447 - there's no symlink involved
448 - it's owned by us
449 - it's not readable/writable by anybody else."
450 (setq dir (directory-file-name dir))
451 (let ((attrs (file-attributes dir)))
452 (unless attrs
453 (letf (((default-file-modes) ?\700)) (make-directory dir t))
454 (setq attrs (file-attributes dir)))
455 ;; Check that it's safe for use.
456 (unless (and (eq t (car attrs)) (eql (nth 2 attrs) (user-uid))
457 (or (eq system-type 'windows-nt)
458 (zerop (logand ?\077 (file-modes dir)))))
459 (error "The directory %s is unsafe" dir))))
460
461 ;;;###autoload
462 (defun server-start (&optional leave-dead)
463 "Allow this Emacs process to be a server for client processes.
464 This starts a server communications subprocess through which
465 client \"editors\" can send your editing commands to this Emacs
466 job. To use the server, set up the program `emacsclient' in the
467 Emacs distribution as your standard \"editor\".
468
469 Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
470 kill any existing server communications subprocess.
471
472 If a server is already running, the server is not started.
473 To force-start a server, do \\[server-force-delete] and then
474 \\[server-start]."
475 (interactive "P")
476 (when (or (not server-clients)
477 ;; Ask the user before deleting existing clients---except
478 ;; when we can't get user input, which may happen when
479 ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
480 (if (and (daemonp)
481 (null (cdr (frame-list)))
482 (eq (selected-frame) terminal-frame))
483 leave-dead
484 (yes-or-no-p
485 "The current server still has clients; delete them? ")))
486 (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
487 (server-file (expand-file-name server-name server-dir)))
488 (when server-process
489 ;; kill it dead!
490 (ignore-errors (delete-process server-process)))
491 ;; Delete the socket files made by previous server invocations.
492 (if (not (eq t (server-running-p server-name)))
493 ;; Remove any leftover socket or authentication file
494 (ignore-errors (delete-file server-file))
495 (setq server-mode nil) ;; already set by the minor mode code
496 (display-warning 'server
497 (format "Emacs server named %S already running" server-name)
498 :warning)
499 (setq leave-dead t))
500 ;; If this Emacs already had a server, clear out associated status.
501 (while server-clients
502 (server-delete-client (car server-clients)))
503 ;; Now any previous server is properly stopped.
504 (if leave-dead
505 (progn
506 (unless (eq t leave-dead) (server-log (message "Server stopped")))
507 (setq server-process nil))
508 ;; Make sure there is a safe directory in which to place the socket.
509 (server-ensure-safe-dir server-dir)
510 (when server-process
511 (server-log (message "Restarting server")))
512 (letf (((default-file-modes) ?\700))
513 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
514 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
515 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
516 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
517 (add-hook 'kill-emacs-hook (lambda () (server-mode -1))) ;Cleanup upon exit.
518 (setq server-process
519 (apply #'make-network-process
520 :name server-name
521 :server t
522 :noquery t
523 :sentinel 'server-sentinel
524 :filter 'server-process-filter
525 ;; We must receive file names without being decoded.
526 ;; Those are decoded by server-process-filter according
527 ;; to file-name-coding-system. Also don't get
528 ;; confused by CRs since we don't quote them.
529 :coding 'raw-text-unix
530 ;; The other args depend on the kind of socket used.
531 (if server-use-tcp
532 (list :family nil
533 :service t
534 :host (or server-host 'local)
535 :plist '(:authenticated nil))
536 (list :family 'local
537 :service server-file
538 :plist '(:authenticated t)))))
539 (unless server-process (error "Could not start server process"))
540 (process-put server-process :server-file server-file)
541 (when server-use-tcp
542 (let ((auth-key
543 (loop
544 ;; The auth key is a 64-byte string of random chars in the
545 ;; range `!'..`~'.
546 for i below 64
547 collect (+ 33 (random 94)) into auth
548 finally return (concat auth))))
549 (process-put server-process :auth-key auth-key)
550 (with-temp-file server-file
551 (set-buffer-multibyte nil)
552 (setq buffer-file-coding-system 'no-conversion)
553 (insert (format-network-address
554 (process-contact server-process :local))
555 " " (int-to-string (emacs-pid))
556 "\n" auth-key)))))))))
557
558 ;;;###autoload
559 (defun server-force-delete (&optional name)
560 "Unconditionally delete connection file for server NAME.
561 If server is running, it is first stopped.
562 NAME defaults to `server-name'. With argument, ask for NAME."
563 (interactive
564 (list (if current-prefix-arg
565 (read-string "Server name: " nil nil server-name))))
566 (when server-mode (with-temp-message nil (server-mode -1)))
567 (let ((file (expand-file-name (or name server-name)
568 (if server-use-tcp
569 server-auth-dir
570 server-socket-dir))))
571 (condition-case nil
572 (progn
573 (delete-file file)
574 (message "Connection file %S deleted" file))
575 (file-error
576 (message "No connection file %S" file)))))
577
578 (defun server-running-p (&optional name)
579 "Test whether server NAME is running.
580
581 Return values:
582 nil the server is definitely not running.
583 t the server seems to be running.
584 something else we cannot determine whether it's running without using
585 commands which may have to wait for a long time."
586 (unless name (setq name server-name))
587 (condition-case nil
588 (if server-use-tcp
589 (with-temp-buffer
590 (insert-file-contents-literally (expand-file-name name server-auth-dir))
591 (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
592 (assq 'comm
593 (system-process-attributes
594 (string-to-number (match-string 1))))
595 t)
596 :other))
597 (delete-process
598 (make-network-process
599 :name "server-client-test" :family 'local :server nil :noquery t
600 :service (expand-file-name name server-socket-dir)))
601 t)
602 (file-error nil)))
603
604 ;;;###autoload
605 (define-minor-mode server-mode
606 "Toggle Server mode.
607 With ARG, turn Server mode on if ARG is positive, off otherwise.
608 Server mode runs a process that accepts commands from the
609 `emacsclient' program. See `server-start' and Info node `Emacs server'."
610 :global t
611 :group 'server
612 :version "22.1"
613 ;; Fixme: Should this check for an existing server socket and do
614 ;; nothing if there is one (for multiple Emacs sessions)?
615 (server-start (not server-mode)))
616 \f
617 (defun server-eval-and-print (expr proc)
618 "Eval EXPR and send the result back to client PROC."
619 (let ((v (eval (car (read-from-string expr)))))
620 (when (and v proc)
621 (with-temp-buffer
622 (let ((standard-output (current-buffer)))
623 (pp v)
624 (let ((text (buffer-substring-no-properties
625 (point-min) (point-max))))
626 (server-send-string
627 proc (format "-print %s\n"
628 (server-quote-arg text)))))))))
629
630 (defun server-create-tty-frame (tty type proc)
631 (unless tty
632 (error "Invalid terminal device"))
633 (unless type
634 (error "Invalid terminal type"))
635 (add-to-list 'frame-inherited-parameters 'client)
636 (let ((frame
637 (server-with-environment (process-get proc 'env)
638 '("LANG" "LC_CTYPE" "LC_ALL"
639 ;; For tgetent(3); list according to ncurses(3).
640 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
641 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
642 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
643 "TERMINFO_DIRS" "TERMPATH"
644 ;; rxvt wants these
645 "COLORFGBG" "COLORTERM")
646 (make-frame `((window-system . nil)
647 (tty . ,tty)
648 (tty-type . ,type)
649 ;; Ignore nowait here; we always need to
650 ;; clean up opened ttys when the client dies.
651 (client . ,proc)
652 ;; This is a leftover from an earlier
653 ;; attempt at making it possible for process
654 ;; run in the server process to use the
655 ;; environment of the client process.
656 ;; It has no effect now and to make it work
657 ;; we'd need to decide how to make
658 ;; process-environment interact with client
659 ;; envvars, and then to change the
660 ;; C functions `child_setup' and
661 ;; `getenv_internal' accordingly.
662 (environment . ,(process-get proc 'env)))))))
663
664 ;; ttys don't use the `display' parameter, but callproc.c does to set
665 ;; the DISPLAY environment on subprocesses.
666 (set-frame-parameter frame 'display
667 (getenv-internal "DISPLAY" (process-get proc 'env)))
668 (select-frame frame)
669 (process-put proc 'frame frame)
670 (process-put proc 'terminal (frame-terminal frame))
671
672 ;; Display *scratch* by default.
673 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
674
675 ;; Reply with our pid.
676 (server-send-string proc (concat "-emacs-pid "
677 (number-to-string (emacs-pid)) "\n"))
678 frame))
679
680 (defun server-create-window-system-frame (display nowait proc)
681 (add-to-list 'frame-inherited-parameters 'client)
682 (if (not (fboundp 'make-frame-on-display))
683 (progn
684 ;; This emacs does not support X.
685 (server-log "Window system unsupported" proc)
686 (server-send-string proc "-window-system-unsupported \n")
687 nil)
688 ;; Flag frame as client-created, but use a dummy client.
689 ;; This will prevent the frame from being deleted when
690 ;; emacsclient quits while also preventing
691 ;; `server-save-buffers-kill-terminal' from unexpectedly
692 ;; killing emacs on that frame.
693 (let* ((params `((client . ,(if nowait 'nowait proc))
694 ;; This is a leftover, see above.
695 (environment . ,(process-get proc 'env))))
696 (frame (make-frame-on-display
697 (or display
698 (frame-parameter nil 'display)
699 (getenv "DISPLAY")
700 (error "Please specify display"))
701 params)))
702 (server-log (format "%s created" frame) proc)
703 (select-frame frame)
704 (process-put proc 'frame frame)
705 (process-put proc 'terminal (frame-terminal frame))
706
707 ;; Display *scratch* by default.
708 (switch-to-buffer (get-buffer-create "*scratch*") 'norecord)
709 frame)))
710
711 (defun server-goto-toplevel (proc)
712 (condition-case nil
713 ;; If we're running isearch, we must abort it to allow Emacs to
714 ;; display the buffer and switch to it.
715 (dolist (buffer (buffer-list))
716 (with-current-buffer buffer
717 (when (bound-and-true-p isearch-mode)
718 (isearch-cancel))))
719 ;; Signaled by isearch-cancel.
720 (quit (message nil)))
721 (when (> (recursion-depth) 0)
722 ;; We're inside a minibuffer already, so if the emacs-client is trying
723 ;; to open a frame on a new display, we might end up with an unusable
724 ;; frame because input from that display will be blocked (until exiting
725 ;; the minibuffer). Better exit this minibuffer right away.
726 ;; Similarly with recursive-edits such as the splash screen.
727 (run-with-timer 0 nil (lexical-let ((proc proc))
728 (lambda () (server-execute-continuation proc))))
729 (top-level)))
730
731 ;; We use various special properties on process objects:
732 ;; - `env' stores the info about the environment of the emacsclient process.
733 ;; - `continuation' is a no-arg function that we need to execute. It contains
734 ;; commands we wanted to execute in some earlier invocation of the process
735 ;; filter but that we somehow were unable to process at that time
736 ;; (e.g. because we first need to throw to the toplevel).
737
738 (defun server-execute-continuation (proc)
739 (let ((continuation (process-get proc 'continuation)))
740 (process-put proc 'continuation nil)
741 (if continuation (ignore-errors (funcall continuation)))))
742
743 (defun* server-process-filter (proc string)
744 "Process a request from the server to edit some files.
745 PROC is the server process. STRING consists of a sequence of
746 commands prefixed by a dash. Some commands have arguments;
747 these are &-quoted and need to be decoded by `server-unquote-arg'.
748 The filter parses and executes these commands.
749
750 To illustrate the protocol, here is an example command that
751 emacsclient sends to create a new X frame (note that the whole
752 sequence is sent on a single line):
753
754 -env HOME=/home/lorentey
755 -env DISPLAY=:0.0
756 ... lots of other -env commands
757 -display :0.0
758 -window-system
759
760 The following commands are accepted by the server:
761
762 `-auth AUTH-STRING'
763 Authenticate the client using the secret authentication string
764 AUTH-STRING.
765
766 `-env NAME=VALUE'
767 An environment variable on the client side.
768
769 `-dir DIRNAME'
770 The current working directory of the client process.
771
772 `-current-frame'
773 Forbid the creation of new frames.
774
775 `-nowait'
776 Request that the next frame created should not be
777 associated with this client.
778
779 `-display DISPLAY'
780 Set the display name to open X frames on.
781
782 `-position LINE[:COLUMN]'
783 Go to the given line and column number
784 in the next file opened.
785
786 `-file FILENAME'
787 Load the given file in the current frame.
788
789 `-eval EXPR'
790 Evaluate EXPR as a Lisp expression and return the
791 result in -print commands.
792
793 `-window-system'
794 Open a new X frame.
795
796 `-tty DEVICENAME TYPE'
797 Open a new tty frame at the client.
798
799 `-suspend'
800 Suspend this tty frame. The client sends this string in
801 response to SIGTSTP and SIGTTOU. The server must cease all I/O
802 on this tty until it gets a -resume command.
803
804 `-resume'
805 Resume this tty frame. The client sends this string when it
806 gets the SIGCONT signal and it is the foreground process on its
807 controlling tty.
808
809 `-ignore COMMENT'
810 Do nothing, but put the comment in the server log.
811 Useful for debugging.
812
813
814 The following commands are accepted by the client:
815
816 `-emacs-pid PID'
817 Describes the process id of the Emacs process;
818 used to forward window change signals to it.
819
820 `-window-system-unsupported'
821 Signals that the server does not support creating X frames;
822 the client must try again with a tty frame.
823
824 `-print STRING'
825 Print STRING on stdout. Used to send values
826 returned by -eval.
827
828 `-error DESCRIPTION'
829 Signal an error (but continue processing).
830
831 `-suspend'
832 Suspend this terminal, i.e., stop the client process.
833 Sent when the user presses C-z."
834 (server-log (concat "Received " string) proc)
835 ;; First things first: let's check the authentication
836 (unless (process-get proc :authenticated)
837 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
838 (equal (match-string 1 string) (process-get proc :auth-key)))
839 (progn
840 (setq string (substring string (match-end 0)))
841 (process-put proc :authenticated t)
842 (server-log "Authentication successful" proc))
843 (server-log "Authentication failed" proc)
844 (server-send-string
845 proc (concat "-error " (server-quote-arg "Authentication failed")))
846 (delete-process proc)
847 ;; We return immediately
848 (return-from server-process-filter)))
849 (let ((prev (process-get proc 'previous-string)))
850 (when prev
851 (setq string (concat prev string))
852 (process-put proc 'previous-string nil)))
853 (condition-case err
854 (progn
855 (server-add-client proc)
856 (if (not (string-match "\n" string))
857 ;; Save for later any partial line that remains.
858 (when (> (length string) 0)
859 (process-put proc 'previous-string string))
860
861 ;; In earlier versions of server.el (where we used an `emacsserver'
862 ;; process), there could be multiple lines. Nowadays this is not
863 ;; supported any more.
864 (assert (eq (match-end 0) (length string)))
865 (let ((request (substring string 0 (match-beginning 0)))
866 (coding-system (and default-enable-multibyte-characters
867 (or file-name-coding-system
868 default-file-name-coding-system)))
869 nowait ; t if emacsclient does not want to wait for us.
870 frame ; The frame that was opened for the client (if any).
871 display ; Open the frame on this display.
872 dontkill ; t if the client should not be killed.
873 commands
874 dir
875 use-current-frame
876 tty-name ;nil, `window-system', or the tty name.
877 tty-type ;string.
878 files
879 filepos
880 command-line-args-left
881 arg)
882 ;; Remove this line from STRING.
883 (setq string (substring string (match-end 0)))
884 (setq command-line-args-left
885 (mapcar 'server-unquote-arg (split-string request " " t)))
886 (while (setq arg (pop command-line-args-left))
887 (cond
888 ;; -version CLIENT-VERSION: obsolete at birth.
889 ((and (equal "-version" arg) command-line-args-left)
890 (pop command-line-args-left))
891
892 ;; -nowait: Emacsclient won't wait for a result.
893 ((equal "-nowait" arg) (setq nowait t))
894
895 ;; -current-frame: Don't create frames.
896 ((equal "-current-frame" arg) (setq use-current-frame t))
897
898 ;; -display DISPLAY:
899 ;; Open X frames on the given display instead of the default.
900 ((and (equal "-display" arg) command-line-args-left)
901 (setq display (pop command-line-args-left))
902 (if (zerop (length display)) (setq display nil)))
903
904 ;; -window-system: Open a new X frame.
905 ((equal "-window-system" arg)
906 (setq dontkill t)
907 (setq tty-name 'window-system))
908
909 ;; -resume: Resume a suspended tty frame.
910 ((equal "-resume" arg)
911 (lexical-let ((terminal (process-get proc 'terminal)))
912 (setq dontkill t)
913 (push (lambda ()
914 (when (eq (terminal-live-p terminal) t)
915 (resume-tty terminal)))
916 commands)))
917
918 ;; -suspend: Suspend the client's frame. (In case we
919 ;; get out of sync, and a C-z sends a SIGTSTP to
920 ;; emacsclient.)
921 ((equal "-suspend" arg)
922 (lexical-let ((terminal (process-get proc 'terminal)))
923 (setq dontkill t)
924 (push (lambda ()
925 (when (eq (terminal-live-p terminal) t)
926 (suspend-tty terminal)))
927 commands)))
928
929 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
930 ;; (The given comment appears in the server log.)
931 ((and (equal "-ignore" arg) command-line-args-left
932 (setq dontkill t)
933 (pop command-line-args-left)))
934
935 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
936 ((and (equal "-tty" arg)
937 (cdr command-line-args-left))
938 (setq tty-name (pop command-line-args-left)
939 tty-type (pop command-line-args-left)
940 dontkill (or dontkill
941 (not use-current-frame))))
942
943 ;; -position LINE[:COLUMN]: Set point to the given
944 ;; position in the next file.
945 ((and (equal "-position" arg)
946 command-line-args-left
947 (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
948 (car command-line-args-left)))
949 (setq arg (pop command-line-args-left))
950 (setq filepos
951 (cons (string-to-number (match-string 1 arg))
952 (string-to-number (or (match-string 2 arg) "")))))
953
954 ;; -file FILENAME: Load the given file.
955 ((and (equal "-file" arg)
956 command-line-args-left)
957 (let ((file (pop command-line-args-left)))
958 (if coding-system
959 (setq file (decode-coding-string file coding-system)))
960 (setq file (command-line-normalize-file-name file))
961 (push (cons file filepos) files)
962 (server-log (format "New file: %s %s"
963 file (or filepos "")) proc))
964 (setq filepos nil))
965
966 ;; -eval EXPR: Evaluate a Lisp expression.
967 ((and (equal "-eval" arg)
968 command-line-args-left)
969 (if use-current-frame
970 (setq use-current-frame 'always))
971 (lexical-let ((expr (pop command-line-args-left)))
972 (if coding-system
973 (setq expr (decode-coding-string expr coding-system)))
974 (push (lambda () (server-eval-and-print expr proc))
975 commands)
976 (setq filepos nil)))
977
978 ;; -env NAME=VALUE: An environment variable.
979 ((and (equal "-env" arg) command-line-args-left)
980 (let ((var (pop command-line-args-left)))
981 ;; XXX Variables should be encoded as in getenv/setenv.
982 (process-put proc 'env
983 (cons var (process-get proc 'env)))))
984
985 ;; -dir DIRNAME: The cwd of the emacsclient process.
986 ((and (equal "-dir" arg) command-line-args-left)
987 (setq dir (pop command-line-args-left))
988 (if coding-system
989 (setq dir (decode-coding-string dir coding-system)))
990 (setq dir (command-line-normalize-file-name dir)))
991
992 ;; Unknown command.
993 (t (error "Unknown command: %s" arg))))
994
995 (setq frame
996 (cond
997 ((and use-current-frame
998 (or (eq use-current-frame 'always)
999 ;; We can't use the Emacs daemon's
1000 ;; terminal frame.
1001 (not (and (daemonp)
1002 (null (cdr (frame-list)))
1003 (eq (selected-frame)
1004 terminal-frame)))))
1005 (setq tty-name nil tty-type nil)
1006 (if display (server-select-display display)))
1007 ((eq tty-name 'window-system)
1008 (server-create-window-system-frame display nowait proc))
1009 ;; When resuming on a tty, tty-name is nil.
1010 (tty-name
1011 (server-create-tty-frame tty-name tty-type proc))))
1012
1013 (process-put
1014 proc 'continuation
1015 (lexical-let ((proc proc)
1016 (files files)
1017 (nowait nowait)
1018 (commands commands)
1019 (dontkill dontkill)
1020 (frame frame)
1021 (dir dir)
1022 (tty-name tty-name))
1023 (lambda ()
1024 (with-current-buffer (get-buffer-create server-buffer)
1025 ;; Use the same cwd as the emacsclient, if possible, so
1026 ;; relative file names work correctly, even in `eval'.
1027 (let ((default-directory
1028 (if (and dir (file-directory-p dir))
1029 dir default-directory)))
1030 (server-execute proc files nowait commands
1031 dontkill frame tty-name))))))
1032
1033 (when (or frame files)
1034 (server-goto-toplevel proc))
1035
1036 (server-execute-continuation proc))))
1037 ;; condition-case
1038 (error (server-return-error proc err))))
1039
1040 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1041 ;; This is run from timers and process-filters, i.e. "asynchronously".
1042 ;; But w.r.t the user, this is not really asynchronous since the timer
1043 ;; is run after 0s and the process-filter is run in response to the
1044 ;; user running `emacsclient'. So it is OK to override the
1045 ;; inhibit-quit flag, which is good since `commands' (as well as
1046 ;; find-file-noselect via the major-mode) can run arbitrary code,
1047 ;; including code that needs to wait.
1048 (with-local-quit
1049 (condition-case err
1050 (let* ((buffers
1051 (when files
1052 (run-hooks 'pre-command-hook)
1053 (prog1 (server-visit-files files proc nowait)
1054 (run-hooks 'post-command-hook)))))
1055
1056 (mapc 'funcall (nreverse commands))
1057
1058 ;; Delete the client if necessary.
1059 (cond
1060 (nowait
1061 ;; Client requested nowait; return immediately.
1062 (server-log "Close nowait client" proc)
1063 (server-delete-client proc))
1064 ((and (not dontkill) (null buffers))
1065 ;; This client is empty; get rid of it immediately.
1066 (server-log "Close empty client" proc)
1067 (server-delete-client proc)))
1068 (cond
1069 ((or isearch-mode (minibufferp))
1070 nil)
1071 ((and frame (null buffers))
1072 (message "%s" (substitute-command-keys
1073 "When done with this frame, type \\[delete-frame]")))
1074 ((not (null buffers))
1075 (server-switch-buffer (car buffers) nil (cdr (car files)))
1076 (run-hooks 'server-switch-hook)
1077 (unless nowait
1078 (message "%s" (substitute-command-keys
1079 "When done with a buffer, type \\[server-edit]")))))
1080 (when (and frame (null tty-name))
1081 (server-unselect-display frame)))
1082 (error (server-return-error proc err)))))
1083
1084 (defun server-return-error (proc err)
1085 (ignore-errors
1086 (server-send-string
1087 proc (concat "-error " (server-quote-arg
1088 (error-message-string err))))
1089 (server-log (error-message-string err) proc)
1090 (delete-process proc)))
1091
1092 (defun server-goto-line-column (line-col)
1093 "Move point to the position indicated in LINE-COL.
1094 LINE-COL should be a pair (LINE . COL)."
1095 (when line-col
1096 (goto-line (car line-col))
1097 (let ((column-number (cdr line-col)))
1098 (when (> column-number 0)
1099 (move-to-column (1- column-number))))))
1100
1101 (defun server-visit-files (files proc &optional nowait)
1102 "Find FILES and return a list of buffers created.
1103 FILES is an alist whose elements are (FILENAME . FILEPOS)
1104 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1105 PROC is the client that requested this operation.
1106 NOWAIT non-nil means this client is not waiting for the results,
1107 so don't mark these buffers specially, just visit them normally."
1108 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1109 (let ((last-nonmenu-event t) client-record)
1110 ;; Restore the current buffer afterward, but not using save-excursion,
1111 ;; because we don't want to save point in this buffer
1112 ;; if it happens to be one of those specified by the server.
1113 (save-current-buffer
1114 (dolist (file files)
1115 ;; If there is an existing buffer modified or the file is
1116 ;; modified, revert it. If there is an existing buffer with
1117 ;; deleted file, offer to write it.
1118 (let* ((minibuffer-auto-raise (or server-raise-frame
1119 minibuffer-auto-raise))
1120 (filen (car file))
1121 (obuf (get-file-buffer filen)))
1122 (add-to-history 'file-name-history filen)
1123 (if (null obuf)
1124 (set-buffer (find-file-noselect filen))
1125 (set-buffer obuf)
1126 (cond ((file-exists-p filen)
1127 (when (not (verify-visited-file-modtime obuf))
1128 (revert-buffer t nil)))
1129 (t
1130 (when (y-or-n-p
1131 (concat "File no longer exists: " filen
1132 ", write buffer to file? "))
1133 (write-file filen))))
1134 (unless server-buffer-clients
1135 (setq server-existing-buffer t)))
1136 (server-goto-line-column (cdr file))
1137 (run-hooks 'server-visit-hook))
1138 (unless nowait
1139 ;; When the buffer is killed, inform the clients.
1140 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1141 (push proc server-buffer-clients))
1142 (push (current-buffer) client-record)))
1143 (unless nowait
1144 (process-put proc 'buffers
1145 (nconc (process-get proc 'buffers) client-record)))
1146 client-record))
1147 \f
1148 (defun server-buffer-done (buffer &optional for-killing)
1149 "Mark BUFFER as \"done\" for its client(s).
1150 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1151 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1152 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1153 a temp file).
1154 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1155 (let ((next-buffer nil)
1156 (killed nil))
1157 (dolist (proc server-clients)
1158 (let ((buffers (process-get proc 'buffers)))
1159 (or next-buffer
1160 (setq next-buffer (nth 1 (memq buffer buffers))))
1161 (when buffers ; Ignore bufferless clients.
1162 (setq buffers (delq buffer buffers))
1163 ;; Delete all dead buffers from PROC.
1164 (dolist (b buffers)
1165 (and (bufferp b)
1166 (not (buffer-live-p b))
1167 (setq buffers (delq b buffers))))
1168 (process-put proc 'buffers buffers)
1169 ;; If client now has no pending buffers,
1170 ;; tell it that it is done, and forget it entirely.
1171 (unless buffers
1172 (server-log "Close" proc)
1173 (if for-killing
1174 ;; `server-delete-client' might delete the client's
1175 ;; frames, which might change the current buffer. We
1176 ;; don't want that (bug#640).
1177 (save-current-buffer
1178 (server-delete-client proc))
1179 (server-delete-client proc))))))
1180 (when (and (bufferp buffer) (buffer-name buffer))
1181 ;; We may or may not kill this buffer;
1182 ;; if we do, do not call server-buffer-done recursively
1183 ;; from kill-buffer-hook.
1184 (let ((server-kill-buffer-running t))
1185 (with-current-buffer buffer
1186 (setq server-buffer-clients nil)
1187 (run-hooks 'server-done-hook))
1188 ;; Notice whether server-done-hook killed the buffer.
1189 (if (null (buffer-name buffer))
1190 (setq killed t)
1191 ;; Don't bother killing or burying the buffer
1192 ;; when we are called from kill-buffer.
1193 (unless for-killing
1194 (when (and (not killed)
1195 server-kill-new-buffers
1196 (with-current-buffer buffer
1197 (not server-existing-buffer)))
1198 (setq killed t)
1199 (bury-buffer buffer)
1200 (kill-buffer buffer))
1201 (unless killed
1202 (if (server-temp-file-p buffer)
1203 (progn
1204 (kill-buffer buffer)
1205 (setq killed t))
1206 (bury-buffer buffer)))))))
1207 (list next-buffer killed)))
1208
1209 (defun server-temp-file-p (&optional buffer)
1210 "Return non-nil if BUFFER contains a file considered temporary.
1211 These are files whose names suggest they are repeatedly
1212 reused to pass information to another program.
1213
1214 The variable `server-temp-file-regexp' controls which filenames
1215 are considered temporary."
1216 (and (buffer-file-name buffer)
1217 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1218
1219 (defun server-done ()
1220 "Offer to save current buffer, mark it as \"done\" for clients.
1221 This kills or buries the buffer, then returns a list
1222 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1223 as a suggestion for what to select next, or nil.
1224 KILLED is t if we killed BUFFER, which happens if it was created
1225 specifically for the clients and did not exist before their request for it."
1226 (when server-buffer-clients
1227 (if (server-temp-file-p)
1228 ;; For a temp file, save, and do make a non-numeric backup
1229 ;; (unless make-backup-files is nil).
1230 (let ((version-control nil)
1231 (buffer-backed-up nil))
1232 (save-buffer))
1233 (when (and (buffer-modified-p)
1234 buffer-file-name
1235 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1236 (save-buffer)))
1237 (server-buffer-done (current-buffer))))
1238
1239 ;; Ask before killing a server buffer.
1240 ;; It was suggested to release its client instead,
1241 ;; but I think that is dangerous--the client would proceed
1242 ;; using whatever is on disk in that file. -- rms.
1243 (defun server-kill-buffer-query-function ()
1244 "Ask before killing a server buffer."
1245 (or (not server-buffer-clients)
1246 (let ((res t))
1247 (dolist (proc server-buffer-clients res)
1248 (when (and (memq proc server-clients)
1249 (eq (process-status proc) 'open))
1250 (setq res nil))))
1251 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1252 (buffer-name (current-buffer))))))
1253
1254 (defun server-kill-emacs-query-function ()
1255 "Ask before exiting Emacs if it has live clients."
1256 (or (not server-clients)
1257 (let (live-client)
1258 (dolist (proc server-clients live-client)
1259 (when (memq t (mapcar 'buffer-live-p (process-get
1260 proc 'buffers)))
1261 (setq live-client t))))
1262 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1263
1264 (defvar server-kill-buffer-running nil
1265 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1266
1267 (defun server-kill-buffer ()
1268 "Remove the current buffer from its clients' buffer list.
1269 Designed to be added to `kill-buffer-hook'."
1270 ;; Prevent infinite recursion if user has made server-done-hook
1271 ;; call kill-buffer.
1272 (or server-kill-buffer-running
1273 (and server-buffer-clients
1274 (let ((server-kill-buffer-running t))
1275 (when server-process
1276 (server-buffer-done (current-buffer) t))))))
1277 \f
1278 (defun server-edit (&optional arg)
1279 "Switch to next server editing buffer; say \"Done\" for current buffer.
1280 If a server buffer is current, it is marked \"done\" and optionally saved.
1281 The buffer is also killed if it did not exist before the clients asked for it.
1282 When all of a client's buffers are marked as \"done\", the client is notified.
1283
1284 Temporary files such as MH <draft> files are always saved and backed up,
1285 no questions asked. (The variable `make-backup-files', if nil, still
1286 inhibits a backup; you can set it locally in a particular buffer to
1287 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1288 which filenames are considered temporary.
1289
1290 If invoked with a prefix argument, or if there is no server process running,
1291 starts server process and that is all. Invoked by \\[server-edit]."
1292 (interactive "P")
1293 (cond
1294 ((or arg
1295 (not server-process)
1296 (memq (process-status server-process) '(signal exit)))
1297 (server-mode 1))
1298 (server-clients (apply 'server-switch-buffer (server-done)))
1299 (t (message "No server editing buffers exist"))))
1300
1301 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1302 "Switch to another buffer, preferably one that has a client.
1303 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1304
1305 KILLED-ONE is t in a recursive call if we have already killed one
1306 temp-file server buffer. This means we should avoid the final
1307 \"switch to some other buffer\" since we've already effectively
1308 done that.
1309
1310 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1311 visit NEXT-BUFFER in an existing window. If non-nil, it should
1312 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1313 (if (null next-buffer)
1314 (progn
1315 (let ((rest server-clients))
1316 (while (and rest (not next-buffer))
1317 (let ((proc (car rest)))
1318 ;; Only look at frameless clients, or those in the selected
1319 ;; frame.
1320 (when (or (not (process-get proc 'frame))
1321 (eq (process-get proc 'frame) (selected-frame)))
1322 (setq next-buffer (car (process-get proc 'buffers))))
1323 (setq rest (cdr rest)))))
1324 (and next-buffer (server-switch-buffer next-buffer killed-one))
1325 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1326 ;; (switch-to-buffer (other-buffer))
1327 (message "No server buffers remain to edit")))
1328 (if (not (buffer-live-p next-buffer))
1329 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1330 ;; and try the next surviving server buffer.
1331 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1332 ;; OK, we know next-buffer is live, let's display and select it.
1333 (if (functionp server-window)
1334 (funcall server-window next-buffer)
1335 (let ((win (get-buffer-window next-buffer 0)))
1336 (if (and win (not server-window))
1337 ;; The buffer is already displayed: just reuse the
1338 ;; window. If FILEPOS is non-nil, use it to replace the
1339 ;; window's own value of point.
1340 (progn
1341 (select-window win)
1342 (set-buffer next-buffer)
1343 (when filepos
1344 (server-goto-line-column filepos)))
1345 ;; Otherwise, let's find an appropriate window.
1346 (cond ((window-live-p server-window)
1347 (select-window server-window))
1348 ((framep server-window)
1349 (unless (frame-live-p server-window)
1350 (setq server-window (make-frame)))
1351 (select-window (frame-selected-window server-window))))
1352 (when (window-minibuffer-p (selected-window))
1353 (select-window (next-window nil 'nomini 0)))
1354 ;; Move to a non-dedicated window, if we have one.
1355 (when (window-dedicated-p (selected-window))
1356 (select-window
1357 (get-window-with-predicate
1358 (lambda (w)
1359 (and (not (window-dedicated-p w))
1360 (equal (frame-terminal (window-frame w))
1361 (frame-terminal (selected-frame)))))
1362 'nomini 'visible (selected-window))))
1363 (condition-case nil
1364 (switch-to-buffer next-buffer)
1365 ;; After all the above, we might still have ended up with
1366 ;; a minibuffer/dedicated-window (if there's no other).
1367 (error (pop-to-buffer next-buffer)))))))
1368 (when server-raise-frame
1369 (select-frame-set-input-focus (window-frame (selected-window))))))
1370
1371 ;;;###autoload
1372 (defun server-save-buffers-kill-terminal (arg)
1373 ;; Called from save-buffers-kill-terminal in files.el.
1374 "Offer to save each buffer, then kill the current client.
1375 With ARG non-nil, silently save all file-visiting buffers, then kill.
1376
1377 If emacsclient was started with a list of filenames to edit, then
1378 only these files will be asked to be saved."
1379 (let ((proc (frame-parameter (selected-frame) 'client)))
1380 (cond ((eq proc 'nowait)
1381 ;; Nowait frames have no client buffer list.
1382 (if (cdr (frame-list))
1383 (progn (save-some-buffers arg)
1384 (delete-frame))
1385 ;; If we're the last frame standing, kill Emacs.
1386 (save-buffers-kill-emacs arg)))
1387 ((processp proc)
1388 (let ((buffers (process-get proc 'buffers)))
1389 ;; If client is bufferless, emulate a normal Emacs exit
1390 ;; and offer to save all buffers. Otherwise, offer to
1391 ;; save only the buffers belonging to the client.
1392 (save-some-buffers
1393 arg (if buffers
1394 (lambda () (memq (current-buffer) buffers))
1395 t))
1396 (server-delete-client proc)))
1397 (t (error "Invalid client frame")))))
1398
1399 (define-key ctl-x-map "#" 'server-edit)
1400
1401 (defun server-unload-function ()
1402 "Unload the server library."
1403 (server-mode -1)
1404 (substitute-key-definition 'server-edit nil ctl-x-map)
1405 (save-current-buffer
1406 (dolist (buffer (buffer-list))
1407 (set-buffer buffer)
1408 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1409 ;; continue standard unloading
1410 nil)
1411
1412 \f
1413 (provide 'server)
1414
1415 ;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1416 ;;; server.el ends here