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