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, 2007 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 3, 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. */
31 /* config.h defines these, which disables sockets altogether! */
38 # include <commctrl.h>
40 # define NO_SOCKETS_IN_FILE_SYSTEM
42 # define HSOCKET SOCKET
43 # define CLOSE_SOCKET closesocket
44 # define INITIALIZE() (initialize_sockets ())
46 #else /* !WINDOWSNT */
48 # include <sys/types.h>
50 # ifdef HAVE_INET_SOCKETS
51 # include <netinet/in.h>
54 # define INVALID_SOCKET -1
56 # define CLOSE_SOCKET close
59 #endif /* !WINDOWSNT */
76 #else /* not WINDOWSNT */
78 #endif /* not WINDOWSNT */
86 char *getenv (), *getwd ();
90 #define VERSION "unspecified"
95 #define EXIT_SUCCESS 0
99 #define EXIT_FAILURE 1
114 /* Name used to invoke this program. */
117 /* The second argument to main. */
120 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
123 /* Nonzero means args are expressions to be evaluated. --eval. */
126 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
127 int current_frame
= 1;
129 /* Nonzero means open a new graphical frame. */
130 int window_system
= 0;
132 /* The display on which Emacs should work. --display. */
133 char *display
= NULL
;
135 /* Nonzero means open a new Emacs frame on the current terminal. */
138 /* If non-NULL, the name of an editor to fallback to if the server
139 is not running. --alternate-editor. */
140 const char *alternate_editor
= NULL
;
142 /* If non-NULL, the filename of the UNIX socket. */
143 char *socket_name
= NULL
;
145 /* If non-NULL, the filename of the authentication file. */
146 char *server_file
= NULL
;
148 /* PID of the Emacs server process. */
151 void print_help_and_exit () NO_RETURN
;
153 struct option longopts
[] =
155 { "no-wait", no_argument
, NULL
, 'n' },
156 { "eval", no_argument
, NULL
, 'e' },
157 { "help", no_argument
, NULL
, 'H' },
158 { "version", no_argument
, NULL
, 'V' },
159 { "tty", no_argument
, NULL
, 't' },
160 { "create-frame", no_argument
, NULL
, 'c' },
161 { "alternate-editor", required_argument
, NULL
, 'a' },
162 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
163 { "socket-name", required_argument
, NULL
, 's' },
165 { "server-file", required_argument
, NULL
, 'f' },
166 { "display", required_argument
, NULL
, 'd' },
171 /* Like malloc but get fatal error if memory is exhausted. */
177 long *result
= (long *) malloc (size
);
186 /* Like strdup but get a fatal error if memory is exhausted. */
189 xstrdup (const char *s
)
191 char *result
= strdup (s
);
201 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
204 #ifndef DIRECTORY_SEP
205 #define DIRECTORY_SEP '/'
207 #ifndef IS_DIRECTORY_SEP
208 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
210 #ifndef IS_DEVICE_SEP
212 #define IS_DEVICE_SEP(_c_) 0
214 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
218 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
222 /* Return the current working directory. Returns NULL on errors.
223 Any other returned value must be freed with free. This is used
224 only when get_current_dir_name is not defined on the system. */
226 get_current_dir_name ()
230 struct stat dotstat
, pwdstat
;
231 /* If PWD is accurate, use it instead of calling getwd. PWD is
232 sometimes a nicer name, and using it may avoid a fatal error if a
233 parent directory is searchable but not readable. */
234 if ((pwd
= getenv ("PWD")) != 0
235 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
236 && stat (pwd
, &pwdstat
) == 0
237 && stat (".", &dotstat
) == 0
238 && dotstat
.st_ino
== pwdstat
.st_ino
239 && dotstat
.st_dev
== pwdstat
.st_dev
241 && strlen (pwd
) < MAXPATHLEN
245 buf
= (char *) xmalloc (strlen (pwd
) + 1);
253 size_t buf_size
= 1024;
254 buf
= (char *) xmalloc (buf_size
);
259 if (getcwd (buf
, buf_size
) == buf
)
263 int tmp_errno
= errno
;
269 buf
= (char *) realloc (buf
, buf_size
);
277 /* We need MAXPATHLEN here. */
278 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
281 if (getwd (buf
) == NULL
)
283 int tmp_errno
= errno
;
294 /* Message functions. */
300 static int window_app
= -1;
301 char szTitle
[MAX_PATH
];
305 /* Checking for STDOUT does not work; it's a valid handle also in
306 nonconsole apps. Testing for the console title seems to work. */
307 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
309 InitCommonControls();
316 execvp wrapper for Windows. Quotes arguments with embedded spaces.
318 This is necessary due to the broken implementation of exec* routines in
319 the Microsoft libraries: they concatenate the arguments together without
320 quoting special characters, and pass the result to CreateProcess, with
321 predictably bad results. By contrast, Posix execvp passes the arguments
322 directly into the argv array of the child process.
325 w32_execvp (path
, argv
)
331 /* Required to allow a .BAT script as alternate editor. */
332 argv
[0] = (char *) alternate_editor
;
334 for (i
= 0; argv
[i
]; i
++)
335 if (strchr (argv
[i
], ' '))
337 char *quoted
= alloca (strlen (argv
[i
]) + 3);
338 sprintf (quoted
, "\"%s\"", argv
[i
]);
342 return execvp (path
, argv
);
346 #define execvp w32_execvp
348 #endif /* WINDOWSNT */
351 message (int is_error
, char *message
, ...)
356 va_start (args
, message
);
357 vsprintf (msg
, message
, args
);
361 if (w32_window_app ())
364 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
366 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
371 FILE *f
= is_error
? stderr
: stdout
;
378 /* Decode the options from argv and argc.
379 The global variable `optind' will say how many arguments we used up. */
382 decode_options (argc
, argv
)
386 alternate_editor
= getenv ("ALTERNATE_EDITOR");
387 display
= getenv ("DISPLAY");
388 if (display
&& strlen (display
) == 0)
393 int opt
= getopt_long (argc
, argv
,
394 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
407 /* If getopt returns 0, then it has already processed a
408 long-named option. We should do nothing. */
412 alternate_editor
= optarg
;
415 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
417 socket_name
= optarg
;
422 server_file
= optarg
;
438 message (FALSE
, "emacsclient %s\n", VERSION
);
452 print_help_and_exit ();
456 message (TRUE
, "Try `%s --help' for more information\n", progname
);
464 #if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
469 /* --no-wait implies --current-frame on ttys when there are file
470 arguments or expressions given. */
471 if (nowait
&& tty
&& argc
- optind
> 0)
486 print_help_and_exit ()
488 /* Spaces and tabs are significant in this message; they're chosen so the
489 message aligns properly both in a tty and in a Windows message box.
490 Please try to preserve them; otherwise the output is very hard to read
491 when using emacsclientw. */
493 "Usage: %s [OPTIONS] FILE...\n\
494 Tell the Emacs server to visit the specified files.\n\
495 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
497 The following OPTIONS are accepted:\n\
498 -V, --version Just print version info and return\n\
499 -H, --help Print this usage information message\n\
500 -t, --tty Open a new Emacs frame on the current terminal\n\
501 -c, --create-frame Create a new frame instead of trying to\n\
502 use the current Emacs frame\n\
503 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
504 -n, --no-wait Don't wait for the server to return\n\
505 -d, --display=DISPLAY Visit the file in the given display\n"
506 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
507 "-s, --socket-name=FILENAME\n\
508 Set filename of the UNIX socket for communication\n"
510 "-f, --server-file=FILENAME\n\
511 Set filename of the TCP authentication file\n\
512 -a, --alternate-editor=EDITOR\n\
513 Editor to fallback to if the server is not running\n\
515 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
520 Try to run a different command, or --if no alternate editor is
521 defined-- exit with an errorcode.
522 Uses argv, but gets it from the global variable main_argv.
527 if (alternate_editor
)
531 execvp (alternate_editor
, main_argv
+ i
);
532 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
533 progname
, alternate_editor
);
539 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
548 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
549 "on systems with Berkeley sockets.\n",
554 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
557 # include <winsock2.h>
559 # include <sys/types.h>
560 # include <sys/socket.h>
564 #define AUTH_KEY_LENGTH 64
565 #define SEND_BUFFER_SIZE 4096
567 extern char *strerror ();
570 /* Buffer to accumulate data to send in TCP connections. */
571 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
572 int sblen
= 0; /* Fill pointer for the send buffer. */
573 /* Socket used to communicate with the Emacs server process. */
574 HSOCKET emacs_socket
= 0;
576 /* Let's send the data to Emacs when either
577 - the data ends in "\n", or
578 - the buffer is full (but this shouldn't happen)
579 Otherwise, we just accumulate it. */
581 send_to_emacs (s
, data
)
587 int dlen
= strlen (data
);
588 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
590 int part
= SEND_BUFFER_SIZE
- sblen
;
591 strncpy (&send_buffer
[sblen
], data
, part
);
593 sblen
= SEND_BUFFER_SIZE
;
597 strcpy (&send_buffer
[sblen
], data
);
604 if (sblen
== SEND_BUFFER_SIZE
605 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
607 int sent
= send (s
, send_buffer
, sblen
, 0);
609 strcpy (send_buffer
, &send_buffer
[sent
]);
616 /* In STR, insert a & before each &, each space, each newline, and
617 any initial -. Change spaces to underscores, too, so that the
618 return value never contains a space.
620 Does not change the string. Outputs the result to STREAM. */
622 quote_argument (s
, str
)
626 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
647 if (*p
== '&' || (*p
== '-' && p
== str
))
654 send_to_emacs (s
, copy
);
660 /* The inverse of quote_argument. Removes quoting in string STR by
661 modifying the string in place. Returns STR. */
664 unquote_argument (str
)
696 file_name_absolute_p (filename
)
697 const unsigned char *filename
;
699 /* Sanity check, it shouldn't happen. */
700 if (! filename
) return FALSE
;
702 /* /xxx is always an absolute path. */
703 if (filename
[0] == '/') return TRUE
;
705 /* Empty filenames (which shouldn't happen) are relative. */
706 if (filename
[0] == '\0') return FALSE
;
709 /* X:\xxx is always absolute. */
710 if (isalpha (filename
[0])
711 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
714 /* Both \xxx and \\xxx\yyy are absolute. */
715 if (filename
[0] == '\\') return TRUE
;
718 FIXME: There's a corner case not dealt with, "x:y", where:
720 1) x is a valid drive designation (usually a letter in the A-Z range)
721 and y is a path, relative to the current directory on drive x. This
722 is absolute, *after* fixing the y part to include the current
725 2) x is a relative file name, and y is an NTFS stream name. This is a
726 correct relative path, but it is very unusual.
728 The trouble is that first case items are also valid examples of the
729 second case, i.e., "c:test" can be understood as drive:path or as
732 The "right" fix would involve checking whether
733 - the current drive/partition is NTFS,
734 - x is a valid (and accesible) drive designator,
735 - x:y already exists as a file:stream in the current directory,
736 - y already exists on the current directory of drive x,
737 - the auspices are favorable,
738 and then taking an "informed decision" based on the above.
740 Whatever the result, Emacs currently does a very bad job of dealing
741 with NTFS file:streams: it cannot visit them, and the only way to
742 create one is by setting `buffer-file-name' to point to it (either
743 manually or with emacsclient). So perhaps resorting to 1) and ignoring
744 2) for now is the right thing to do.
746 Anyway, something to decide After the Release.
754 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
756 __cdecl
close_winsock ()
761 /* Initialize the WinSock2 library. */
763 initialize_sockets ()
767 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
769 message (TRUE
, "%s: error initializing WinSock2", progname
);
773 atexit (close_winsock
);
775 #endif /* WINDOWSNT */
779 * Read the information needed to set up a TCP comm channel with
780 * the Emacs server: host, port, pid and authentication string.
783 get_server_config (server
, authentication
)
784 struct sockaddr_in
*server
;
785 char *authentication
;
792 if (file_name_absolute_p (server_file
))
793 config
= fopen (server_file
, "rb");
796 char *home
= getenv ("HOME");
800 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
801 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
802 config
= fopen (path
, "rb");
805 if (!config
&& (home
= getenv ("APPDATA")))
807 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
808 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
809 config
= fopen (path
, "rb");
817 if (fgets (dotted
, sizeof dotted
, config
)
818 && (port
= strchr (dotted
, ':'))
819 && (pid
= strchr (port
, ' ')))
826 message (TRUE
, "%s: invalid configuration info", progname
);
830 server
->sin_family
= AF_INET
;
831 server
->sin_addr
.s_addr
= inet_addr (dotted
);
832 server
->sin_port
= htons (atoi (port
));
834 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
836 message (TRUE
, "%s: cannot read authentication info", progname
);
842 emacs_pid
= atoi (pid
);
851 struct sockaddr_in server
;
852 struct linger l_arg
= {1, 1};
853 char auth_string
[AUTH_KEY_LENGTH
+ 1];
855 if (! get_server_config (&server
, auth_string
))
856 return INVALID_SOCKET
;
858 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
859 message (FALSE
, "%s: connected to remote socket at %s\n",
860 progname
, inet_ntoa (server
.sin_addr
));
863 * Open up an AF_INET socket
865 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
867 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
868 return INVALID_SOCKET
;
874 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
876 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
877 return INVALID_SOCKET
;
880 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
883 * Send the authentication
885 auth_string
[AUTH_KEY_LENGTH
] = '\0';
887 send_to_emacs (s
, "-auth ");
888 send_to_emacs (s
, auth_string
);
889 send_to_emacs (s
, "\n");
895 /* Returns 1 if PREFIX is a prefix of STRING. */
897 strprefix (char *prefix
, char *string
)
899 return !strncmp (prefix
, string
, strlen (prefix
));
903 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
905 /* Three possibilities:
906 2 - can't be `stat'ed (sets errno)
907 1 - isn't owned by us
908 0 - success: none of the above */
911 socket_status (socket_name
)
916 if (stat (socket_name
, &statbfr
) == -1)
919 if (statbfr
.st_uid
!= geteuid ())
926 /* A signal handler that passes the signal to the Emacs process.
927 Useful for SIGWINCH. */
930 pass_signal_to_emacs (int signalnum
)
932 int old_errno
= errno
;
935 kill (emacs_pid
, signalnum
);
937 signal (signalnum
, pass_signal_to_emacs
);
941 /* Signal handler for SIGCONT; notify the Emacs process that it can
942 now resume our tty frame. */
945 handle_sigcont (int signalnum
)
947 int old_errno
= errno
;
949 if (tcgetpgrp (1) == getpgrp ())
951 /* We are in the foreground. */
952 send_to_emacs (emacs_socket
, "-resume \n");
956 /* We are in the background; cancel the continue. */
957 kill (getpid (), SIGSTOP
);
960 signal (signalnum
, handle_sigcont
);
964 /* Signal handler for SIGTSTP; notify the Emacs process that we are
965 going to sleep. Normally the suspend is initiated by Emacs via
966 server-handle-suspend-tty, but if the server gets out of sync with
967 reality, we may get a SIGTSTP on C-z. Handling this signal and
968 notifying Emacs about it should get things under control again. */
971 handle_sigtstp (int signalnum
)
973 int old_errno
= errno
;
977 send_to_emacs (emacs_socket
, "-suspend \n");
979 /* Unblock this signal and call the default handler by temprarily
980 changing the handler and resignalling. */
981 sigprocmask (SIG_BLOCK
, NULL
, &set
);
982 sigdelset (&set
, signalnum
);
983 signal (signalnum
, SIG_DFL
);
984 kill (getpid (), signalnum
);
985 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
986 signal (signalnum
, handle_sigtstp
);
990 /* Set up signal handlers before opening a frame on the current tty. */
995 /* Set up signal handlers. */
996 signal (SIGWINCH
, pass_signal_to_emacs
);
998 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
999 deciding which terminal the signal came from. C-g is now a
1000 normal input event on secondary terminals. */
1002 signal (SIGINT
, pass_signal_to_emacs
);
1003 signal (SIGQUIT
, pass_signal_to_emacs
);
1006 signal (SIGCONT
, handle_sigcont
);
1007 signal (SIGTSTP
, handle_sigtstp
);
1008 signal (SIGTTOU
, handle_sigtstp
);
1016 struct sockaddr_un server
;
1019 * Open up an AF_UNIX socket in this person's home directory
1022 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1024 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1025 return INVALID_SOCKET
;
1028 server
.sun_family
= AF_UNIX
;
1031 int sock_status
= 0;
1032 int default_sock
= !socket_name
;
1033 int saved_errno
= 0;
1034 char *server_name
= "server";
1036 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
1037 { /* socket_name is a file name component. */
1038 server_name
= socket_name
;
1040 default_sock
= 1; /* Try both UIDs. */
1045 socket_name
= alloca (100 + strlen (server_name
));
1046 sprintf (socket_name
, "/tmp/emacs%d/%s",
1047 (int) geteuid (), server_name
);
1050 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1051 strcpy (server
.sun_path
, socket_name
);
1054 message (TRUE
, "%s: socket-name %s too long",
1055 progname
, socket_name
);
1059 /* See if the socket exists, and if it's owned by us. */
1060 sock_status
= socket_status (server
.sun_path
);
1061 saved_errno
= errno
;
1062 if (sock_status
&& default_sock
)
1064 /* Failing that, see if LOGNAME or USER exist and differ from
1065 our euid. If so, look for a socket based on the UID
1066 associated with the name. This is reminiscent of the logic
1067 that init_editfns uses to set the global Vuser_full_name. */
1069 char *user_name
= (char *) getenv ("LOGNAME");
1072 user_name
= (char *) getenv ("USER");
1076 struct passwd
*pw
= getpwnam (user_name
);
1078 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1080 /* We're running under su, apparently. */
1081 socket_name
= alloca (100 + strlen (server_name
));
1082 sprintf (socket_name
, "/tmp/emacs%d/%s",
1083 (int) pw
->pw_uid
, server_name
);
1085 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1086 strcpy (server
.sun_path
, socket_name
);
1089 message (TRUE
, "%s: socket-name %s too long",
1090 progname
, socket_name
);
1091 exit (EXIT_FAILURE
);
1094 sock_status
= socket_status (server
.sun_path
);
1095 saved_errno
= errno
;
1098 errno
= saved_errno
;
1102 switch (sock_status
)
1105 /* There's a socket, but it isn't owned by us. This is OK if
1107 if (0 != geteuid ())
1109 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1110 return INVALID_SOCKET
;
1116 if (saved_errno
== ENOENT
)
1118 "%s: can't find socket; have you started the server?\n\
1119 To start the server in Emacs, type \"M-x server-start\".\n",
1122 message (TRUE
, "%s: can't stat %s: %s\n",
1123 progname
, server
.sun_path
, strerror (saved_errno
));
1124 return INVALID_SOCKET
;
1128 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1131 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1132 return INVALID_SOCKET
;
1137 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1146 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1147 /* Explicit --socket-name argument. */
1150 s
= set_local_socket ();
1151 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1153 message (TRUE
, "%s: error accessing socket \"%s\"",
1154 progname
, socket_name
);
1155 exit (EXIT_FAILURE
);
1159 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1161 server_file
= getenv ("EMACS_SERVER_FILE");
1165 s
= set_tcp_socket ();
1166 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1169 message (TRUE
, "%s: error accessing server file \"%s\"",
1170 progname
, server_file
);
1171 exit (EXIT_FAILURE
);
1174 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1175 /* Implicit local socket. */
1176 s
= set_local_socket ();
1177 if (s
!= INVALID_SOCKET
)
1181 /* Implicit server file. */
1182 server_file
= "server";
1183 s
= set_tcp_socket ();
1184 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1187 /* No implicit or explicit socket, and no alternate editor. */
1188 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1189 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1192 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1193 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1195 exit (EXIT_FAILURE
);
1199 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1200 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1203 w32_find_emacs_process (hWnd
, lParam
)
1210 /* Reject any window not of class "Emacs". */
1211 if (! get_wc (hWnd
, class, sizeof (class))
1212 || strcmp (class, "Emacs"))
1215 /* We only need the process id, not the thread id. */
1216 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1218 /* Not the one we're looking for. */
1219 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1221 /* OK, let's raise it. */
1224 /* Stop enumeration. */
1229 * Search for a window of class "Emacs" and owned by a process with
1230 * process id = emacs_pid. If found, allow it to grab the focus.
1237 /* It shouldn't happen when dealing with TCP sockets. */
1238 if (!emacs_pid
) return;
1240 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
1242 /* Modern Windows restrict which processes can set the foreground window.
1243 emacsclient can allow Emacs to grab the focus by calling the function
1244 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1245 NT) lack this function, so we have to check its availability. */
1246 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
1247 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
1248 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1250 FreeLibrary (hUser32
);
1259 int i
, rl
, needlf
= 0;
1261 char string
[BUFSIZ
+1];
1266 /* Process options. */
1267 decode_options (argc
, argv
);
1269 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
1271 message (TRUE
, "%s: file name or argument required\n"
1272 "Try `%s --help' for more information\n",
1273 progname
, progname
);
1274 exit (EXIT_FAILURE
);
1277 if ((emacs_socket
= set_socket ()) == INVALID_SOCKET
)
1281 cwd
= get_current_dir_name ();
1284 /* getwd puts message in STRING if it fails. */
1285 message (TRUE
, "%s: %s\n", progname
,
1286 "Cannot get current working directory");
1294 /* Send over our environment. */
1297 extern char **environ
;
1299 for (i
= 0; environ
[i
]; i
++)
1301 char *name
= xstrdup (environ
[i
]);
1302 char *value
= strchr (name
, '=');
1303 send_to_emacs (emacs_socket
, "-env ");
1304 quote_argument (emacs_socket
, environ
[i
]);
1305 send_to_emacs (emacs_socket
, " ");
1309 /* Send over our current directory. */
1312 send_to_emacs (emacs_socket
, "-dir ");
1313 quote_argument (emacs_socket
, cwd
);
1314 send_to_emacs (emacs_socket
, "/");
1315 send_to_emacs (emacs_socket
, " ");
1320 send_to_emacs (emacs_socket
, "-nowait ");
1323 send_to_emacs (emacs_socket
, "-current-frame ");
1327 send_to_emacs (emacs_socket
, "-display ");
1328 quote_argument (emacs_socket
, display
);
1329 send_to_emacs (emacs_socket
, " ");
1334 char *type
= getenv ("TERM");
1335 char *tty_name
= NULL
;
1337 tty_name
= ttyname (fileno (stdin
));
1342 message (TRUE
, "%s: could not get terminal name\n", progname
);
1348 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1353 if (! strcmp (type
, "eterm"))
1355 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1356 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1357 " is not supported\n", progname
);
1360 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1364 send_to_emacs (emacs_socket
, "-tty ");
1365 quote_argument (emacs_socket
, tty_name
);
1366 send_to_emacs (emacs_socket
, " ");
1367 quote_argument (emacs_socket
, type
);
1368 send_to_emacs (emacs_socket
, " ");
1372 send_to_emacs (emacs_socket
, "-window-system ");
1374 if ((argc
- optind
> 0))
1376 for (i
= optind
; i
< argc
; i
++)
1382 /* Don't prepend cwd or anything like that. */
1383 send_to_emacs (emacs_socket
, "-eval ");
1384 quote_argument (emacs_socket
, argv
[i
]);
1385 send_to_emacs (emacs_socket
, " ");
1389 if (*argv
[i
] == '+')
1391 char *p
= argv
[i
] + 1;
1392 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1395 send_to_emacs (emacs_socket
, "-position ");
1396 quote_argument (emacs_socket
, argv
[i
]);
1397 send_to_emacs (emacs_socket
, " ");
1403 else if (! file_name_absolute_p (argv
[i
]))
1406 send_to_emacs (emacs_socket
, "-file ");
1409 quote_argument (emacs_socket
, cwd
);
1410 send_to_emacs (emacs_socket
, "/");
1412 quote_argument (emacs_socket
, argv
[i
]);
1413 send_to_emacs (emacs_socket
, " ");
1418 if (!tty
&& !window_system
)
1420 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1423 send_to_emacs (emacs_socket
, "-eval ");
1425 send_to_emacs (emacs_socket
, "-file ");
1426 quote_argument (emacs_socket
, str
);
1428 send_to_emacs (emacs_socket
, " ");
1432 send_to_emacs (emacs_socket
, "\n");
1434 /* Wait for an answer. */
1435 if (!eval
&& !tty
&& !nowait
)
1437 printf ("Waiting for Emacs...");
1443 /* Now, wait for an answer and print any messages. */
1444 while ((rl
= recv (emacs_socket
, string
, BUFSIZ
, 0)) > 0)
1449 p
= string
+ strlen (string
) - 1;
1450 while (p
> string
&& *p
== '\n')
1453 if (strprefix ("-emacs-pid ", string
))
1455 /* -emacs-pid PID: The process id of the Emacs process. */
1456 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1458 else if (strprefix ("-window-system-unsupported ", string
))
1460 /* -window-system-unsupported: Emacs was compiled without X
1461 support. Try again on the terminal. */
1467 else if (strprefix ("-print ", string
))
1469 /* -print STRING: Print STRING on the terminal. */
1470 str
= unquote_argument (string
+ strlen ("-print "));
1474 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1476 else if (strprefix ("-error ", string
))
1478 /* -error DESCRIPTION: Signal an error on the terminal. */
1479 str
= unquote_argument (string
+ strlen ("-error "));
1482 fprintf (stderr
, "*ERROR*: %s", str
);
1483 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1486 else if (strprefix ("-suspend ", string
))
1488 /* -suspend: Suspend this terminal, i.e., stop the process. */
1497 /* Unknown command. */
1500 printf ("*ERROR*: Unknown message: %s", string
);
1501 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1510 CLOSE_SOCKET (emacs_socket
);
1511 return EXIT_SUCCESS
;
1514 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1517 #ifndef HAVE_STRERROR
1522 extern char *sys_errlist
[];
1523 extern int sys_nerr
;
1525 if (errnum
>= 0 && errnum
< sys_nerr
)
1526 return sys_errlist
[errnum
];
1527 return (char *) "Unknown error";
1530 #endif /* ! HAVE_STRERROR */
1532 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1533 (do not change this comment) */
1535 /* emacsclient.c ends here */