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