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