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