* lisp/emacs-lisp/cconv.el: New file.
[bpt/emacs.git] / lisp / server.el
1 ;;; -*- lexical-binding: t -*-
2 ;;; server.el --- Lisp code for GNU Emacs running as server process
3
4 ;; Copyright (C) 1986-1987, 1992, 1994-2011 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 (lambda () (server-execute-continuation proc)))
782 (top-level)))
783
784 ;; We use various special properties on process objects:
785 ;; - `env' stores the info about the environment of the emacsclient process.
786 ;; - `continuation' is a no-arg function that we need to execute. It contains
787 ;; commands we wanted to execute in some earlier invocation of the process
788 ;; filter but that we somehow were unable to process at that time
789 ;; (e.g. because we first need to throw to the toplevel).
790
791 (defun server-execute-continuation (proc)
792 (let ((continuation (process-get proc 'continuation)))
793 (process-put proc 'continuation nil)
794 (if continuation (ignore-errors (funcall continuation)))))
795
796 (defun* server-process-filter (proc string)
797 "Process a request from the server to edit some files.
798 PROC is the server process. STRING consists of a sequence of
799 commands prefixed by a dash. Some commands have arguments;
800 these are &-quoted and need to be decoded by `server-unquote-arg'.
801 The filter parses and executes these commands.
802
803 To illustrate the protocol, here is an example command that
804 emacsclient sends to create a new X frame (note that the whole
805 sequence is sent on a single line):
806
807 -env HOME=/home/lorentey
808 -env DISPLAY=:0.0
809 ... lots of other -env commands
810 -display :0.0
811 -window-system
812
813 The following commands are accepted by the server:
814
815 `-auth AUTH-STRING'
816 Authenticate the client using the secret authentication string
817 AUTH-STRING.
818
819 `-env NAME=VALUE'
820 An environment variable on the client side.
821
822 `-dir DIRNAME'
823 The current working directory of the client process.
824
825 `-current-frame'
826 Forbid the creation of new frames.
827
828 `-nowait'
829 Request that the next frame created should not be
830 associated with this client.
831
832 `-display DISPLAY'
833 Set the display name to open X frames on.
834
835 `-position LINE[:COLUMN]'
836 Go to the given line and column number
837 in the next file opened.
838
839 `-file FILENAME'
840 Load the given file in the current frame.
841
842 `-eval EXPR'
843 Evaluate EXPR as a Lisp expression and return the
844 result in -print commands.
845
846 `-window-system'
847 Open a new X frame.
848
849 `-tty DEVICENAME TYPE'
850 Open a new tty frame at the client.
851
852 `-suspend'
853 Suspend this tty frame. The client sends this string in
854 response to SIGTSTP and SIGTTOU. The server must cease all I/O
855 on this tty until it gets a -resume command.
856
857 `-resume'
858 Resume this tty frame. The client sends this string when it
859 gets the SIGCONT signal and it is the foreground process on its
860 controlling tty.
861
862 `-ignore COMMENT'
863 Do nothing, but put the comment in the server log.
864 Useful for debugging.
865
866
867 The following commands are accepted by the client:
868
869 `-emacs-pid PID'
870 Describes the process id of the Emacs process;
871 used to forward window change signals to it.
872
873 `-window-system-unsupported'
874 Signals that the server does not support creating X frames;
875 the client must try again with a tty frame.
876
877 `-print STRING'
878 Print STRING on stdout. Used to send values
879 returned by -eval.
880
881 `-error DESCRIPTION'
882 Signal an error and delete process PROC.
883
884 `-suspend'
885 Suspend this terminal, i.e., stop the client process.
886 Sent when the user presses C-z."
887 (server-log (concat "Received " string) proc)
888 ;; First things first: let's check the authentication
889 (unless (process-get proc :authenticated)
890 (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
891 (equal (match-string 1 string) (process-get proc :auth-key)))
892 (progn
893 (setq string (substring string (match-end 0)))
894 (process-put proc :authenticated t)
895 (server-log "Authentication successful" proc))
896 (server-log "Authentication failed" proc)
897 (server-send-string
898 proc (concat "-error " (server-quote-arg "Authentication failed")))
899 ;; Before calling `delete-process', give emacsclient time to
900 ;; receive the error string and shut down on its own.
901 (sit-for 1)
902 (delete-process proc)
903 ;; We return immediately
904 (return-from server-process-filter)))
905 (let ((prev (process-get proc 'previous-string)))
906 (when prev
907 (setq string (concat prev string))
908 (process-put proc 'previous-string nil)))
909 (condition-case err
910 (progn
911 (server-add-client proc)
912 ;; Send our pid
913 (server-send-string proc (concat "-emacs-pid "
914 (number-to-string (emacs-pid)) "\n"))
915 (if (not (string-match "\n" string))
916 ;; Save for later any partial line that remains.
917 (when (> (length string) 0)
918 (process-put proc 'previous-string string))
919
920 ;; In earlier versions of server.el (where we used an `emacsserver'
921 ;; process), there could be multiple lines. Nowadays this is not
922 ;; supported any more.
923 (assert (eq (match-end 0) (length string)))
924 (let ((request (substring string 0 (match-beginning 0)))
925 (coding-system (and (default-value 'enable-multibyte-characters)
926 (or file-name-coding-system
927 default-file-name-coding-system)))
928 nowait ; t if emacsclient does not want to wait for us.
929 frame ; Frame opened for the client (if any).
930 display ; Open frame on this display.
931 parent-id ; Window ID for XEmbed
932 dontkill ; t if client should not be killed.
933 commands
934 dir
935 use-current-frame
936 tty-name ; nil, `window-system', or the tty name.
937 tty-type ; string.
938 files
939 filepos
940 command-line-args-left
941 arg)
942 ;; Remove this line from STRING.
943 (setq string (substring string (match-end 0)))
944 (setq command-line-args-left
945 (mapcar 'server-unquote-arg (split-string request " " t)))
946 (while (setq arg (pop command-line-args-left))
947 (cond
948 ;; -version CLIENT-VERSION: obsolete at birth.
949 ((and (equal "-version" arg) command-line-args-left)
950 (pop command-line-args-left))
951
952 ;; -nowait: Emacsclient won't wait for a result.
953 ((equal "-nowait" arg) (setq nowait t))
954
955 ;; -current-frame: Don't create frames.
956 ((equal "-current-frame" arg) (setq use-current-frame t))
957
958 ;; -display DISPLAY:
959 ;; Open X frames on the given display instead of the default.
960 ((and (equal "-display" arg) command-line-args-left)
961 (setq display (pop command-line-args-left))
962 (if (zerop (length display)) (setq display nil)))
963
964 ;; -parent-id ID:
965 ;; Open X frame within window ID, via XEmbed.
966 ((and (equal "-parent-id" arg) command-line-args-left)
967 (setq parent-id (pop command-line-args-left))
968 (if (zerop (length parent-id)) (setq parent-id nil)))
969
970 ;; -window-system: Open a new X frame.
971 ((equal "-window-system" arg)
972 (setq dontkill t)
973 (setq tty-name 'window-system))
974
975 ;; -resume: Resume a suspended tty frame.
976 ((equal "-resume" arg)
977 (let ((terminal (process-get proc 'terminal)))
978 (setq dontkill t)
979 (push (lambda ()
980 (when (eq (terminal-live-p terminal) t)
981 (resume-tty terminal)))
982 commands)))
983
984 ;; -suspend: Suspend the client's frame. (In case we
985 ;; get out of sync, and a C-z sends a SIGTSTP to
986 ;; emacsclient.)
987 ((equal "-suspend" arg)
988 (let ((terminal (process-get proc 'terminal)))
989 (setq dontkill t)
990 (push (lambda ()
991 (when (eq (terminal-live-p terminal) t)
992 (suspend-tty terminal)))
993 commands)))
994
995 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
996 ;; (The given comment appears in the server log.)
997 ((and (equal "-ignore" arg) command-line-args-left
998 (setq dontkill t)
999 (pop command-line-args-left)))
1000
1001 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
1002 ((and (equal "-tty" arg)
1003 (cdr command-line-args-left))
1004 (setq tty-name (pop command-line-args-left)
1005 tty-type (pop command-line-args-left)
1006 dontkill (or dontkill
1007 (not use-current-frame))))
1008
1009 ;; -position LINE[:COLUMN]: Set point to the given
1010 ;; position in the next file.
1011 ((and (equal "-position" arg)
1012 command-line-args-left
1013 (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
1014 (car command-line-args-left)))
1015 (setq arg (pop command-line-args-left))
1016 (setq filepos
1017 (cons (string-to-number (match-string 1 arg))
1018 (string-to-number (or (match-string 2 arg) "")))))
1019
1020 ;; -file FILENAME: Load the given file.
1021 ((and (equal "-file" arg)
1022 command-line-args-left)
1023 (let ((file (pop command-line-args-left)))
1024 (if coding-system
1025 (setq file (decode-coding-string file coding-system)))
1026 (setq file (expand-file-name file dir))
1027 (push (cons file filepos) files)
1028 (server-log (format "New file: %s %s"
1029 file (or filepos "")) proc))
1030 (setq filepos nil))
1031
1032 ;; -eval EXPR: Evaluate a Lisp expression.
1033 ((and (equal "-eval" arg)
1034 command-line-args-left)
1035 (if use-current-frame
1036 (setq use-current-frame 'always))
1037 (let ((expr (pop command-line-args-left)))
1038 (if coding-system
1039 (setq expr (decode-coding-string expr coding-system)))
1040 (push (lambda () (server-eval-and-print expr proc))
1041 commands)
1042 (setq filepos nil)))
1043
1044 ;; -env NAME=VALUE: An environment variable.
1045 ((and (equal "-env" arg) command-line-args-left)
1046 (let ((var (pop command-line-args-left)))
1047 ;; XXX Variables should be encoded as in getenv/setenv.
1048 (process-put proc 'env
1049 (cons var (process-get proc 'env)))))
1050
1051 ;; -dir DIRNAME: The cwd of the emacsclient process.
1052 ((and (equal "-dir" arg) command-line-args-left)
1053 (setq dir (pop command-line-args-left))
1054 (if coding-system
1055 (setq dir (decode-coding-string dir coding-system)))
1056 (setq dir (command-line-normalize-file-name dir)))
1057
1058 ;; Unknown command.
1059 (t (error "Unknown command: %s" arg))))
1060
1061 (setq frame
1062 (cond
1063 ((and use-current-frame
1064 (or (eq use-current-frame 'always)
1065 ;; We can't use the Emacs daemon's
1066 ;; terminal frame.
1067 (not (and (daemonp)
1068 (null (cdr (frame-list)))
1069 (eq (selected-frame)
1070 terminal-frame)))))
1071 (setq tty-name nil tty-type nil)
1072 (if display (server-select-display display)))
1073 ((eq tty-name 'window-system)
1074 (server-create-window-system-frame display nowait proc
1075 parent-id))
1076 ;; When resuming on a tty, tty-name is nil.
1077 (tty-name
1078 (server-create-tty-frame tty-name tty-type proc))))
1079
1080 (process-put
1081 proc 'continuation
1082 (lambda ()
1083 (with-current-buffer (get-buffer-create server-buffer)
1084 ;; Use the same cwd as the emacsclient, if possible, so
1085 ;; relative file names work correctly, even in `eval'.
1086 (let ((default-directory
1087 (if (and dir (file-directory-p dir))
1088 dir default-directory)))
1089 (server-execute proc files nowait commands
1090 dontkill frame tty-name)))))
1091
1092 (when (or frame files)
1093 (server-goto-toplevel proc))
1094
1095 (server-execute-continuation proc))))
1096 ;; condition-case
1097 (error (server-return-error proc err))))
1098
1099 (defun server-execute (proc files nowait commands dontkill frame tty-name)
1100 ;; This is run from timers and process-filters, i.e. "asynchronously".
1101 ;; But w.r.t the user, this is not really asynchronous since the timer
1102 ;; is run after 0s and the process-filter is run in response to the
1103 ;; user running `emacsclient'. So it is OK to override the
1104 ;; inhibit-quit flag, which is good since `commands' (as well as
1105 ;; find-file-noselect via the major-mode) can run arbitrary code,
1106 ;; including code that needs to wait.
1107 (with-local-quit
1108 (condition-case err
1109 (let* ((buffers
1110 (when files
1111 (server-visit-files files proc nowait))))
1112
1113 (mapc 'funcall (nreverse commands))
1114
1115 ;; Delete the client if necessary.
1116 (cond
1117 (nowait
1118 ;; Client requested nowait; return immediately.
1119 (server-log "Close nowait client" proc)
1120 (server-delete-client proc))
1121 ((and (not dontkill) (null buffers))
1122 ;; This client is empty; get rid of it immediately.
1123 (server-log "Close empty client" proc)
1124 (server-delete-client proc)))
1125 (cond
1126 ((or isearch-mode (minibufferp))
1127 nil)
1128 ((and frame (null buffers))
1129 (message "%s" (substitute-command-keys
1130 "When done with this frame, type \\[delete-frame]")))
1131 ((not (null buffers))
1132 (server-switch-buffer (car buffers) nil (cdr (car files)))
1133 (run-hooks 'server-switch-hook)
1134 (unless nowait
1135 (message "%s" (substitute-command-keys
1136 "When done with a buffer, type \\[server-edit]")))))
1137 (when (and frame (null tty-name))
1138 (server-unselect-display frame)))
1139 (error (server-return-error proc err)))))
1140
1141 (defun server-return-error (proc err)
1142 (ignore-errors
1143 (server-send-string
1144 proc (concat "-error " (server-quote-arg
1145 (error-message-string err))))
1146 (server-log (error-message-string err) proc)
1147 ;; Before calling `delete-process', give emacsclient time to
1148 ;; receive the error string and shut down on its own.
1149 (sit-for 5)
1150 (delete-process proc)))
1151
1152 (defun server-goto-line-column (line-col)
1153 "Move point to the position indicated in LINE-COL.
1154 LINE-COL should be a pair (LINE . COL)."
1155 (when line-col
1156 (goto-char (point-min))
1157 (forward-line (1- (car line-col)))
1158 (let ((column-number (cdr line-col)))
1159 (when (> column-number 0)
1160 (move-to-column (1- column-number))))))
1161
1162 (defun server-visit-files (files proc &optional nowait)
1163 "Find FILES and return a list of buffers created.
1164 FILES is an alist whose elements are (FILENAME . FILEPOS)
1165 where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
1166 PROC is the client that requested this operation.
1167 NOWAIT non-nil means this client is not waiting for the results,
1168 so don't mark these buffers specially, just visit them normally."
1169 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
1170 (let ((last-nonmenu-event t) client-record)
1171 ;; Restore the current buffer afterward, but not using save-excursion,
1172 ;; because we don't want to save point in this buffer
1173 ;; if it happens to be one of those specified by the server.
1174 (save-current-buffer
1175 (dolist (file files)
1176 ;; If there is an existing buffer modified or the file is
1177 ;; modified, revert it. If there is an existing buffer with
1178 ;; deleted file, offer to write it.
1179 (let* ((minibuffer-auto-raise (or server-raise-frame
1180 minibuffer-auto-raise))
1181 (filen (car file))
1182 (obuf (get-file-buffer filen)))
1183 (add-to-history 'file-name-history filen)
1184 (if (null obuf)
1185 (progn
1186 (run-hooks 'pre-command-hook)
1187 (set-buffer (find-file-noselect filen)))
1188 (set-buffer obuf)
1189 ;; separately for each file, in sync with post-command hooks,
1190 ;; with the new buffer current:
1191 (run-hooks 'pre-command-hook)
1192 (cond ((file-exists-p filen)
1193 (when (not (verify-visited-file-modtime obuf))
1194 (revert-buffer t nil)))
1195 (t
1196 (when (y-or-n-p
1197 (concat "File no longer exists: " filen
1198 ", write buffer to file? "))
1199 (write-file filen))))
1200 (unless server-buffer-clients
1201 (setq server-existing-buffer t)))
1202 (server-goto-line-column (cdr file))
1203 (run-hooks 'server-visit-hook)
1204 ;; hooks may be specific to current buffer:
1205 (run-hooks 'post-command-hook))
1206 (unless nowait
1207 ;; When the buffer is killed, inform the clients.
1208 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
1209 (push proc server-buffer-clients))
1210 (push (current-buffer) client-record)))
1211 (unless nowait
1212 (process-put proc 'buffers
1213 (nconc (process-get proc 'buffers) client-record)))
1214 client-record))
1215 \f
1216 (defun server-buffer-done (buffer &optional for-killing)
1217 "Mark BUFFER as \"done\" for its client(s).
1218 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
1219 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
1220 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
1221 a temp file).
1222 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
1223 (let ((next-buffer nil)
1224 (killed nil))
1225 (dolist (proc server-clients)
1226 (let ((buffers (process-get proc 'buffers)))
1227 (or next-buffer
1228 (setq next-buffer (nth 1 (memq buffer buffers))))
1229 (when buffers ; Ignore bufferless clients.
1230 (setq buffers (delq buffer buffers))
1231 ;; Delete all dead buffers from PROC.
1232 (dolist (b buffers)
1233 (and (bufferp b)
1234 (not (buffer-live-p b))
1235 (setq buffers (delq b buffers))))
1236 (process-put proc 'buffers buffers)
1237 ;; If client now has no pending buffers,
1238 ;; tell it that it is done, and forget it entirely.
1239 (unless buffers
1240 (server-log "Close" proc)
1241 (if for-killing
1242 ;; `server-delete-client' might delete the client's
1243 ;; frames, which might change the current buffer. We
1244 ;; don't want that (bug#640).
1245 (save-current-buffer
1246 (server-delete-client proc))
1247 (server-delete-client proc))))))
1248 (when (and (bufferp buffer) (buffer-name buffer))
1249 ;; We may or may not kill this buffer;
1250 ;; if we do, do not call server-buffer-done recursively
1251 ;; from kill-buffer-hook.
1252 (let ((server-kill-buffer-running t))
1253 (with-current-buffer buffer
1254 (setq server-buffer-clients nil)
1255 (run-hooks 'server-done-hook))
1256 ;; Notice whether server-done-hook killed the buffer.
1257 (if (null (buffer-name buffer))
1258 (setq killed t)
1259 ;; Don't bother killing or burying the buffer
1260 ;; when we are called from kill-buffer.
1261 (unless for-killing
1262 (when (and (not killed)
1263 server-kill-new-buffers
1264 (with-current-buffer buffer
1265 (not server-existing-buffer)))
1266 (setq killed t)
1267 (bury-buffer buffer)
1268 ;; Prevent kill-buffer from prompting (Bug#3696).
1269 (with-current-buffer buffer
1270 (set-buffer-modified-p nil))
1271 (kill-buffer buffer))
1272 (unless killed
1273 (if (server-temp-file-p buffer)
1274 (progn
1275 (with-current-buffer buffer
1276 (set-buffer-modified-p nil))
1277 (kill-buffer buffer)
1278 (setq killed t))
1279 (bury-buffer buffer)))))))
1280 (list next-buffer killed)))
1281
1282 (defun server-temp-file-p (&optional buffer)
1283 "Return non-nil if BUFFER contains a file considered temporary.
1284 These are files whose names suggest they are repeatedly
1285 reused to pass information to another program.
1286
1287 The variable `server-temp-file-regexp' controls which filenames
1288 are considered temporary."
1289 (and (buffer-file-name buffer)
1290 (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
1291
1292 (defun server-done ()
1293 "Offer to save current buffer, mark it as \"done\" for clients.
1294 This kills or buries the buffer, then returns a list
1295 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
1296 as a suggestion for what to select next, or nil.
1297 KILLED is t if we killed BUFFER, which happens if it was created
1298 specifically for the clients and did not exist before their request for it."
1299 (when server-buffer-clients
1300 (if (server-temp-file-p)
1301 ;; For a temp file, save, and do make a non-numeric backup
1302 ;; (unless make-backup-files is nil).
1303 (let ((version-control nil)
1304 (buffer-backed-up nil))
1305 (save-buffer))
1306 (when (and (buffer-modified-p)
1307 buffer-file-name
1308 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
1309 (save-buffer)))
1310 (server-buffer-done (current-buffer))))
1311
1312 ;; Ask before killing a server buffer.
1313 ;; It was suggested to release its client instead,
1314 ;; but I think that is dangerous--the client would proceed
1315 ;; using whatever is on disk in that file. -- rms.
1316 (defun server-kill-buffer-query-function ()
1317 "Ask before killing a server buffer."
1318 (or (not server-buffer-clients)
1319 (let ((res t))
1320 (dolist (proc server-buffer-clients res)
1321 (when (and (memq proc server-clients)
1322 (eq (process-status proc) 'open))
1323 (setq res nil))))
1324 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
1325 (buffer-name (current-buffer))))))
1326
1327 (defun server-kill-emacs-query-function ()
1328 "Ask before exiting Emacs if it has live clients."
1329 (or (not server-clients)
1330 (let (live-client)
1331 (dolist (proc server-clients live-client)
1332 (when (memq t (mapcar 'buffer-live-p (process-get
1333 proc 'buffers)))
1334 (setq live-client t))))
1335 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
1336
1337 (defvar server-kill-buffer-running nil
1338 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
1339
1340 (defun server-kill-buffer ()
1341 "Remove the current buffer from its clients' buffer list.
1342 Designed to be added to `kill-buffer-hook'."
1343 ;; Prevent infinite recursion if user has made server-done-hook
1344 ;; call kill-buffer.
1345 (or server-kill-buffer-running
1346 (and server-buffer-clients
1347 (let ((server-kill-buffer-running t))
1348 (when server-process
1349 (server-buffer-done (current-buffer) t))))))
1350 \f
1351 (defun server-edit (&optional arg)
1352 "Switch to next server editing buffer; say \"Done\" for current buffer.
1353 If a server buffer is current, it is marked \"done\" and optionally saved.
1354 The buffer is also killed if it did not exist before the clients asked for it.
1355 When all of a client's buffers are marked as \"done\", the client is notified.
1356
1357 Temporary files such as MH <draft> files are always saved and backed up,
1358 no questions asked. (The variable `make-backup-files', if nil, still
1359 inhibits a backup; you can set it locally in a particular buffer to
1360 prevent a backup for it.) The variable `server-temp-file-regexp' controls
1361 which filenames are considered temporary.
1362
1363 If invoked with a prefix argument, or if there is no server process running,
1364 starts server process and that is all. Invoked by \\[server-edit]."
1365 (interactive "P")
1366 (cond
1367 ((or arg
1368 (not server-process)
1369 (memq (process-status server-process) '(signal exit)))
1370 (server-mode 1))
1371 (server-clients (apply 'server-switch-buffer (server-done)))
1372 (t (message "No server editing buffers exist"))))
1373
1374 (defun server-switch-buffer (&optional next-buffer killed-one filepos)
1375 "Switch to another buffer, preferably one that has a client.
1376 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
1377
1378 KILLED-ONE is t in a recursive call if we have already killed one
1379 temp-file server buffer. This means we should avoid the final
1380 \"switch to some other buffer\" since we've already effectively
1381 done that.
1382
1383 FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
1384 visit NEXT-BUFFER in an existing window. If non-nil, it should
1385 be a cons cell (LINENUMBER . COLUMNNUMBER)."
1386 (if (null next-buffer)
1387 (progn
1388 (let ((rest server-clients))
1389 (while (and rest (not next-buffer))
1390 (let ((proc (car rest)))
1391 ;; Only look at frameless clients, or those in the selected
1392 ;; frame.
1393 (when (or (not (process-get proc 'frame))
1394 (eq (process-get proc 'frame) (selected-frame)))
1395 (setq next-buffer (car (process-get proc 'buffers))))
1396 (setq rest (cdr rest)))))
1397 (and next-buffer (server-switch-buffer next-buffer killed-one))
1398 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1399 ;; (switch-to-buffer (other-buffer))
1400 (message "No server buffers remain to edit")))
1401 (if (not (buffer-live-p next-buffer))
1402 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1403 ;; and try the next surviving server buffer.
1404 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1405 ;; OK, we know next-buffer is live, let's display and select it.
1406 (if (functionp server-window)
1407 (funcall server-window next-buffer)
1408 (let ((win (get-buffer-window next-buffer 0)))
1409 (if (and win (not server-window))
1410 ;; The buffer is already displayed: just reuse the
1411 ;; window. If FILEPOS is non-nil, use it to replace the
1412 ;; window's own value of point.
1413 (progn
1414 (select-window win)
1415 (set-buffer next-buffer)
1416 (when filepos
1417 (server-goto-line-column filepos)))
1418 ;; Otherwise, let's find an appropriate window.
1419 (cond ((window-live-p server-window)
1420 (select-window server-window))
1421 ((framep server-window)
1422 (unless (frame-live-p server-window)
1423 (setq server-window (make-frame)))
1424 (select-window (frame-selected-window server-window))))
1425 (when (window-minibuffer-p (selected-window))
1426 (select-window (next-window nil 'nomini 0)))
1427 ;; Move to a non-dedicated window, if we have one.
1428 (when (window-dedicated-p (selected-window))
1429 (select-window
1430 (get-window-with-predicate
1431 (lambda (w)
1432 (and (not (window-dedicated-p w))
1433 (equal (frame-terminal (window-frame w))
1434 (frame-terminal (selected-frame)))))
1435 'nomini 'visible (selected-window))))
1436 (condition-case nil
1437 (switch-to-buffer next-buffer)
1438 ;; After all the above, we might still have ended up with
1439 ;; a minibuffer/dedicated-window (if there's no other).
1440 (error (pop-to-buffer next-buffer)))))))
1441 (when server-raise-frame
1442 (select-frame-set-input-focus (window-frame (selected-window))))))
1443
1444 ;;;###autoload
1445 (defun server-save-buffers-kill-terminal (arg)
1446 ;; Called from save-buffers-kill-terminal in files.el.
1447 "Offer to save each buffer, then kill the current client.
1448 With ARG non-nil, silently save all file-visiting buffers, then kill.
1449
1450 If emacsclient was started with a list of filenames to edit, then
1451 only these files will be asked to be saved."
1452 (let ((proc (frame-parameter (selected-frame) 'client)))
1453 (cond ((eq proc 'nowait)
1454 ;; Nowait frames have no client buffer list.
1455 (if (cdr (frame-list))
1456 (progn (save-some-buffers arg)
1457 (delete-frame))
1458 ;; If we're the last frame standing, kill Emacs.
1459 (save-buffers-kill-emacs arg)))
1460 ((processp proc)
1461 (let ((buffers (process-get proc 'buffers)))
1462 ;; If client is bufferless, emulate a normal Emacs exit
1463 ;; and offer to save all buffers. Otherwise, offer to
1464 ;; save only the buffers belonging to the client.
1465 (save-some-buffers
1466 arg (if buffers
1467 (lambda () (memq (current-buffer) buffers))
1468 t))
1469 (server-delete-client proc)))
1470 (t (error "Invalid client frame")))))
1471
1472 (define-key ctl-x-map "#" 'server-edit)
1473
1474 (defun server-unload-function ()
1475 "Unload the server library."
1476 (server-mode -1)
1477 (substitute-key-definition 'server-edit nil ctl-x-map)
1478 (save-current-buffer
1479 (dolist (buffer (buffer-list))
1480 (set-buffer buffer)
1481 (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
1482 ;; continue standard unloading
1483 nil)
1484
1485 \f
1486 (provide 'server)
1487
1488 ;;; server.el ends here