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