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