Merged from miles@gnu.org--gnu-2005 (patch 152-156, 642-654)
[bpt/emacs.git] / lisp / server.el
1 ;;; server.el --- Lisp code for GNU Emacs running as server process
2
3 ;; Copyright (C) 1986, 1987, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4 ;; 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
5
6 ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
7 ;; Maintainer: FSF
8 ;; Keywords: processes
9
10 ;; Changes by peck@sun.com and by rms.
11 ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
12
13 ;; This file is part of GNU Emacs.
14
15 ;; GNU Emacs is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; any later version.
19
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING. If not, write to the
27 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
28 ;; Boston, MA 02110-1301, USA.
29
30 ;;; Commentary:
31
32 ;; This Lisp code is run in Emacs when it is to operate as
33 ;; a server for other processes.
34
35 ;; Load this library and do M-x server-edit to enable Emacs as a server.
36 ;; Emacs opens up a socket for communication with clients. If there are no
37 ;; client buffers to edit, server-edit acts like (switch-to-buffer
38 ;; (other-buffer))
39
40 ;; When some other program runs "the editor" to edit a file,
41 ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
42 ;; This program transmits the file names to Emacs through
43 ;; the server subprocess, and Emacs visits them and lets you edit them.
44
45 ;; Note that any number of clients may dispatch files to Emacs to be edited.
46
47 ;; When you finish editing a Server buffer, again call server-edit
48 ;; to mark that buffer as done for the client and switch to the next
49 ;; Server buffer. When all the buffers for a client have been edited
50 ;; and exited with server-edit, the client "editor" will return
51 ;; to the program that invoked it.
52
53 ;; Your editing commands and Emacs's display output go to and from
54 ;; the terminal in the usual way. Thus, server operation is possible
55 ;; only when Emacs can talk to the terminal at the time you invoke
56 ;; the client. This is possible in four cases:
57
58 ;; 1. On a window system, where Emacs runs in one window and the
59 ;; program that wants to use "the editor" runs in another.
60
61 ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
62 ;; program that wants to use "the editor" runs on another.
63
64 ;; 3. When the program that wants to use "the editor" is running
65 ;; as a subprocess of Emacs.
66
67 ;; 4. On a system with job control, when Emacs is suspended, the program
68 ;; that wants to use "the editor" will stop and display
69 ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
70 ;; brought into the foreground for editing. When done editing, Emacs is
71 ;; suspended again, and the client program is brought into the foreground.
72
73 ;; The buffer local variable "server-buffer-clients" lists
74 ;; the clients who are waiting for this buffer to be edited.
75 ;; The global variable "server-clients" lists all the waiting clients,
76 ;; and which files are yet to be edited for each.
77
78 ;;; Code:
79
80 (eval-when-compile (require 'cl))
81
82 (defgroup server nil
83 "Emacs running as a server process."
84 :group 'external)
85
86 (defcustom server-visit-hook nil
87 "*Hook run when visiting a file for the Emacs server."
88 :group 'server
89 :type 'hook)
90
91 (defcustom server-switch-hook nil
92 "*Hook run when switching to a buffer for the Emacs server."
93 :group 'server
94 :type 'hook)
95
96 (defcustom server-done-hook nil
97 "*Hook run when done editing a buffer for the Emacs server."
98 :group 'server
99 :type 'hook)
100
101 (defvar server-process nil
102 "The current server process.")
103
104 (defvar server-clients nil
105 "List of current server clients.
106 Each element is (PROC PROPERTIES...) where PROC is a process object,
107 and PROPERTIES is an association list of client properties.")
108
109 (defvar server-buffer-clients nil
110 "List of client ids for clients requesting editing of current buffer.")
111 (make-variable-buffer-local 'server-buffer-clients)
112 ;; Changing major modes should not erase this local.
113 (put 'server-buffer-clients 'permanent-local t)
114
115 (defcustom server-window nil
116 "*Specification of the window to use for selecting Emacs server buffers.
117 If nil, use the selected window.
118 If it is a function, it should take one argument (a buffer) and
119 display and select it. A common value is `pop-to-buffer'.
120 If it is a window, use that.
121 If it is a frame, use the frame's selected window.
122
123 It is not meaningful to set this to a specific frame or window with Custom.
124 Only programs can do so."
125 :group 'server
126 :version "22.1"
127 :type '(choice (const :tag "Use selected window"
128 :match (lambda (widget value)
129 (not (functionp value)))
130 nil)
131 (function-item :tag "Use pop-to-buffer" pop-to-buffer)
132 (function :tag "Other function")))
133
134 (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
135 "*Regexp matching names of temporary files.
136 These are deleted and reused after each edit by the programs that
137 invoke the Emacs server."
138 :group 'server
139 :type 'regexp)
140
141 (defcustom server-kill-new-buffers t
142 "*Whether to kill buffers when done with them.
143 If non-nil, kill a buffer unless it already existed before editing
144 it with Emacs server. If nil, kill only buffers as specified by
145 `server-temp-file-regexp'.
146 Please note that only buffers are killed that still have a client,
147 i.e. buffers visited which \"emacsclient --no-wait\" are never killed in
148 this way."
149 :group 'server
150 :type 'boolean
151 :version "21.1")
152
153 (or (assq 'server-buffer-clients minor-mode-alist)
154 (setq minor-mode-alist (cons '(server-buffer-clients " Server") minor-mode-alist)))
155
156 (defvar server-existing-buffer nil
157 "Non-nil means the buffer existed before the server was asked to visit it.
158 This means that the server should not kill the buffer when you say you
159 are done with it in the server.")
160 (make-variable-buffer-local 'server-existing-buffer)
161
162 (defvar server-name "server")
163
164 (defvar server-socket-dir nil
165 "The directory in which to place the server socket.
166 Initialized by `server-start'.")
167
168 (defun server-client (proc)
169 "Return the Emacs client corresponding to PROC.
170 PROC must be a process object.
171 The car of the result is PROC; the cdr is an association list.
172 See `server-client-get' and `server-client-set'."
173 (assq proc server-clients))
174
175 (defun server-client-get (client property)
176 "Get the value of PROPERTY in CLIENT.
177 CLIENT may be a process object, or a client returned by `server-client'.
178 Return nil if CLIENT has no such property."
179 (or (listp client) (setq client (server-client client)))
180 (cdr (assq property (cdr client))))
181
182 (defun server-client-set (client property value)
183 "Set the PROPERTY to VALUE in CLIENT, and return VALUE.
184 CLIENT may be a process object, or a client returned by `server-client'."
185 (let (p proc)
186 (if (listp client)
187 (setq proc (car client))
188 (setq proc client
189 client (server-client client)))
190 (setq p (assq property client))
191 (cond
192 (p (setcdr p value))
193 (client (setcdr client (cons (cons property value) (cdr client))))
194 (t (setq server-clients
195 `((,proc (,property . ,value)) . ,server-clients))))
196 value))
197
198 (defun server-clients-with (property value)
199 "Return a list of clients with PROPERTY set to VALUE."
200 (let (result)
201 (dolist (client server-clients result)
202 (when (equal value (server-client-get client property))
203 (setq result (cons (car client) result))))))
204
205 (defun server-add-client (proc)
206 "Create a client for process PROC, if it doesn't already have one.
207 New clients have no properties."
208 (unless (server-client proc)
209 (setq server-clients (cons (cons proc nil)
210 server-clients))))
211
212 ;;;###autoload
213 (defun server-getenv (variable &optional frame)
214 "Get the value of VARIABLE in the client environment of frame FRAME.
215 VARIABLE should be a string. Value is nil if VARIABLE is undefined in
216 the environment. Otherwise, value is a string.
217
218 If FRAME is an emacsclient frame, then the variable is looked up
219 in the environment of the emacsclient process; otherwise the
220 function consults the environment of the Emacs process.
221
222 If FRAME is nil or missing, then the selected frame is used."
223 (when (not frame) (setq frame (selected-frame)))
224 (let ((client (frame-parameter frame 'client)) env)
225 (if (null client)
226 (getenv variable)
227 (setq env (server-client-get client 'environment))
228 (if (null env)
229 (getenv variable)
230 (cdr (assoc variable env))))))
231
232 (defmacro server-with-client-environment (client vars &rest body)
233 "Evaluate BODY with environment variables VARS set to those of CLIENT.
234 The environment variables are then restored to their previous values.
235
236 VARS should be a list of strings."
237 (declare (indent 2))
238 (let ((oldvalues (make-symbol "oldvalues"))
239 (var (make-symbol "var"))
240 (value (make-symbol "value"))
241 (pair (make-symbol "pair")))
242 `(let (,oldvalues)
243 (dolist (,var (quote ,vars))
244 (let ((,value (cdr (assoc ,var (server-client-get ,client 'environment)))))
245 (setq ,oldvalues (cons (cons ,var (getenv ,var)) ,oldvalues))
246 (setenv ,var ,value)))
247 (unwind-protect
248 (progn ,@body)
249 (dolist (,pair ,oldvalues)
250 (setenv (car ,pair) (cdr ,pair)))))))
251
252 (defun server-delete-client (client &optional noframe)
253 "Delete CLIENT, including its buffers, devices and frames.
254 If NOFRAME is non-nil, let the frames live. (To be used from
255 `delete-frame-functions'."
256 ;; Force a new lookup of client (prevents infinite recursion).
257 (setq client (server-client
258 (if (listp client) (car client) client)))
259 (let ((proc (car client))
260 (buffers (server-client-get client 'buffers)))
261 (when client
262 (setq server-clients (delq client server-clients))
263
264 (dolist (buf buffers)
265 (when (buffer-live-p buf)
266 (with-current-buffer buf
267 ;; Remove PROC from the clients of each buffer.
268 (setq server-buffer-clients (delq proc server-buffer-clients))
269 ;; Kill the buffer if necessary.
270 (when (and (null server-buffer-clients)
271 (or (and server-kill-new-buffers
272 (not server-existing-buffer))
273 (server-temp-file-p)))
274 (kill-buffer (current-buffer))))))
275
276 ;; Delete the client's tty.
277 (let ((device (server-client-get client 'device)))
278 (when (eq (display-live-p device) t)
279 (delete-display device)))
280
281 ;; Delete the client's frames.
282 (unless noframe
283 (dolist (frame (frame-list))
284 (if (and (frame-live-p frame)
285 (equal (car client) (frame-parameter frame 'client)))
286 (delete-frame frame))))
287
288 ;; Delete the client's process.
289 (if (eq (process-status (car client)) 'open)
290 (delete-process (car client)))
291
292 (server-log "Deleted" proc))))
293
294 (defun server-log (string &optional client)
295 "If a *server* buffer exists, write STRING to it for logging purposes.
296 If CLIENT is non-nil, add a description of it to the logged
297 message."
298 (if (get-buffer "*server*")
299 (with-current-buffer "*server*"
300 (goto-char (point-max))
301 (insert (current-time-string)
302 (cond
303 ((null client) " ")
304 ((listp client) (format " %s: " (car client)))
305 (t (format " %s: " client)))
306 string)
307 (or (bolp) (newline)))))
308
309 (defun server-sentinel (proc msg)
310 "The process sentinel for Emacs server connections."
311 ;; If this is a new client process, set the query-on-exit flag to nil
312 ;; for this process (it isn't inherited from the server process).
313 (when (and (eq (process-status proc) 'open)
314 (process-query-on-exit-flag proc))
315 (set-process-query-on-exit-flag proc nil))
316 (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
317 (server-delete-client proc))
318
319 (defun server-handle-delete-frame (frame)
320 "Delete the client connection when the emacsclient frame is deleted."
321 (let ((proc (frame-parameter frame 'client)))
322 (when (and (frame-live-p frame)
323 proc
324 (or (window-system frame)
325 ;; A terminal device must not yet be deleted if
326 ;; there are other frames on it.
327 (< 0 (let ((frame-num 0))
328 (mapc (lambda (f)
329 (when (eq (frame-display f)
330 (frame-display frame))
331 (setq frame-num (1+ frame-num))))
332 (frame-list))
333 frame-num))))
334 (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
335 (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
336
337 (defun server-handle-suspend-tty (device)
338 "Notify the emacsclient process to suspend itself when its tty device is suspended."
339 (dolist (proc (server-clients-with 'device device))
340 (server-log (format "server-handle-suspend-tty, device %s" device) proc)
341 (condition-case err
342 (server-send-string proc "-suspend \n")
343 (file-error (condition-case nil (server-delete-client proc) (error nil))))))
344
345 (defun server-unquote-arg (arg)
346 "Remove &-quotation from ARG.
347 See `server-quote-arg' and `server-process-filter'."
348 (replace-regexp-in-string
349 "&." (lambda (s)
350 (case (aref s 1)
351 (?& "&")
352 (?- "-")
353 (?n "\n")
354 (t " ")))
355 arg t t))
356
357 (defun server-quote-arg (arg)
358 "In ARG, insert a & before each &, each space, each newline, and -.
359 Change spaces to underscores, too, so that the return value never
360 contains a space.
361
362 See `server-unquote-arg' and `server-process-filter'."
363 (replace-regexp-in-string
364 "[-&\n ]" (lambda (s)
365 (case (aref s 0)
366 (?& "&&")
367 (?- "&-")
368 (?\n "&n")
369 (?\s "&_")))
370 arg t t))
371
372 (defun server-send-string (proc string)
373 "A wrapper around `proc-send-string' for logging."
374 (server-log (concat "Sent " string) proc)
375 (process-send-string proc string))
376
377 (defun server-ensure-safe-dir (dir)
378 "Make sure DIR is a directory with no race-condition issues.
379 Creates the directory if necessary and makes sure:
380 - there's no symlink involved
381 - it's owned by us
382 - it's not readable/writable by anybody else."
383 (setq dir (directory-file-name dir))
384 (let ((attrs (file-attributes dir)))
385 (unless attrs
386 (letf (((default-file-modes) ?\700)) (make-directory dir))
387 (setq attrs (file-attributes dir)))
388 ;; Check that it's safe for use.
389 (unless (and (eq t (car attrs)) (eq (nth 2 attrs) (user-uid))
390 (zerop (logand ?\077 (file-modes dir))))
391 (error "The directory %s is unsafe" dir))))
392
393 ;;;###autoload
394 (defun server-start (&optional leave-dead)
395 "Allow this Emacs process to be a server for client processes.
396 This starts a server communications subprocess through which
397 client \"editors\" can send your editing commands to this Emacs
398 job. To use the server, set up the program `emacsclient' in the
399 Emacs distribution as your standard \"editor\".
400
401 Prefix arg LEAVE-DEAD means just kill any existing server
402 communications subprocess."
403 (interactive "P")
404 (when (or
405 (not server-clients)
406 (yes-or-no-p
407 "The current server still has clients; delete them? "))
408 ;; It is safe to get the user id now.
409 (setq server-socket-dir (or server-socket-dir
410 (format "/tmp/emacs%d" (user-uid))))
411 ;; Make sure there is a safe directory in which to place the socket.
412 (server-ensure-safe-dir server-socket-dir)
413 ;; kill it dead!
414 (if server-process
415 (condition-case () (delete-process server-process) (error nil)))
416 ;; Delete the socket files made by previous server invocations.
417 (condition-case ()
418 (delete-file (expand-file-name server-name server-socket-dir))
419 (error nil))
420 ;; If this Emacs already had a server, clear out associated status.
421 (while server-clients
422 (server-delete-client (car server-clients)))
423 (if leave-dead
424 (progn
425 (server-log (message "Server stopped"))
426 (setq server-process nil))
427 (if server-process
428 (server-log (message "Restarting server"))
429 (server-log (message "Starting server")))
430 (letf (((default-file-modes) ?\700))
431 (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
432 (add-hook 'delete-frame-functions 'server-handle-delete-frame)
433 (add-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
434 (add-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
435 (setq server-process
436 (make-network-process
437 :name "server" :family 'local :server t :noquery t
438 :service (expand-file-name server-name server-socket-dir)
439 :sentinel 'server-sentinel :filter 'server-process-filter
440 ;; We must receive file names without being decoded.
441 ;; Those are decoded by server-process-filter according
442 ;; to file-name-coding-system.
443 :coding 'raw-text))))))
444
445 ;;;###autoload
446 (define-minor-mode server-mode
447 "Toggle Server mode.
448 With ARG, turn Server mode on if ARG is positive, off otherwise.
449 Server mode runs a process that accepts commands from the
450 `emacsclient' program. See `server-start' and Info node `Emacs server'."
451 :global t
452 :group 'server
453 :version "22.1"
454 ;; Fixme: Should this check for an existing server socket and do
455 ;; nothing if there is one (for multiple Emacs sessions)?
456 (server-start (not server-mode)))
457 \f
458 (defun server-process-filter (proc string)
459 "Process a request from the server to edit some files.
460 PROC is the server process. STRING consists of a sequence of
461 commands prefixed by a dash. Some commands have arguments; these
462 are &-quoted and need to be decoded by `server-unquote-arg'. The
463 filter parses and executes these commands.
464
465 To illustrate the protocol, here is an example command that
466 emacsclient sends to create a new X frame (note that the whole
467 sequence is sent on a single line):
468
469 -version 21.3.50 xterm
470 -env HOME /home/lorentey
471 -env DISPLAY :0.0
472 ... lots of other -env commands
473 -display :0.0
474 -window-system
475
476 The server normally sends back the single command `-good-version'
477 as a response.
478
479 The following commands are accepted by the server:
480
481 `-version CLIENT-VERSION'
482 Check version numbers between server and client, and signal an
483 error if there is a mismatch. The server replies with
484 `-good-version' to confirm the match.
485
486 `-env NAME VALUE'
487 An environment variable on the client side.
488
489 `-current-frame'
490 Forbid the creation of new frames.
491
492 `-nowait'
493 Request that the next frame created should not be
494 associated with this client.
495
496 `-display DISPLAY'
497 Set the display name to open X frames on.
498
499 `-position LINE[:COLUMN]'
500 Go to the given line and column number
501 in the next file opened.
502
503 `-file FILENAME'
504 Load the given file in the current frame.
505
506 `-eval EXPR'
507 Evaluate EXPR as a Lisp expression and return the
508 result in -print commands.
509
510 `-window-system'
511 Open a new X frame.
512
513 `-tty DEVICENAME TYPE'
514 Open a new tty frame at the client.
515
516 `-resume'
517 Resume this tty frame. The client sends this string when it
518 gets the SIGCONT signal and it is the foreground process on its
519 controlling tty.
520
521 `-suspend'
522 Suspend this tty frame. The client sends this string in
523 response to SIGTSTP and SIGTTOU. The server must cease all I/O
524 on this tty until it gets a -resume command.
525
526 `-ignore COMMENT'
527 Do nothing, but put the comment in the server
528 log. Useful for debugging.
529
530
531 The following commands are accepted by the client:
532
533 `-good-version'
534 Signals a version match between the client and the server.
535
536 `-emacs-pid PID'
537 Describes the process id of the Emacs process;
538 used to forward window change signals to it.
539
540 `-window-system-unsupported'
541 Signals that the server does not
542 support creating X frames; the client must try again with a tty
543 frame.
544
545 `-print STRING'
546 Print STRING on stdout. Used to send values
547 returned by -eval.
548
549 `-error DESCRIPTION'
550 Signal an error (but continue processing).
551
552 `-suspend'
553 Suspend this terminal, i.e., stop the client process. Sent
554 when the user presses C-z."
555 (server-log (concat "Received " string) proc)
556 (let ((prev (process-get proc 'previous-string)))
557 (when prev
558 (setq string (concat prev string))
559 (process-put proc 'previous-string nil)))
560 (condition-case err
561 (progn
562 (server-add-client proc)
563 ;; If the input is multiple lines,
564 ;; process each line individually.
565 (while (string-match "\n" string)
566 (let ((request (substring string 0 (match-beginning 0)))
567 (coding-system (and default-enable-multibyte-characters
568 (or file-name-coding-system
569 default-file-name-coding-system)))
570 (client (server-client proc))
571 current-frame
572 nowait ; t if emacsclient does not want to wait for us.
573 frame ; The frame that was opened for the client (if any).
574 display ; Open the frame on this display.
575 dontkill ; t if the client should not be killed.
576 (files nil)
577 (lineno 1)
578 (columnno 0))
579 ;; Remove this line from STRING.
580 (setq string (substring string (match-end 0)))
581 (while (string-match " *[^ ]* " request)
582 (let ((arg (substring request (match-beginning 0) (1- (match-end 0)))))
583 (setq request (substring request (match-end 0)))
584 (cond
585 ;; -version CLIENT-VERSION:
586 ;; Check version numbers, signal an error if there is a mismatch.
587 ((and (equal "-version" arg)
588 (string-match "\\([0-9.]+\\) " request))
589 (let* ((client-version (match-string 1 request))
590 (truncated-emacs-version
591 (substring emacs-version 0 (length client-version))))
592 (setq request (substring request (match-end 0)))
593 (if (equal client-version truncated-emacs-version)
594 (progn
595 (server-send-string proc "-good-version \n")
596 (server-client-set client 'version client-version))
597 (error (concat "Version mismatch: Emacs is "
598 truncated-emacs-version
599 ", emacsclient is " client-version)))))
600
601 ;; -nowait: Emacsclient won't wait for a result.
602 ((equal "-nowait" arg) (setq nowait t))
603
604 ;; -current-frame: Don't create frames.
605 ((equal "-current-frame" arg) (setq current-frame t))
606
607 ;; -display DISPLAY:
608 ;; Open X frames on the given instead of the default.
609 ((and (equal "-display" arg) (string-match "\\([^ ]*\\) " request))
610 (setq display (match-string 1 request)
611 request (substring request (match-end 0))))
612
613 ;; -window-system: Open a new X frame.
614 ((equal "-window-system" arg)
615 (unless (server-client-get client 'version)
616 (error "Protocol error; make sure to use the correct version of emacsclient"))
617 (unless current-frame
618 (if (fboundp 'x-create-frame)
619 (let ((params (if nowait
620 ;; Flag frame as client-created, but use a dummy client.
621 ;; This will prevent the frame from being deleted when
622 ;; emacsclient quits while also preventing
623 ;; `server-save-buffers-kill-display' from unexpectedly
624 ;; killing emacs on that frame.
625 (list (cons 'client 'nowait))
626 (list (cons 'client proc)))))
627 (setq frame (make-frame-on-display
628 (or display
629 (frame-parameter nil 'device)
630 (getenv "DISPLAY")
631 (error "Please specify display"))
632 params))
633 (server-log (format "%s created" frame) proc)
634 ;; XXX We need to ensure the parameters are
635 ;; really set because Emacs forgets unhandled
636 ;; initialization parameters for X frames at
637 ;; the moment.
638 (modify-frame-parameters frame params)
639 (select-frame frame)
640 (server-client-set client 'frame frame)
641 (server-client-set client 'device (frame-display frame))
642 (setq dontkill t))
643 ;; This emacs does not support X.
644 (server-log "Window system unsupported" proc)
645 (server-send-string proc "-window-system-unsupported \n")
646 (setq dontkill t))))
647
648 ;; -resume: Resume a suspended tty frame.
649 ((equal "-resume" arg)
650 (let ((device (server-client-get client 'device)))
651 (setq dontkill t)
652 (when (eq (display-live-p device) t)
653 (resume-tty device))))
654
655 ;; -suspend: Suspend the client's frame. (In case we
656 ;; get out of sync, and a C-z sends a SIGTSTP to
657 ;; emacsclient.)
658 ((equal "-suspend" arg)
659 (let ((device (server-client-get client 'device)))
660 (setq dontkill t)
661 (when (eq (display-live-p device) t)
662 (suspend-tty device))))
663
664 ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
665 ;; (The given comment appears in the server log.)
666 ((and (equal "-ignore" arg) (string-match "\\([^ ]*\\) " request))
667 (setq dontkill t
668 request (substring request (match-end 0))))
669
670 ;; -tty DEVICE-NAME TYPE: Open a new tty frame at the client.
671 ((and (equal "-tty" arg) (string-match "\\([^ ]*\\) \\([^ ]*\\) " request))
672 (let ((tty (server-unquote-arg (match-string 1 request)))
673 (type (server-unquote-arg (match-string 2 request))))
674 (setq request (substring request (match-end 0)))
675 (unless (server-client-get client 'version)
676 (error "Protocol error; make sure you use the correct version of emacsclient"))
677 (unless current-frame
678 (server-with-client-environment proc
679 ("LANG" "LC_CTYPE" "LC_ALL"
680 ;; For tgetent(3); list according to ncurses(3).
681 "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
682 "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
683 "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
684 "TERMINFO_DIRS" "TERMPATH")
685 (setq frame (make-frame-on-tty tty type
686 ;; Ignore nowait here; we always need to clean
687 ;; up opened ttys when the client dies.
688 `((client . ,proc)))))
689 (select-frame frame)
690 (server-client-set client 'frame frame)
691 (server-client-set client 'tty (display-name frame))
692 (server-client-set client 'device (frame-display frame))
693
694 ;; Reply with our pid.
695 (server-send-string proc (concat "-emacs-pid " (number-to-string (emacs-pid)) "\n"))
696 (setq dontkill t))))
697
698 ;; -position LINE: Go to the given line in the next file.
699 ((and (equal "-position" arg) (string-match "\\(\\+[0-9]+\\) " request))
700 (setq lineno (string-to-number (substring (match-string 1 request) 1))
701 request (substring request (match-end 0))))
702
703 ;; -position LINE:COLUMN: Set point to the given position in the next file.
704 ((and (equal "-position" arg) (string-match "\\+\\([0-9]+\\):\\([0-9]+\\) " request))
705 (setq lineno (string-to-number (match-string 1 request))
706 columnno (string-to-number (match-string 2 request))
707 request (substring request (match-end 0))))
708
709 ;; -file FILENAME: Load the given file.
710 ((and (equal "-file" arg) (string-match "\\([^ ]+\\) " request))
711 (let ((file (server-unquote-arg (match-string 1 request))))
712 (setq request (substring request (match-end 0)))
713 (if coding-system
714 (setq file (decode-coding-string file coding-system)))
715 (setq file (command-line-normalize-file-name file))
716 (push (list file lineno columnno) files)
717 (server-log (format "New file: %s (%d:%d)" file lineno columnno) proc))
718 (setq lineno 1
719 columnno 0))
720
721 ;; -eval EXPR: Evaluate a Lisp expression.
722 ((and (equal "-eval" arg) (string-match "\\([^ ]+\\) " request))
723 (let ((expr (server-unquote-arg (match-string 1 request))))
724 (setq request (substring request (match-end 0)))
725 (if coding-system
726 (setq expr (decode-coding-string expr coding-system)))
727 (let ((v (eval (car (read-from-string expr)))))
728 (when (and (not frame) v)
729 (with-temp-buffer
730 (let ((standard-output (current-buffer)))
731 (pp v)
732 (server-send-string
733 proc (format "-print %s\n"
734 (server-quote-arg
735 (buffer-substring-no-properties (point-min)
736 (point-max)))))))))
737 (setq lineno 1
738 columnno 0)))
739
740 ;; -env NAME VALUE: An environment variable.
741 ((and (equal "-env" arg) (string-match "\\([^ ]+\\) \\([^ ]+\\) " request))
742 (let ((name (server-unquote-arg (match-string 1 request)))
743 (value (server-unquote-arg (match-string 2 request))))
744 (when coding-system
745 (setq name (decode-coding-string name coding-system))
746 (setq value (decode-coding-string value coding-system)))
747 (setq request (substring request (match-end 0)))
748 (server-client-set
749 client 'environment
750 (cons (cons name value)
751 (server-client-get client 'environment)))))
752
753 ;; Unknown command.
754 (t (error "Unknown command: %s" arg)))))
755
756 (let (buffers)
757 (when files
758 (run-hooks 'pre-command-hook)
759 (setq buffers (server-visit-files files client nowait))
760 (run-hooks 'post-command-hook))
761
762 ;; Delete the client if necessary.
763 (cond
764 (nowait
765 ;; Client requested nowait; return immediately.
766 (server-log "Close nowait client" proc)
767 (server-delete-client proc))
768 ((and (not dontkill) (null buffers))
769 ;; This client is empty; get rid of it immediately.
770 (server-log "Close empty client" proc)
771 (server-delete-client proc)))
772 (cond
773 ((or isearch-mode (minibufferp))
774 nil)
775 ((and frame (null buffers))
776 (message "%s" (substitute-command-keys
777 "When done with this frame, type \\[delete-frame]")))
778 ((not (null buffers))
779 (server-switch-buffer (car buffers))
780 (run-hooks 'server-switch-hook)
781 (unless nowait
782 (message "%s" (substitute-command-keys
783 "When done with a buffer, type \\[server-edit]"))))))))
784
785 ;; Save for later any partial line that remains.
786 (when (> (length string) 0)
787 (process-put proc 'previous-string string)))
788 ;; condition-case
789 (error (ignore-errors
790 (server-send-string
791 proc (concat "-error " (server-quote-arg (error-message-string err))))
792 (setq string "")
793 (server-log (error-message-string err) proc)
794 (delete-process proc)))))
795
796 (defun server-goto-line-column (file-line-col)
797 "Move point to the position indicated in FILE-LINE-COL.
798 FILE-LINE-COL should be a three-element list as described in
799 `server-visit-files'."
800 (goto-line (nth 1 file-line-col))
801 (let ((column-number (nth 2 file-line-col)))
802 (if (> column-number 0)
803 (move-to-column (1- column-number)))))
804
805 (defun server-visit-files (files client &optional nowait)
806 "Find FILES and return a list of buffers created.
807 FILES is an alist whose elements are (FILENAME LINENUMBER COLUMNNUMBER).
808 CLIENT is the client that requested this operation.
809 NOWAIT non-nil means this client is not waiting for the results,
810 so don't mark these buffers specially, just visit them normally."
811 ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
812 (let ((last-nonmenu-event t) client-record)
813 ;; Restore the current buffer afterward, but not using save-excursion,
814 ;; because we don't want to save point in this buffer
815 ;; if it happens to be one of those specified by the server.
816 (save-current-buffer
817 (dolist (file files)
818 ;; If there is an existing buffer modified or the file is
819 ;; modified, revert it. If there is an existing buffer with
820 ;; deleted file, offer to write it.
821 (let* ((filen (car file))
822 (obuf (get-file-buffer filen)))
823 (push filen file-name-history)
824 (if (and obuf (set-buffer obuf))
825 (progn
826 (cond ((file-exists-p filen)
827 (if (not (verify-visited-file-modtime obuf))
828 (revert-buffer t nil)))
829 (t
830 (if (y-or-n-p
831 (concat "File no longer exists: " filen
832 ", write buffer to file? "))
833 (write-file filen))))
834 (setq server-existing-buffer t)
835 (server-goto-line-column file))
836 (set-buffer (find-file-noselect filen))
837 (server-goto-line-column file)
838 (run-hooks 'server-visit-hook)))
839 (unless nowait
840 ;; When the buffer is killed, inform the clients.
841 (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
842 (push (car client) server-buffer-clients))
843 (push (current-buffer) client-record)))
844 (unless nowait
845 (server-client-set
846 client 'buffers
847 (nconc (server-client-get client 'buffers) client-record)))
848 client-record))
849 \f
850 (defun server-buffer-done (buffer &optional for-killing)
851 "Mark BUFFER as \"done\" for its client(s).
852 This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
853 NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
854 or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
855 a temp file).
856 FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
857 (let ((next-buffer nil)
858 (killed nil))
859 (dolist (client server-clients)
860 (let ((buffers (server-client-get client 'buffers)))
861 (or next-buffer
862 (setq next-buffer (nth 1 (memq buffer buffers))))
863 (when buffers ; Ignore bufferless clients.
864 (setq buffers (delq buffer buffers))
865 ;; Delete all dead buffers from CLIENT.
866 (dolist (b buffers)
867 (and (bufferp b)
868 (not (buffer-live-p b))
869 (setq buffers (delq b buffers))))
870 (server-client-set client 'buffers buffers)
871 ;; If client now has no pending buffers,
872 ;; tell it that it is done, and forget it entirely.
873 (unless buffers
874 (server-log "Close" client)
875 (server-delete-client client)))))
876 (if (and (bufferp buffer) (buffer-name buffer))
877 ;; We may or may not kill this buffer;
878 ;; if we do, do not call server-buffer-done recursively
879 ;; from kill-buffer-hook.
880 (let ((server-kill-buffer-running t))
881 (with-current-buffer buffer
882 (setq server-buffer-clients nil)
883 (run-hooks 'server-done-hook))
884 ;; Notice whether server-done-hook killed the buffer.
885 (if (null (buffer-name buffer))
886 (setq killed t)
887 ;; Don't bother killing or burying the buffer
888 ;; when we are called from kill-buffer.
889 (unless for-killing
890 (when (and (not killed)
891 server-kill-new-buffers
892 (with-current-buffer buffer
893 (not server-existing-buffer)))
894 (setq killed t)
895 (bury-buffer buffer)
896 (kill-buffer buffer))
897 (unless killed
898 (if (server-temp-file-p buffer)
899 (progn
900 (kill-buffer buffer)
901 (setq killed t))
902 (bury-buffer buffer)))))))
903 (list next-buffer killed)))
904
905 (defun server-temp-file-p (&optional buffer)
906 "Return non-nil if BUFFER contains a file considered temporary.
907 These are files whose names suggest they are repeatedly
908 reused to pass information to another program.
909
910 The variable `server-temp-file-regexp' controls which filenames
911 are considered temporary."
912 (and (buffer-file-name buffer)
913 (string-match server-temp-file-regexp (buffer-file-name buffer))))
914
915 (defun server-done ()
916 "Offer to save current buffer, mark it as \"done\" for clients.
917 This kills or buries the buffer, then returns a list
918 of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
919 as a suggestion for what to select next, or nil.
920 KILLED is t if we killed BUFFER, which happens if it was created
921 specifically for the clients and did not exist before their request for it."
922 (when server-buffer-clients
923 (if (server-temp-file-p)
924 ;; For a temp file, save, and do make a non-numeric backup
925 ;; (unless make-backup-files is nil).
926 (let ((version-control nil)
927 (buffer-backed-up nil))
928 (save-buffer))
929 (if (and (buffer-modified-p)
930 buffer-file-name
931 (y-or-n-p (concat "Save file " buffer-file-name "? ")))
932 (save-buffer)))
933 (server-buffer-done (current-buffer))))
934
935 ;; Ask before killing a server buffer.
936 ;; It was suggested to release its client instead,
937 ;; but I think that is dangerous--the client would proceed
938 ;; using whatever is on disk in that file. -- rms.
939 (defun server-kill-buffer-query-function ()
940 "Ask before killing a server buffer."
941 (or (not server-buffer-clients)
942 (let ((res t))
943 (dolist (proc server-buffer-clients res)
944 (let ((client (server-client proc)))
945 (when (and client (eq (process-status proc) 'open))
946 (setq res nil)))))
947 (yes-or-no-p (format "Buffer `%s' still has clients; kill it? "
948 (buffer-name (current-buffer))))))
949
950 (defun server-kill-emacs-query-function ()
951 "Ask before exiting Emacs it has live clients."
952 (or (not server-clients)
953 (let (live-client)
954 (dolist (client server-clients live-client)
955 (if (memq t (mapcar 'buffer-live-p (server-client-get
956 client 'buffers)))
957 (setq live-client t))))
958 (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
959
960 (defvar server-kill-buffer-running nil
961 "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
962
963 (defun server-kill-buffer ()
964 "Remove the current buffer from its clients' buffer list.
965 Designed to be added to `kill-buffer-hook'."
966 ;; Prevent infinite recursion if user has made server-done-hook
967 ;; call kill-buffer.
968 (or server-kill-buffer-running
969 (and server-buffer-clients
970 (let ((server-kill-buffer-running t))
971 (when server-process
972 (server-buffer-done (current-buffer) t))))))
973 \f
974 (defun server-edit (&optional arg)
975 "Switch to next server editing buffer; say \"Done\" for current buffer.
976 If a server buffer is current, it is marked \"done\" and optionally saved.
977 The buffer is also killed if it did not exist before the clients asked for it.
978 When all of a client's buffers are marked as \"done\", the client is notified.
979
980 Temporary files such as MH <draft> files are always saved and backed up,
981 no questions asked. (The variable `make-backup-files', if nil, still
982 inhibits a backup; you can set it locally in a particular buffer to
983 prevent a backup for it.) The variable `server-temp-file-regexp' controls
984 which filenames are considered temporary.
985
986 If invoked with a prefix argument, or if there is no server process running,
987 starts server process and that is all. Invoked by \\[server-edit]."
988 (interactive "P")
989 (if (or arg
990 (not server-process)
991 (memq (process-status server-process) '(signal exit)))
992 (server-start nil)
993 (apply 'server-switch-buffer (server-done))))
994
995 (defun server-switch-buffer (&optional next-buffer killed-one)
996 "Switch to another buffer, preferably one that has a client.
997 Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
998
999 KILLED-ONE is t in a recursive call if we have already killed one
1000 temp-file server buffer. This means we should avoid the final
1001 \"switch to some other buffer\" since we've already effectively
1002 done that."
1003 (if (null next-buffer)
1004 (progn
1005 (let ((rest server-clients))
1006 (while (and rest (not next-buffer))
1007 (let ((client (car rest)))
1008 ;; Only look at frameless clients.
1009 (when (not (server-client-get client 'frame))
1010 (setq next-buffer (car (server-client-get client 'buffers))))
1011 (setq rest (cdr rest)))))
1012 (and next-buffer (server-switch-buffer next-buffer killed-one))
1013 (unless (or next-buffer killed-one (window-dedicated-p (selected-window)))
1014 ;; (switch-to-buffer (other-buffer))
1015 (message "No server buffers remain to edit")))
1016 (if (not (buffer-live-p next-buffer))
1017 ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
1018 ;; and try the next surviving server buffer.
1019 (apply 'server-switch-buffer (server-buffer-done next-buffer))
1020 ;; OK, we know next-buffer is live, let's display and select it.
1021 (if (functionp server-window)
1022 (funcall server-window next-buffer)
1023 (let ((win (get-buffer-window next-buffer 0)))
1024 (if (and win (not server-window))
1025 ;; The buffer is already displayed: just reuse the window.
1026 (let ((frame (window-frame win)))
1027 (if (eq (frame-visible-p frame) 'icon)
1028 (raise-frame frame))
1029 (select-window win)
1030 (set-buffer next-buffer))
1031 ;; Otherwise, let's find an appropriate window.
1032 (cond ((and (windowp server-window)
1033 (window-live-p server-window))
1034 (select-window server-window))
1035 ((framep server-window)
1036 (if (not (frame-live-p server-window))
1037 (setq server-window (make-frame)))
1038 (select-window (frame-selected-window server-window))))
1039 (if (window-minibuffer-p (selected-window))
1040 (select-window (next-window nil 'nomini 0)))
1041 ;; Move to a non-dedicated window, if we have one.
1042 (when (window-dedicated-p (selected-window))
1043 (select-window
1044 (get-window-with-predicate
1045 (lambda (w)
1046 (and (not (window-dedicated-p w))
1047 (equal (frame-parameter (window-frame w) 'device)
1048 (frame-parameter (selected-frame) 'device))))
1049 'nomini 'visible (selected-window))))
1050 (condition-case nil
1051 (switch-to-buffer next-buffer)
1052 ;; After all the above, we might still have ended up with
1053 ;; a minibuffer/dedicated-window (if there's no other).
1054 (error (pop-to-buffer next-buffer)))))))))
1055
1056 (defun server-save-buffers-kill-display (&optional arg)
1057 "Offer to save each buffer, then kill the current connection.
1058 If the current frame has no client, kill Emacs itself.
1059
1060 With prefix arg, silently save all file-visiting buffers, then kill.
1061
1062 If emacsclient was started with a list of filenames to edit, then
1063 only these files will be asked to be saved."
1064 (interactive "P")
1065 (let ((proc (frame-parameter (selected-frame) 'client))
1066 (frame (selected-frame)))
1067 (if proc
1068 (let ((buffers (server-client-get proc 'buffers)))
1069 ;; If client is bufferless, emulate a normal Emacs session
1070 ;; exit and offer to save all buffers. Otherwise, offer to
1071 ;; save only the buffers belonging to the client.
1072 (save-some-buffers arg
1073 (if buffers
1074 (lambda () (memq (current-buffer) buffers))
1075 t))
1076 (server-delete-client proc)
1077 (when (frame-live-p frame)
1078 (delete-frame frame)))
1079 (save-buffers-kill-emacs))))
1080
1081 (define-key ctl-x-map "#" 'server-edit)
1082
1083 (defun server-unload-hook ()
1084 "Unload the server library."
1085 (server-start t)
1086 (remove-hook 'suspend-tty-functions 'server-handle-suspend-tty)
1087 (remove-hook 'delete-frame-functions 'server-handle-delete-frame)
1088 (remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
1089 (remove-hook 'kill-emacs-query-functions 'server-kill-emacs-query-function)
1090 (remove-hook 'kill-buffer-hook 'server-kill-buffer))
1091
1092 (add-hook 'server-unload-hook 'server-unload-hook)
1093 \f
1094 (provide 'server)
1095
1096 ;;; arch-tag: 1f7ecb42-f00a-49f8-906d-61995d84c8d6
1097 ;;; server.el ends here