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