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, 2006 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. */
50 #define DIRECTORY_SEP '/'
52 #ifndef IS_DIRECTORY_SEP
53 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
57 #define IS_DEVICE_SEP(_c_) 0
59 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
63 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
68 char *getenv (), *getwd ();
72 #define VERSION "unspecified"
75 /* Name used to invoke this program. */
78 /* The first argument to main. */
81 /* The second argument to main. */
84 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
87 /* Nonzero means args are expressions to be evaluated. --eval. */
90 /* Nonzero means don't open a new frame. --current-frame. */
91 int current_frame
= 0;
93 /* Nonzero means open a new graphical frame. */
94 int window_system
= 0;
96 /* The display on which Emacs should work. --display. */
99 /* Nonzero means open a new Emacs frame on the current terminal. */
102 /* If non-NULL, the name of an editor to fallback to if the server
103 is not running. --alternate-editor. */
104 const char * alternate_editor
= NULL
;
106 /* If non-NULL, the filename of the UNIX socket. */
107 char *socket_name
= NULL
;
109 void print_help_and_exit ();
111 struct option longopts
[] =
113 { "no-wait", no_argument
, NULL
, 'n' },
114 { "eval", no_argument
, NULL
, 'e' },
115 { "help", no_argument
, NULL
, 'H' },
116 { "version", no_argument
, NULL
, 'V' },
117 { "tty", no_argument
, NULL
, 't' },
118 { "current-frame", no_argument
, NULL
, 'c' },
119 { "alternate-editor", required_argument
, NULL
, 'a' },
120 { "socket-name", required_argument
, NULL
, 's' },
121 { "display", required_argument
, NULL
, 'd' },
125 /* Decode the options from argv and argc.
126 The global variable `optind' will say how many arguments we used up. */
129 decode_options (argc
, argv
)
133 alternate_editor
= getenv ("ALTERNATE_EDITOR");
134 display
= getenv ("DISPLAY");
135 if (display
&& strlen (display
) == 0)
140 int opt
= getopt_long (argc
, argv
,
141 "VHnea:s:d:tc", longopts
, 0);
149 /* If getopt returns 0, then it has already processed a
150 long-named option. We should do nothing. */
154 alternate_editor
= optarg
;
158 socket_name
= optarg
;
174 printf ("emacsclient %s\n", VERSION
);
187 print_help_and_exit ();
191 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
202 /* --no-wait implies --current-frame on ttys when there are file
203 arguments or expressions given. */
204 if (nowait
&& tty
&& argc
- optind
> 0)
218 print_help_and_exit ()
221 "Usage: %s [OPTIONS] FILE...\n\
222 Tell the Emacs server to visit the specified files.\n\
223 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
225 The following OPTIONS are accepted:\n\
226 -V, --version Just print a version info and return\n\
227 -H, --help Print this usage information message\n\
228 -t, --tty Open a new Emacs frame on the current terminal\n\
229 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
230 -n, --no-wait Don't wait for the server to return\n\
231 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
232 -d, --display=DISPLAY Visit the file in the given display\n\
233 -s, --socket-name=FILENAME\n\
234 Set the filename of the UNIX socket for communication\n\
235 -a, --alternate-editor=EDITOR\n\
236 Editor to fallback to if the server is not running\n\
238 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
242 /* Like malloc but get fatal error if memory is exhausted. */
248 long *result
= (long *) malloc (size
);
257 /* Like strdup but get a fatal error if memory is exhausted. */
260 xstrdup (const char *s
)
262 char *result
= strdup (s
);
272 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
274 /* Return the current working directory. Returns NULL on errors.
275 Any other returned value must be freed with free. This is used
276 only when get_current_dir_name is not defined on the system. */
278 get_current_dir_name ()
282 struct stat dotstat
, pwdstat
;
283 /* If PWD is accurate, use it instead of calling getwd. PWD is
284 sometimes a nicer name, and using it may avoid a fatal error if a
285 parent directory is searchable but not readable. */
286 if ((pwd
= getenv ("PWD")) != 0
287 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
288 && stat (pwd
, &pwdstat
) == 0
289 && stat (".", &dotstat
) == 0
290 && dotstat
.st_ino
== pwdstat
.st_ino
291 && dotstat
.st_dev
== pwdstat
.st_dev
293 && strlen (pwd
) < MAXPATHLEN
297 buf
= (char *) malloc (strlen (pwd
) + 1);
305 size_t buf_size
= 1024;
306 buf
= (char *) malloc (buf_size
);
311 if (getcwd (buf
, buf_size
) == buf
)
315 int tmp_errno
= errno
;
321 buf
= (char *) realloc (buf
, buf_size
);
329 /* We need MAXPATHLEN here. */
330 buf
= (char *) malloc (MAXPATHLEN
+ 1);
333 if (getwd (buf
) == NULL
)
335 int tmp_errno
= errno
;
348 /* In STR, insert a & before each &, each space, each newline, and
349 any initial -. Change spaces to underscores, too, so that the
350 return value never contains a space.
352 Does not change the string. Outputs the result to STREAM. */
355 quote_argument (str
, stream
)
359 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
380 if (*p
== '&' || (*p
== '-' && p
== str
))
387 fprintf (stream
, "%s", copy
);
393 /* The inverse of quote_argument. Removes quoting in string STR by
394 modifying the string in place. Returns STR. */
397 unquote_argument (str
)
429 Try to run a different command, or --if no alternate editor is
430 defined-- exit with an errorcode.
435 if (alternate_editor
)
438 execvp (alternate_editor
, main_argv
+ i
);
447 /* The process id of Emacs. */
450 /* File handles for communicating with Emacs. */
453 /* A signal handler that passes the signal to the Emacs process.
454 Useful for SIGWINCH. */
457 pass_signal_to_emacs (int signalnum
)
459 int old_errno
= errno
;
462 kill (emacs_pid
, signalnum
);
464 signal (signalnum
, pass_signal_to_emacs
);
468 /* Signal handler for SIGCONT; notify the Emacs process that it can
469 now resume our tty frame. */
472 handle_sigcont (int signalnum
)
474 int old_errno
= errno
;
476 if (tcgetpgrp (1) == getpgrp ())
478 /* We are in the foreground. */
479 fprintf (out
, "-resume \n");
481 fsync (fileno (out
));
485 /* We are in the background; cancel the continue. */
486 kill (getpid (), SIGSTOP
);
489 signal (signalnum
, handle_sigcont
);
493 /* Signal handler for SIGTSTP; notify the Emacs process that we are
494 going to sleep. Normally the suspend is initiated by Emacs via
495 server-handle-suspend-tty, but if the server gets out of sync with
496 reality, we may get a SIGTSTP on C-z. Handling this signal and
497 notifying Emacs about it should get things under control again. */
500 handle_sigtstp (int signalnum
)
502 int old_errno
= errno
;
507 fprintf (out
, "-suspend \n");
509 fsync (fileno (out
));
512 /* Unblock this signal and call the default handler by temprarily
513 changing the handler and resignalling. */
514 sigprocmask (SIG_BLOCK
, NULL
, &set
);
515 sigdelset (&set
, signalnum
);
516 signal (signalnum
, SIG_DFL
);
517 kill (getpid (), signalnum
);
518 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
519 signal (signalnum
, handle_sigtstp
);
524 /* Set up signal handlers before opening a frame on the current tty. */
529 /* Set up signal handlers. */
530 signal (SIGWINCH
, pass_signal_to_emacs
);
532 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
533 deciding which terminal the signal came from. C-g is now a
534 normal input event on secondary terminals. */
536 signal (SIGINT
, pass_signal_to_emacs
);
537 signal (SIGQUIT
, pass_signal_to_emacs
);
540 signal (SIGCONT
, handle_sigcont
);
541 signal (SIGTSTP
, handle_sigtstp
);
542 signal (SIGTTOU
, handle_sigtstp
);
546 #if !defined (HAVE_SOCKETS) || defined (NO_SOCKETS_IN_FILE_SYSTEM)
553 fprintf (stderr
, "%s: Sorry, the Emacs server is supported only\n",
555 fprintf (stderr
, "on systems with Berkeley sockets.\n");
560 #else /* HAVE_SOCKETS */
562 #include <sys/types.h>
563 #include <sys/socket.h>
565 #include <sys/stat.h>
568 extern char *strerror ();
571 /* Three possibilities:
572 2 - can't be `stat'ed (sets errno)
573 1 - isn't owned by us
574 0 - success: none of the above */
577 socket_status (socket_name
)
582 if (stat (socket_name
, &statbfr
) == -1)
585 if (statbfr
.st_uid
!= geteuid ())
591 /* Returns 1 if PREFIX is a prefix of STRING. */
593 strprefix (char *prefix
, char *string
)
602 for (i
= 0; prefix
[i
]; i
++)
603 if (!string
[i
] || string
[i
] != prefix
[i
])
613 int s
, i
, needlf
= 0;
614 struct sockaddr_un server
;
622 /* Process options. */
623 decode_options (argc
, argv
);
625 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
627 fprintf (stderr
, "%s: file name or argument required\n", progname
);
628 fprintf (stderr
, "Try `%s --help' for more information\n", progname
);
633 * Open up an AF_UNIX socket in this person's home directory
636 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
638 fprintf (stderr
, "%s: ", argv
[0]);
643 server
.sun_family
= AF_UNIX
;
647 int default_sock
= !socket_name
;
650 char *server_name
= "server";
652 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
653 { /* socket_name is a file name component. */
654 server_name
= socket_name
;
656 default_sock
= 1; /* Try both UIDs. */
661 socket_name
= alloca (100 + strlen (server_name
));
662 sprintf (socket_name
, "/tmp/emacs%d/%s",
663 (int) geteuid (), server_name
);
666 if (strlen (socket_name
) < sizeof (server
.sun_path
))
667 strcpy (server
.sun_path
, socket_name
);
670 fprintf (stderr
, "%s: socket-name %s too long",
671 argv
[0], socket_name
);
675 /* See if the socket exists, and if it's owned by us. */
676 sock_status
= socket_status (server
.sun_path
);
678 if (sock_status
&& default_sock
)
680 /* Failing that, see if LOGNAME or USER exist and differ from
681 our euid. If so, look for a socket based on the UID
682 associated with the name. This is reminiscent of the logic
683 that init_editfns uses to set the global Vuser_full_name. */
685 char *user_name
= (char *) getenv ("LOGNAME");
688 user_name
= (char *) getenv ("USER");
692 struct passwd
*pw
= getpwnam (user_name
);
694 if (pw
&& (pw
->pw_uid
!= geteuid ()))
696 /* We're running under su, apparently. */
697 socket_name
= alloca (100 + strlen (server_name
));
698 sprintf (socket_name
, "/tmp/emacs%d/%s",
699 (int) pw
->pw_uid
, server_name
);
701 if (strlen (socket_name
) < sizeof (server
.sun_path
))
702 strcpy (server
.sun_path
, socket_name
);
705 fprintf (stderr
, "%s: socket-name %s too long",
706 argv
[0], socket_name
);
710 sock_status
= socket_status (server
.sun_path
);
721 /* There's a socket, but it isn't owned by us. This is OK if
725 fprintf (stderr
, "%s: Invalid socket owner\n", argv
[0]);
732 if (saved_errno
== ENOENT
)
734 "%s: can't find socket; have you started the server?\n\
735 To start the server in Emacs, type \"M-x server-start\".\n",
738 fprintf (stderr
, "%s: can't stat %s: %s\n",
739 argv
[0], server
.sun_path
, strerror (saved_errno
));
745 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
748 fprintf (stderr
, "%s: ", argv
[0]);
753 /* We use the stream OUT to send our commands to the server. */
754 if ((out
= fdopen (s
, "r+")) == NULL
)
756 fprintf (stderr
, "%s: ", argv
[0]);
761 /* We use the stream IN to read the responses.
762 We used to use just one stream for both output and input
763 on the socket, but reversing direction works nonportably:
764 on some systems, the output appears as the first input;
765 on other systems it does not. */
766 if ((in
= fdopen (s
, "r+")) == NULL
)
768 fprintf (stderr
, "%s: ", argv
[0]);
774 cwd
= getcwd (string
, sizeof string
);
776 cwd
= getwd (string
);
780 /* getwd puts message in STRING if it fails. */
783 fprintf (stderr
, "%s: %s (%s)\n", argv
[0],
784 "cannot get current working directory", strerror (errno
));
786 fprintf (stderr
, "%s: %s (%s)\n", argv
[0], string
, strerror (errno
));
791 /* First of all, send our version number for verification. */
792 fprintf (out
, "-version %s ", VERSION
);
794 /* Send over our environment. */
797 extern char **environ
;
799 for (i
= 0; environ
[i
]; i
++)
801 char *name
= xstrdup (environ
[i
]);
802 char *value
= strchr (name
, '=');
803 fprintf (out
, "-env ");
804 quote_argument (environ
[i
], out
);
809 /* Send over our current directory. */
812 char *dir
= get_current_dir_name ();
815 fprintf (out
, "-dir ");
816 quote_argument (dir
, out
);
825 fprintf (out
, "-nowait ");
828 fprintf (out
, "-current-frame ");
832 fprintf (out
, "-display ");
833 quote_argument (display
, out
);
839 char *tty_name
= ttyname (fileno (stdin
));
840 char *type
= getenv ("TERM");
844 fprintf (stderr
, "%s: could not get terminal name\n", progname
);
850 fprintf (stderr
, "%s: please set the TERM variable to your terminal type\n",
855 if (! strcmp (type
, "eterm"))
857 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
858 fprintf (stderr
, "%s: opening a frame in an Emacs term buffer"
859 " is not supported\n", progname
);
865 fprintf (out
, "-tty ");
866 quote_argument (tty_name
, out
);
868 quote_argument (type
, out
);
873 fprintf (out
, "-window-system ");
875 if ((argc
- optind
> 0))
877 for (i
= optind
; i
< argc
; i
++)
883 /* Don't prepend any cwd or anything like that. */
884 fprintf (out
, "-eval ");
885 quote_argument (argv
[i
], out
);
892 char *p
= argv
[i
] + 1;
893 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
896 fprintf (out
, "-position ");
897 quote_argument (argv
[i
], out
);
904 else if (*argv
[i
] != '/')
907 fprintf (out
, "-file ");
910 quote_argument (cwd
, out
);
913 quote_argument (argv
[i
], out
);
919 if (!tty
&& !window_system
)
921 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
924 fprintf (out
, "-eval ");
926 fprintf (out
, "-file ");
927 quote_argument (str
, out
);
935 fsync (fileno (out
));
937 /* Wait for an answer. */
938 if (!eval
&& !tty
&& !nowait
)
940 printf ("Waiting for Emacs...");
946 /* Now, wait for an answer and print any messages. */
947 while ((str
= fgets (string
, BUFSIZ
, in
)))
949 char *p
= str
+ strlen (str
) - 1;
950 while (p
> str
&& *p
== '\n')
953 if (strprefix ("-good-version ", str
))
955 /* -good-version: The versions match. */
957 else if (strprefix ("-emacs-pid ", str
))
959 /* -emacs-pid PID: The process id of the Emacs process. */
960 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
962 else if (strprefix ("-window-system-unsupported ", str
))
964 /* -window-system-unsupported: Emacs was compiled without X
965 support. Try again on the terminal. */
971 else if (strprefix ("-print ", str
))
973 /* -print STRING: Print STRING on the terminal. */
974 str
= unquote_argument (str
+ strlen ("-print "));
978 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
980 else if (strprefix ("-error ", str
))
982 /* -error DESCRIPTION: Signal an error on the terminal. */
983 str
= unquote_argument (str
+ strlen ("-error "));
986 printf ("*ERROR*: %s", str
);
987 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
989 else if (strprefix ("-suspend ", str
))
991 /* -suspend: Suspend this terminal, i.e., stop the process. */
999 /* Unknown command. */
1002 printf ("*ERROR*: Unknown message: %s", str
);
1003 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1012 return EXIT_SUCCESS
;
1015 #endif /* HAVE_SOCKETS */
1017 #ifndef HAVE_STRERROR
1022 extern char *sys_errlist
[];
1023 extern int sys_nerr
;
1025 if (errnum
>= 0 && errnum
< sys_nerr
)
1026 return sys_errlist
[errnum
];
1027 return (char *) "Unknown error";
1030 #endif /* ! HAVE_STRERROR */
1032 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1033 (do not change this comment) */
1035 /* emacsclient.c ends here */