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