Added -w option to emacsclient for opening a new X frame.
[bpt/emacs.git] / lib-src / emacsclient.c
1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2003, 2004
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
21
22
23 #define NO_SHORTNAMES
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #undef signal
30
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #ifdef VMS
39 # include "vms-pwd.h"
40 #else
41 # include <pwd.h>
42 #endif /* not VMS */
43
44 #include <signal.h>
45 #include <errno.h>
46
47 \f
48 char *getenv (), *getwd ();
49 char *getcwd ();
50
51 /* This is defined with -D from the compilation command,
52 which extracts it from ../lisp/version.el. */
53
54 #ifndef VERSION
55 #define VERSION "unspecified"
56 #endif
57 \f
58 /* Name used to invoke this program. */
59 char *progname;
60
61 /* The first argument to main. */
62 int main_argc;
63
64 /* The second argument to main. */
65 char **main_argv;
66
67 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
68 int nowait = 0;
69
70 /* Nonzero means args are expressions to be evaluated. --eval. */
71 int eval = 0;
72
73 /* Nonzero means open a new graphical frame. */
74 int window_system = 0;
75
76 /* The display on which Emacs should work. --display. */
77 char *display = NULL;
78
79 /* Nonzero means open a new Emacs frame on the current terminal. */
80 int tty = 0;
81
82 /* If non-NULL, the name of an editor to fallback to if the server
83 is not running. --alternate-editor. */
84 const char * alternate_editor = NULL;
85
86 /* If non-NULL, the filename of the UNIX socket. */
87 char *socket_name = NULL;
88
89 void print_help_and_exit ();
90
91 struct option longopts[] =
92 {
93 { "no-wait", no_argument, NULL, 'n' },
94 { "eval", no_argument, NULL, 'e' },
95 { "help", no_argument, NULL, 'H' },
96 { "version", no_argument, NULL, 'V' },
97 { "tty", no_argument, NULL, 't' },
98 { "window-system", no_argument, NULL, 'w' },
99 { "alternate-editor", required_argument, NULL, 'a' },
100 { "socket-name", required_argument, NULL, 's' },
101 { "display", required_argument, NULL, 'd' },
102 { 0, 0, 0, 0 }
103 };
104
105 /* Decode the options from argv and argc.
106 The global variable `optind' will say how many arguments we used up. */
107
108 void
109 decode_options (argc, argv)
110 int argc;
111 char **argv;
112 {
113 alternate_editor = getenv ("ALTERNATE_EDITOR");
114 display = getenv ("DISPLAY");
115
116 while (1)
117 {
118 int opt = getopt_long (argc, argv,
119 "VHnea:s:d:tw", longopts, 0);
120
121 if (opt == EOF)
122 break;
123
124 switch (opt)
125 {
126 case 0:
127 /* If getopt returns 0, then it has already processed a
128 long-named option. We should do nothing. */
129 break;
130
131 case 'a':
132 alternate_editor = optarg;
133 break;
134
135 case 's':
136 socket_name = optarg;
137 break;
138
139 case 'd':
140 display = optarg;
141 break;
142
143 case 'n':
144 nowait = 1;
145 break;
146
147 case 'e':
148 eval = 1;
149 break;
150
151 case 'V':
152 printf ("emacsclient %s\n", VERSION);
153 exit (0);
154 break;
155
156 case 't':
157 tty = 1;
158 window_system = 0;
159 break;
160
161 case 'w':
162 window_system = 1;
163 tty = 0;
164 break;
165
166 case 'H':
167 print_help_and_exit ();
168 break;
169
170 default:
171 fprintf (stderr, "Try `%s --help' for more information\n", progname);
172 exit (1);
173 break;
174 }
175 }
176
177 if (tty) {
178 nowait = 0;
179 display = 0;
180 }
181 }
182
183 void
184 print_help_and_exit ()
185 {
186 printf (
187 "Usage: %s [OPTIONS] FILE...\n\
188 Tell the Emacs server to visit the specified files.\n\
189 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
190 \n\
191 The following OPTIONS are accepted:\n\
192 -V, --version Just print a version info and return\n\
193 -H, --help Print this usage information message\n\
194 -t, --tty Open a new Emacs frame on the current terminal\n\
195 -w, --window-system Open a new graphical Emacs frame\n\
196 -n, --no-wait Don't wait for the server to return\n\
197 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
198 -d, --display=DISPLAY Visit the file in the given display\n\
199 -s, --socket-name=FILENAME\n\
200 Set the filename of the UNIX socket for communication\n\
201 -a, --alternate-editor=EDITOR\n\
202 Editor to fallback to if the server is not running\n\
203 \n\
204 Report bugs to bug-gnu-emacs@gnu.org.\n", progname);
205 exit (0);
206 }
207
208 /* In NAME, insert a & before each &, each space, each newline, and
209 any initial -. Change spaces to underscores, too, so that the
210 return value never contains a space. */
211
212 void
213 quote_file_name (name, stream)
214 char *name;
215 FILE *stream;
216 {
217 char *copy = (char *) malloc (strlen (name) * 2 + 1);
218 char *p, *q;
219
220 p = name;
221 q = copy;
222 while (*p)
223 {
224 if (*p == ' ')
225 {
226 *q++ = '&';
227 *q++ = '_';
228 p++;
229 }
230 else if (*p == '\n')
231 {
232 *q++ = '&';
233 *q++ = 'n';
234 p++;
235 }
236 else
237 {
238 if (*p == '&' || (*p == '-' && p == name))
239 *q++ = '&';
240 *q++ = *p++;
241 }
242 }
243 *q++ = 0;
244
245 fprintf (stream, copy);
246
247 free (copy);
248 }
249
250 /* Like malloc but get fatal error if memory is exhausted. */
251
252 long *
253 xmalloc (size)
254 unsigned int size;
255 {
256 long *result = (long *) malloc (size);
257 if (result == NULL)
258 {
259 perror ("malloc");
260 exit (1);
261 }
262 return result;
263 }
264 \f
265 /*
266 Try to run a different command, or --if no alternate editor is
267 defined-- exit with an errorcode.
268 */
269 void
270 fail (void)
271 {
272 if (alternate_editor)
273 {
274 int i = optind - 1;
275 execvp (alternate_editor, main_argv + i);
276 return;
277 }
278 else
279 {
280 exit (1);
281 }
282 }
283
284 int emacs_pid;
285
286 /* A signal handler that passes the signal to the Emacs process.
287 Useful for SIGWINCH. */
288
289 SIGTYPE
290 pass_signal_to_emacs (int signalnum)
291 {
292 int old_errno = errno;
293
294 if (emacs_pid)
295 kill (emacs_pid, signalnum);
296
297 signal (signalnum, pass_signal_to_emacs);
298 errno = old_errno;
299 }
300
301 /* Set up signal handlers before opening a frame on the current tty. */
302
303 void
304 init_signals (void)
305 {
306 /* Set up signal handlers. */
307 signal (SIGWINCH, pass_signal_to_emacs);
308
309 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
310 deciding which terminal the signal came from. C-g is now a
311 normal input event on secondary terminals. */
312 #if 0
313 signal (SIGINT, pass_signal_to_emacs);
314 signal (SIGQUIT, pass_signal_to_emacs);
315 #endif
316 }
317
318 \f
319 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
320
321 int
322 main (argc, argv)
323 int argc;
324 char **argv;
325 {
326 fprintf (stderr, "%s: Sorry, the Emacs server is supported only\n",
327 argv[0]);
328 fprintf (stderr, "on systems with Berkeley sockets.\n");
329
330 fail ();
331 }
332
333 #else /* HAVE_SOCKETS */
334
335 #include <sys/types.h>
336 #include <sys/socket.h>
337 #include <sys/un.h>
338 #include <sys/stat.h>
339 #include <errno.h>
340
341 extern char *strerror ();
342 extern int errno;
343
344 /* Three possibilities:
345 2 - can't be `stat'ed (sets errno)
346 1 - isn't owned by us
347 0 - success: none of the above */
348
349 static int
350 socket_status (socket_name)
351 char *socket_name;
352 {
353 struct stat statbfr;
354
355 if (stat (socket_name, &statbfr) == -1)
356 return 2;
357
358 if (statbfr.st_uid != geteuid ())
359 return 1;
360
361 return 0;
362 }
363
364 /* Returns 1 if PREFIX is a prefix of STRING. */
365 static int
366 strprefix (char *prefix, char *string)
367 {
368 int i;
369 if (! prefix)
370 return 1;
371
372 if (!string)
373 return 0;
374
375 for (i = 0; prefix[i]; i++)
376 if (!string[i] || string[i] != prefix[i])
377 return 0;
378 return 1;
379 }
380
381 int
382 main (argc, argv)
383 int argc;
384 char **argv;
385 {
386 int s, i, needlf = 0;
387 FILE *out, *in;
388 struct sockaddr_un server;
389 char *cwd, *str;
390 char string[BUFSIZ];
391
392 main_argc = argc;
393 main_argv = argv;
394 progname = argv[0];
395
396 /* Process options. */
397 decode_options (argc, argv);
398
399 if ((argc - optind < 1) && !eval && !tty && !window_system)
400 {
401 fprintf (stderr, "%s: file name or argument required\n", progname);
402 fprintf (stderr, "Try `%s --help' for more information\n", progname);
403 exit (1);
404 }
405
406 /*
407 * Open up an AF_UNIX socket in this person's home directory
408 */
409
410 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
411 {
412 fprintf (stderr, "%s: ", argv[0]);
413 perror ("socket");
414 fail ();
415 }
416
417 server.sun_family = AF_UNIX;
418
419 {
420 int sock_status = 0;
421 int default_sock = !socket_name;
422 int saved_errno = 0;
423
424 char *server_name = "server";
425
426 if (socket_name && !index (socket_name, '/') && !index (socket_name, '\\'))
427 { /* socket_name is a file name component. */
428 server_name = socket_name;
429 socket_name = NULL;
430 default_sock = 1; /* Try both UIDs. */
431 }
432
433 if (default_sock)
434 {
435 socket_name = alloca (100 + strlen (server_name));
436 sprintf (socket_name, "/tmp/emacs%d/%s",
437 (int) geteuid (), server_name);
438 }
439
440 if (strlen (socket_name) < sizeof (server.sun_path))
441 strcpy (server.sun_path, socket_name);
442 else
443 {
444 fprintf (stderr, "%s: socket-name %s too long",
445 argv[0], socket_name);
446 fail ();
447 }
448
449 /* See if the socket exists, and if it's owned by us. */
450 sock_status = socket_status (server.sun_path);
451 saved_errno = errno;
452 if (sock_status && default_sock)
453 {
454 /* Failing that, see if LOGNAME or USER exist and differ from
455 our euid. If so, look for a socket based on the UID
456 associated with the name. This is reminiscent of the logic
457 that init_editfns uses to set the global Vuser_full_name. */
458
459 char *user_name = (char *) getenv ("LOGNAME");
460
461 if (!user_name)
462 user_name = (char *) getenv ("USER");
463
464 if (user_name)
465 {
466 struct passwd *pw = getpwnam (user_name);
467
468 if (pw && (pw->pw_uid != geteuid ()))
469 {
470 /* We're running under su, apparently. */
471 socket_name = alloca (100 + strlen (server_name));
472 sprintf (socket_name, "/tmp/emacs%d/%s",
473 (int) pw->pw_uid, server_name);
474
475 if (strlen (socket_name) < sizeof (server.sun_path))
476 strcpy (server.sun_path, socket_name);
477 else
478 {
479 fprintf (stderr, "%s: socket-name %s too long",
480 argv[0], socket_name);
481 exit (1);
482 }
483
484 sock_status = socket_status (server.sun_path);
485 saved_errno = errno;
486 }
487 else
488 errno = saved_errno;
489 }
490 }
491
492 switch (sock_status)
493 {
494 case 1:
495 /* There's a socket, but it isn't owned by us. This is OK if
496 we are root. */
497 if (0 != geteuid ())
498 {
499 fprintf (stderr, "%s: Invalid socket owner\n", argv[0]);
500 fail ();
501 }
502 break;
503
504 case 2:
505 /* `stat' failed */
506 if (saved_errno == ENOENT)
507 fprintf (stderr,
508 "%s: Can't find socket; have you started the server?\n\
509 To start the server in Emacs, type \"M-x server-start\".\n",
510 argv[0]);
511 else
512 fprintf (stderr, "%s: Can't stat %s: %s\n",
513 argv[0], server.sun_path, strerror (saved_errno));
514 fail ();
515 break;
516 }
517 }
518
519 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
520 < 0)
521 {
522 fprintf (stderr, "%s: ", argv[0]);
523 perror ("connect");
524 fail ();
525 }
526
527 /* We use the stream OUT to send our command to the server. */
528 if ((out = fdopen (s, "r+")) == NULL)
529 {
530 fprintf (stderr, "%s: ", argv[0]);
531 perror ("fdopen");
532 fail ();
533 }
534
535 /* We use the stream IN to read the response.
536 We used to use just one stream for both output and input
537 on the socket, but reversing direction works nonportably:
538 on some systems, the output appears as the first input;
539 on other systems it does not. */
540 if ((in = fdopen (s, "r+")) == NULL)
541 {
542 fprintf (stderr, "%s: ", argv[0]);
543 perror ("fdopen");
544 fail ();
545 }
546
547 #ifdef HAVE_GETCWD
548 cwd = getcwd (string, sizeof string);
549 #else
550 cwd = getwd (string);
551 #endif
552 if (cwd == 0)
553 {
554 /* getwd puts message in STRING if it fails. */
555
556 #ifdef HAVE_GETCWD
557 fprintf (stderr, "%s: %s (%s)\n", argv[0],
558 "Cannot get current working directory", strerror (errno));
559 #else
560 fprintf (stderr, "%s: %s (%s)\n", argv[0], string, strerror (errno));
561 #endif
562 fail ();
563 }
564
565 if (nowait)
566 fprintf (out, "-nowait ");
567
568 if (eval)
569 fprintf (out, "-eval ");
570
571 if (display)
572 {
573 fprintf (out, "-display ");
574 quote_file_name (display, out);
575 fprintf (out, " ");
576 }
577
578 if (tty)
579 {
580 char *tty_name = ttyname (fileno (stdin));
581 if (! tty_name)
582 fail ();
583
584 init_signals ();
585
586 fprintf (out, "-tty ");
587 quote_file_name (tty_name, out);
588 fprintf (out, " ");
589 quote_file_name (getenv("TERM"), out);
590 fprintf (out, " ");
591 }
592
593 if (window_system)
594 fprintf (out, "-window-system ");
595
596 if ((argc - optind > 0))
597 {
598 for (i = optind; i < argc; i++)
599 {
600 if (eval)
601 ; /* Don't prepend any cwd or anything like that. */
602 else if (*argv[i] == '+')
603 {
604 char *p = argv[i] + 1;
605 while (isdigit ((unsigned char) *p) || *p == ':') p++;
606 if (*p != 0)
607 {
608 quote_file_name (cwd, out);
609 fprintf (out, "/");
610 }
611 }
612 else if (*argv[i] != '/')
613 {
614 quote_file_name (cwd, out);
615 fprintf (out, "/");
616 }
617
618 quote_file_name (argv[i], out);
619 fprintf (out, " ");
620 }
621 }
622 else
623 {
624 if (!tty && !window_system)
625 {
626 while ((str = fgets (string, BUFSIZ, stdin)))
627 {
628 quote_file_name (str, out);
629 }
630 fprintf (out, " ");
631 }
632 }
633
634 fprintf (out, "\n");
635 fflush (out);
636
637 /* Maybe wait for an answer. */
638 if (nowait)
639 {
640 return 0;
641 }
642
643 if (!eval && !tty)
644 {
645 printf ("Waiting for Emacs...");
646 needlf = 2;
647 }
648 fflush (stdout);
649
650 /* Now, wait for an answer and print any messages. */
651 while ((str = fgets (string, BUFSIZ, in)))
652 {
653 if (strprefix ("-emacs-pid ", str))
654 {
655 emacs_pid = strtol (string + strlen ("-emacs-pid"), NULL, 10);
656 }
657 else if (strprefix ("-print ", str))
658 {
659 if (needlf == 2)
660 printf ("\n");
661 printf ("%s", str + strlen ("-print "));
662 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
663 }
664 else if (strprefix ("-error ", str))
665 {
666 if (needlf == 2)
667 printf ("\n");
668 printf ("*ERROR*: %s", str + strlen ("-print "));
669 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
670 }
671 else
672 {
673 if (needlf == 2)
674 printf ("\n");
675 printf ("*ERROR*: Unknown message: %s", str);
676 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
677 }
678 }
679
680 if (needlf)
681 printf ("\n");
682 fflush (stdout);
683
684 return 0;
685 }
686
687 #endif /* HAVE_SOCKETS */
688 \f
689 #ifndef HAVE_STRERROR
690 char *
691 strerror (errnum)
692 int errnum;
693 {
694 extern char *sys_errlist[];
695 extern int sys_nerr;
696
697 if (errnum >= 0 && errnum < sys_nerr)
698 return sys_errlist[errnum];
699 return (char *) "Unknown error";
700 }
701
702 #endif /* ! HAVE_STRERROR */
703
704 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
705 (do not change this comment) */