]>
code.delx.au - gnu-emacs/blob - lib-src/emacsclient.c
1 /* Client process that communicates with GNU Emacs acting as server.
2 Copyright (C) 1986, 1987, 1994, 1999, 2000, 2001, 2002, 2003, 2004,
3 2005 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
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)
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.
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., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
48 char *getenv (), *getwd ();
52 #define VERSION "unspecified"
55 /* Name used to invoke this program. */
58 /* The first argument to main. */
61 /* The second argument to main. */
64 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
67 /* Nonzero means args are expressions to be evaluated. --eval. */
70 /* Nonzero means don't open a new frame. --current-frame. */
71 int current_frame
= 0;
73 /* Nonzero means open a new graphical frame. */
74 int window_system
= 0;
76 /* The display on which Emacs should work. --display. */
79 /* Nonzero means open a new Emacs frame on the current terminal. */
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
;
86 /* If non-NULL, the filename of the UNIX socket. */
87 char *socket_name
= NULL
;
89 void print_help_and_exit ();
91 struct option longopts
[] =
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 { "current-frame", no_argument
, NULL
, 'c' },
99 { "alternate-editor", required_argument
, NULL
, 'a' },
100 { "socket-name", required_argument
, NULL
, 's' },
101 { "display", required_argument
, NULL
, 'd' },
105 /* Decode the options from argv and argc.
106 The global variable `optind' will say how many arguments we used up. */
109 decode_options (argc
, argv
)
113 alternate_editor
= getenv ("ALTERNATE_EDITOR");
114 display
= getenv ("DISPLAY");
115 if (display
&& strlen (display
) == 0)
120 int opt
= getopt_long (argc
, argv
,
121 "VHnea:s:d:tc", longopts
, 0);
129 /* If getopt returns 0, then it has already processed a
130 long-named option. We should do nothing. */
134 alternate_editor
= optarg
;
138 socket_name
= optarg
;
154 printf ("emacsclient %s\n", VERSION
);
167 print_help_and_exit ();
171 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
182 /* --no-wait implies --current-frame on ttys when there are file
183 arguments or expressions given. */
184 if (nowait
&& tty
&& argc
- optind
> 0)
198 print_help_and_exit ()
201 "Usage: %s [OPTIONS] FILE...\n\
202 Tell the Emacs server to visit the specified files.\n\
203 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
205 The following OPTIONS are accepted:\n\
206 -V, --version Just print a version info and return\n\
207 -H, --help Print this usage information message\n\
208 -t, --tty Open a new Emacs frame on the current terminal\n\
209 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
210 -n, --no-wait Don't wait for the server to return\n\
211 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
212 -d, --display=DISPLAY Visit the file in the given display\n\
213 -s, --socket-name=FILENAME\n\
214 Set the filename of the UNIX socket for communication\n\
215 -a, --alternate-editor=EDITOR\n\
216 Editor to fallback to if the server is not running\n\
218 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
222 /* Like malloc but get fatal error if memory is exhausted. */
228 long *result
= (long *) malloc (size
);
237 /* Like strdup but get a fatal error if memory is exhausted. */
240 xstrdup (const char *s
)
242 char *result
= strdup (s
);
251 /* In STR, insert a & before each &, each space, each newline, and
252 any initial -. Change spaces to underscores, too, so that the
253 return value never contains a space.
255 Does not change the string. Outputs the result to STREAM. */
258 quote_argument (str
, stream
)
262 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
283 if (*p
== '&' || (*p
== '-' && p
== str
))
290 fprintf (stream
, "%s", copy
);
296 /* The inverse of quote_argument. Removes quoting in string STR by
297 modifying the string in place. Returns STR. */
300 unquote_argument (str
)
332 Try to run a different command, or --if no alternate editor is
333 defined-- exit with an errorcode.
338 if (alternate_editor
)
341 execvp (alternate_editor
, main_argv
+ i
);
350 /* The process id of Emacs. */
353 /* File handles for communicating with Emacs. */
356 /* A signal handler that passes the signal to the Emacs process.
357 Useful for SIGWINCH. */
360 pass_signal_to_emacs (int signalnum
)
362 int old_errno
= errno
;
365 kill (emacs_pid
, signalnum
);
367 signal (signalnum
, pass_signal_to_emacs
);
371 /* Signal handler for SIGCONT; notify the Emacs process that it can
372 now resume our tty frame. */
375 handle_sigcont (int signalnum
)
377 int old_errno
= errno
;
379 if (tcgetpgrp (1) == getpgrp ())
381 /* We are in the foreground. */
382 fprintf (out
, "-resume \n");
384 fsync (fileno (out
));
388 /* We are in the background; cancel the continue. */
389 kill (getpid (), SIGSTOP
);
392 signal (signalnum
, handle_sigcont
);
396 /* Signal handler for SIGTSTP; notify the Emacs process that we are
397 going to sleep. Normally the suspend is initiated by Emacs via
398 server-handle-suspend-tty, but if the server gets out of sync with
399 reality, we may get a SIGTSTP on C-z. Handling this signal and
400 notifying Emacs about it should get things under control again. */
403 handle_sigtstp (int signalnum
)
405 int old_errno
= errno
;
410 fprintf (out
, "-suspend \n");
412 fsync (fileno (out
));
415 /* Unblock this signal and call the default handler by temprarily
416 changing the handler and resignalling. */
417 sigprocmask (SIG_BLOCK
, NULL
, &set
);
418 sigdelset (&set
, signalnum
);
419 signal (signalnum
, SIG_DFL
);
420 kill (getpid (), signalnum
);
421 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
422 signal (signalnum
, handle_sigtstp
);
427 /* Set up signal handlers before opening a frame on the current tty. */
432 /* Set up signal handlers. */
433 signal (SIGWINCH
, pass_signal_to_emacs
);
435 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
436 deciding which terminal the signal came from. C-g is now a
437 normal input event on secondary terminals. */
439 signal (SIGINT
, pass_signal_to_emacs
);
440 signal (SIGQUIT
, pass_signal_to_emacs
);
443 signal (SIGCONT
, handle_sigcont
);
444 signal (SIGTSTP
, handle_sigtstp
);
445 signal (SIGTTOU
, handle_sigtstp
);
449 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
456 fprintf (stderr
, "%s: Sorry, the Emacs server is supported only\n",
458 fprintf (stderr
, "on systems with Berkeley sockets.\n");
463 #else /* HAVE_SOCKETS */
465 #include <sys/types.h>
466 #include <sys/socket.h>
468 #include <sys/stat.h>
471 extern char *strerror ();
474 /* Three possibilities:
475 2 - can't be `stat'ed (sets errno)
476 1 - isn't owned by us
477 0 - success: none of the above */
480 socket_status (socket_name
)
485 if (stat (socket_name
, &statbfr
) == -1)
488 if (statbfr
.st_uid
!= geteuid ())
494 /* Returns 1 if PREFIX is a prefix of STRING. */
496 strprefix (char *prefix
, char *string
)
505 for (i
= 0; prefix
[i
]; i
++)
506 if (!string
[i
] || string
[i
] != prefix
[i
])
516 int s
, i
, needlf
= 0;
517 struct sockaddr_un server
;
525 /* Process options. */
526 decode_options (argc
, argv
);
528 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
530 fprintf (stderr
, "%s: file name or argument required\n", progname
);
531 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
536 * Open up an AF_UNIX socket in this person's home directory
539 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
541 fprintf (stderr
, "%s: ", argv
[0]);
546 server
.sun_family
= AF_UNIX
;
550 int default_sock
= !socket_name
;
553 char *server_name
= "server";
555 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
556 { /* socket_name is a file name component. */
557 server_name
= socket_name
;
559 default_sock
= 1; /* Try both UIDs. */
564 socket_name
= alloca (100 + strlen (server_name
));
565 sprintf (socket_name
, "/tmp/emacs%d/%s",
566 (int) geteuid (), server_name
);
569 if (strlen (socket_name
) < sizeof (server
.sun_path
))
570 strcpy (server
.sun_path
, socket_name
);
573 fprintf (stderr
, "%s: socket-name %s too long",
574 argv
[0], socket_name
);
578 /* See if the socket exists, and if it's owned by us. */
579 sock_status
= socket_status (server
.sun_path
);
581 if (sock_status
&& default_sock
)
583 /* Failing that, see if LOGNAME or USER exist and differ from
584 our euid. If so, look for a socket based on the UID
585 associated with the name. This is reminiscent of the logic
586 that init_editfns uses to set the global Vuser_full_name. */
588 char *user_name
= (char *) getenv ("LOGNAME");
591 user_name
= (char *) getenv ("USER");
595 struct passwd
*pw
= getpwnam (user_name
);
597 if (pw
&& (pw
->pw_uid
!= geteuid ()))
599 /* We're running under su, apparently. */
600 socket_name
= alloca (100 + strlen (server_name
));
601 sprintf (socket_name
, "/tmp/emacs%d/%s",
602 (int) pw
->pw_uid
, server_name
);
604 if (strlen (socket_name
) < sizeof (server
.sun_path
))
605 strcpy (server
.sun_path
, socket_name
);
608 fprintf (stderr
, "%s: socket-name %s too long",
609 argv
[0], socket_name
);
613 sock_status
= socket_status (server
.sun_path
);
624 /* There's a socket, but it isn't owned by us. This is OK if
628 fprintf (stderr
, "%s: Invalid socket owner\n", argv
[0]);
635 if (saved_errno
== ENOENT
)
637 "%s: can't find socket; have you started the server?\n\
638 To start the server in Emacs, type \"M-x server-start\".\n",
641 fprintf (stderr
, "%s: can't stat %s: %s\n",
642 argv
[0], server
.sun_path
, strerror (saved_errno
));
648 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
651 fprintf (stderr
, "%s: ", argv
[0]);
656 /* We use the stream OUT to send our commands to the server. */
657 if ((out
= fdopen (s
, "r+")) == NULL
)
659 fprintf (stderr
, "%s: ", argv
[0]);
664 /* We use the stream IN to read the responses.
665 We used to use just one stream for both output and input
666 on the socket, but reversing direction works nonportably:
667 on some systems, the output appears as the first input;
668 on other systems it does not. */
669 if ((in
= fdopen (s
, "r+")) == NULL
)
671 fprintf (stderr
, "%s: ", argv
[0]);
677 cwd
= getcwd (string
, sizeof string
);
679 cwd
= getwd (string
);
683 /* getwd puts message in STRING if it fails. */
686 fprintf (stderr
, "%s: %s (%s)\n", argv
[0],
687 "cannot get current working directory", strerror (errno
));
689 fprintf (stderr
, "%s: %s (%s)\n", argv
[0], string
, strerror (errno
));
694 /* First of all, send our version number for verification. */
695 fprintf (out
, "-version %s ", VERSION
);
697 /* Send over our environment. */
700 extern char **environ
;
702 for (i
= 0; environ
[i
]; i
++)
704 char *name
= xstrdup (environ
[i
]);
705 char *value
= strchr (name
, '=');
706 fprintf (out
, "-env ");
707 quote_argument (environ
[i
], out
);
714 fprintf (out
, "-nowait ");
717 fprintf (out
, "-current-frame ");
721 fprintf (out
, "-display ");
722 quote_argument (display
, out
);
728 char *tty_name
= ttyname (fileno (stdin
));
729 char *type
= getenv ("TERM");
733 fprintf (stderr
, "%s: could not get terminal name\n", progname
);
739 fprintf (stderr
, "%s: please set the TERM variable to your terminal type\n",
744 if (! strcmp (type
, "eterm"))
746 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
747 fprintf (stderr
, "%s: opening a frame in an Emacs term buffer"
748 " is not supported\n", progname
);
754 fprintf (out
, "-tty ");
755 quote_argument (tty_name
, out
);
757 quote_argument (type
, out
);
762 fprintf (out
, "-window-system ");
764 if ((argc
- optind
> 0))
766 for (i
= optind
; i
< argc
; i
++)
772 /* Don't prepend any cwd or anything like that. */
773 fprintf (out
, "-eval ");
774 quote_argument (argv
[i
], out
);
781 char *p
= argv
[i
] + 1;
782 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
785 fprintf (out
, "-position ");
786 quote_argument (argv
[i
], out
);
793 else if (*argv
[i
] != '/')
796 fprintf (out
, "-file ");
799 quote_argument (cwd
, out
);
802 quote_argument (argv
[i
], out
);
808 if (!tty
&& !window_system
)
810 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
813 fprintf (out
, "-eval ");
815 fprintf (out
, "-file ");
816 quote_argument (str
, out
);
824 fsync (fileno (out
));
826 /* Wait for an answer. */
827 if (!eval
&& !tty
&& !nowait
)
829 printf ("Waiting for Emacs...");
835 /* Now, wait for an answer and print any messages. */
836 while ((str
= fgets (string
, BUFSIZ
, in
)))
838 char *p
= str
+ strlen (str
) - 1;
839 while (p
> str
&& *p
== '\n')
842 if (strprefix ("-good-version ", str
))
844 /* -good-version: The versions match. */
846 else if (strprefix ("-emacs-pid ", str
))
848 /* -emacs-pid PID: The process id of the Emacs process. */
849 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
851 else if (strprefix ("-window-system-unsupported ", str
))
853 /* -window-system-unsupported: Emacs was compiled without X
854 support. Try again on the terminal. */
860 else if (strprefix ("-print ", str
))
862 /* -print STRING: Print STRING on the terminal. */
863 str
= unquote_argument (str
+ strlen ("-print "));
867 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
869 else if (strprefix ("-error ", str
))
871 /* -error DESCRIPTION: Signal an error on the terminal. */
872 str
= unquote_argument (str
+ strlen ("-error "));
875 printf ("*ERROR*: %s", str
);
876 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
878 else if (strprefix ("-suspend ", str
))
880 /* -suspend: Suspend this terminal, i.e., stop the process. */
888 /* Unknown command. */
891 printf ("*ERROR*: Unknown message: %s", str
);
892 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
904 #endif /* HAVE_SOCKETS */
906 #ifndef HAVE_STRERROR
911 extern char *sys_errlist
[];
914 if (errnum
>= 0 && errnum
< sys_nerr
)
915 return sys_errlist
[errnum
];
916 return (char *) "Unknown error";
919 #endif /* ! HAVE_STRERROR */
921 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
922 (do not change this comment) */
924 /* emacsclient.c ends here */