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