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 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. */
31 /* config.h defines these, which disables sockets altogether! */
39 # define NO_SOCKETS_IN_FILE_SYSTEM
41 # define HSOCKET SOCKET
42 # define CLOSE_SOCKET closesocket
43 # define INITIALIZE() (initialize_sockets ())
45 #else /* !WINDOWSNT */
47 # include <sys/types.h>
49 # ifdef HAVE_INET_SOCKETS
50 # include <netinet/in.h>
53 # define INVALID_SOCKET -1
55 # define CLOSE_SOCKET close
58 #endif /* !WINDOWSNT */
75 #else /* not WINDOWSNT */
77 #endif /* not WINDOWSNT */
86 #define DIRECTORY_SEP '/'
88 #ifndef IS_DIRECTORY_SEP
89 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
93 #define IS_DEVICE_SEP(_c_) 0
95 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
99 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
104 char *getenv (), *getwd ();
108 #define VERSION "unspecified"
111 #define SEND_STRING(data) (send_to_emacs (emacs_socket, (data)))
112 #define SEND_QUOTED(data) (quote_argument (emacs_socket, (data)))
115 #define EXIT_SUCCESS 0
119 #define EXIT_FAILURE 1
134 /* Name used to invoke this program. */
137 /* The first argument to main. */
140 /* The second argument to main. */
143 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
146 /* Nonzero means args are expressions to be evaluated. --eval. */
149 /* Nonzero means don't open a new frame. --current-frame. */
150 int current_frame
= 0;
152 /* Nonzero means open a new graphical frame. */
153 int window_system
= 0;
155 /* The display on which Emacs should work. --display. */
156 char *display
= NULL
;
158 /* Nonzero means open a new Emacs frame on the current terminal. */
161 /* If non-NULL, the name of an editor to fallback to if the server
162 is not running. --alternate-editor. */
163 const char *alternate_editor
= NULL
;
165 /* If non-NULL, the filename of the UNIX socket. */
166 char *socket_name
= NULL
;
168 /* If non-NULL, the filename of the authentication file. */
169 char *server_file
= NULL
;
171 /* PID of the Emacs server process. */
174 void print_help_and_exit () NO_RETURN
;
176 struct option longopts
[] =
178 { "no-wait", no_argument
, NULL
, 'n' },
179 { "eval", no_argument
, NULL
, 'e' },
180 { "help", no_argument
, NULL
, 'H' },
181 { "version", no_argument
, NULL
, 'V' },
182 { "tty", no_argument
, NULL
, 't' },
183 { "current-frame", no_argument
, NULL
, 'c' },
184 { "alternate-editor", required_argument
, NULL
, 'a' },
185 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
186 { "socket-name", required_argument
, NULL
, 's' },
188 { "server-file", required_argument
, NULL
, 'f' },
189 { "display", required_argument
, NULL
, 'd' },
194 /* Like malloc but get fatal error if memory is exhausted. */
200 long *result
= (long *) malloc (size
);
209 /* Like strdup but get a fatal error if memory is exhausted. */
212 xstrdup (const char *s
)
214 char *result
= strdup (s
);
224 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
226 /* Return the current working directory. Returns NULL on errors.
227 Any other returned value must be freed with free. This is used
228 only when get_current_dir_name is not defined on the system. */
230 get_current_dir_name ()
234 struct stat dotstat
, pwdstat
;
235 /* If PWD is accurate, use it instead of calling getwd. PWD is
236 sometimes a nicer name, and using it may avoid a fatal error if a
237 parent directory is searchable but not readable. */
238 if ((pwd
= getenv ("PWD")) != 0
239 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
240 && stat (pwd
, &pwdstat
) == 0
241 && stat (".", &dotstat
) == 0
242 && dotstat
.st_ino
== pwdstat
.st_ino
243 && dotstat
.st_dev
== pwdstat
.st_dev
245 && strlen (pwd
) < MAXPATHLEN
249 buf
= (char *) xmalloc (strlen (pwd
) + 1);
257 size_t buf_size
= 1024;
258 buf
= (char *) xmalloc (buf_size
);
263 if (getcwd (buf
, buf_size
) == buf
)
267 int tmp_errno
= errno
;
273 buf
= (char *) realloc (buf
, buf_size
);
281 /* We need MAXPATHLEN here. */
282 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
285 if (getwd (buf
) == NULL
)
287 int tmp_errno
= errno
;
298 /* Message functions. */
304 static int window_app
= -1;
305 char szTitle
[MAX_PATH
];
308 /* Checking for STDOUT does not work; it's a valid handle also in
309 nonconsole apps. Testing for the console title seems to work. */
310 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
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
);
451 print_help_and_exit ();
455 message (TRUE
, "Try `%s --help' for more information\n", progname
);
466 /* --no-wait implies --current-frame on ttys when there are file
467 arguments or expressions given. */
468 if (nowait
&& tty
&& argc
- optind
> 0)
483 print_help_and_exit ()
486 "Usage: %s [OPTIONS] FILE...\n\
487 Tell the Emacs server to visit the specified files.\n\
488 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
490 The following OPTIONS are accepted:\n\
491 -V, --version Just print version info and return\n\
492 -H, --help Print this usage information message\n\
493 -t, --tty Open a new Emacs frame on the current terminal\n\
494 -c, --current-frame Do not create a new frame; use the current Emacs frame\n\
495 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
496 -n, --no-wait Don't wait for the server to return\n\
497 -d, --display=DISPLAY Visit the file in the given display\n"
498 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
499 "-s, --socket-name=FILENAME\n\
500 Set filename of the UNIX socket for communication\n"
502 "-f, --server-file=FILENAME\n\
503 Set filename of the TCP authentication file\n\
504 -a, --alternate-editor=EDITOR\n\
505 Editor to fallback to if the server is not running\n\
507 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
512 Try to run a different command, or --if no alternate editor is
513 defined-- exit with an errorcode.
518 if (alternate_editor
)
522 execvp (alternate_editor
, main_argv
+ i
);
523 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
524 progname
, alternate_editor
);
530 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
540 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
541 "on systems with Berkeley sockets.\n",
546 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
549 # include <winsock2.h>
551 # include <sys/types.h>
552 # include <sys/socket.h>
554 # include <sys/stat.h>
558 #define AUTH_KEY_LENGTH 64
559 #define SEND_BUFFER_SIZE 4096
561 extern char *strerror ();
564 /* Buffer to accumulate data to send in TCP connections. */
565 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
566 int sblen
= 0; /* Fill pointer for the send buffer. */
567 /* Socket used to communicate with the Emacs server process. */
568 HSOCKET emacs_socket
= 0;
570 /* Let's send the data to Emacs when either
571 - the data ends in "\n", or
572 - the buffer is full (but this shouldn't happen)
573 Otherwise, we just accumulate it. */
575 send_to_emacs (s
, data
)
581 int dlen
= strlen (data
);
582 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
584 int part
= SEND_BUFFER_SIZE
- sblen
;
585 strncpy (&send_buffer
[sblen
], data
, part
);
587 sblen
= SEND_BUFFER_SIZE
;
591 strcpy (&send_buffer
[sblen
], data
);
598 if (sblen
== SEND_BUFFER_SIZE
599 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
601 int sent
= send (s
, send_buffer
, sblen
, 0);
603 strcpy (send_buffer
, &send_buffer
[sent
]);
610 /* In STR, insert a & before each &, each space, each newline, and
611 any initial -. Change spaces to underscores, too, so that the
612 return value never contains a space.
614 Does not change the string. Outputs the result to STREAM. */
616 quote_argument (s
, str
)
620 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
641 if (*p
== '&' || (*p
== '-' && p
== str
))
654 /* The inverse of quote_argument. Removes quoting in string STR by
655 modifying the string in place. Returns STR. */
658 unquote_argument (str
)
690 file_name_absolute_p (filename
)
691 const unsigned char *filename
;
693 /* Sanity check, it shouldn't happen. */
694 if (! filename
) return FALSE
;
696 /* /xxx is always an absolute path. */
697 if (filename
[0] == '/') return TRUE
;
699 /* Empty filenames (which shouldn't happen) are relative. */
700 if (filename
[0] == '\0') return FALSE
;
703 /* X:\xxx is always absolute. */
704 if (isalpha (filename
[0])
705 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
708 /* Both \xxx and \\xxx\yyy are absolute. */
709 if (filename
[0] == '\\') return TRUE
;
712 FIXME: There's a corner case not dealt with, "x:y", where:
714 1) x is a valid drive designation (usually a letter in the A-Z range)
715 and y is a path, relative to the current directory on drive x. This
716 is absolute, *after* fixing the y part to include the current
719 2) x is a relative file name, and y is an NTFS stream name. This is a
720 correct relative path, but it is very unusual.
722 The trouble is that first case items are also valid examples of the
723 second case, i.e., "c:test" can be understood as drive:path or as
726 The "right" fix would involve checking whether
727 - the current drive/partition is NTFS,
728 - x is a valid (and accesible) drive designator,
729 - x:y already exists as a file:stream in the current directory,
730 - y already exists on the current directory of drive x,
731 - the auspices are favorable,
732 and then taking an "informed decision" based on the above.
734 Whatever the result, Emacs currently does a very bad job of dealing
735 with NTFS file:streams: it cannot visit them, and the only way to
736 create one is by setting `buffer-file-name' to point to it (either
737 manually or with emacsclient). So perhaps resorting to 1) and ignoring
738 2) for now is the right thing to do.
740 Anyway, something to decide After the Release.
748 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
750 __cdecl
close_winsock ()
755 /* Initialize the WinSock2 library. */
757 initialize_sockets ()
761 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
763 message (TRUE
, "%s: error initializing WinSock2", progname
);
767 atexit (close_winsock
);
769 #endif /* WINDOWSNT */
773 * Read the information needed to set up a TCP comm channel with
774 * the Emacs server: host, port, pid and authentication string.
777 get_server_config (server
, authentication
)
778 struct sockaddr_in
*server
;
779 char *authentication
;
786 if (file_name_absolute_p (server_file
))
787 config
= fopen (server_file
, "rb");
790 char *home
= getenv ("HOME");
794 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
795 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
796 config
= fopen (path
, "rb");
799 if (!config
&& (home
= getenv ("APPDATA")))
801 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
802 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
803 config
= fopen (path
, "rb");
811 if (fgets (dotted
, sizeof dotted
, config
)
812 && (port
= strchr (dotted
, ':'))
813 && (pid
= strchr (port
, ' ')))
820 message (TRUE
, "%s: invalid configuration info", progname
);
824 server
->sin_family
= AF_INET
;
825 server
->sin_addr
.s_addr
= inet_addr (dotted
);
826 server
->sin_port
= htons (atoi (port
));
828 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
830 message (TRUE
, "%s: cannot read authentication info", progname
);
836 emacs_pid
= atoi (pid
);
845 struct sockaddr_in server
;
846 struct linger l_arg
= {1, 1};
847 char auth_string
[AUTH_KEY_LENGTH
+ 1];
849 if (! get_server_config (&server
, auth_string
))
850 return INVALID_SOCKET
;
852 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
853 message (FALSE
, "%s: connected to remote socket at %s\n",
854 progname
, inet_ntoa (server
.sin_addr
));
857 * Open up an AF_INET socket
859 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
861 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
862 return INVALID_SOCKET
;
868 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
870 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
871 return INVALID_SOCKET
;
874 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
877 * Send the authentication
879 auth_string
[AUTH_KEY_LENGTH
] = '\0';
881 SEND_STRING ("-auth ");
882 SEND_STRING (auth_string
);
889 /* Returns 1 if PREFIX is a prefix of STRING. */
891 strprefix (char *prefix
, char *string
)
900 for (i
= 0; prefix
[i
]; i
++)
901 if (!string
[i
] || string
[i
] != prefix
[i
])
907 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
909 /* Three possibilities:
910 2 - can't be `stat'ed (sets errno)
911 1 - isn't owned by us
912 0 - success: none of the above */
915 socket_status (socket_name
)
920 if (stat (socket_name
, &statbfr
) == -1)
923 if (statbfr
.st_uid
!= geteuid ())
930 /* A signal handler that passes the signal to the Emacs process.
931 Useful for SIGWINCH. */
934 pass_signal_to_emacs (int signalnum
)
936 int old_errno
= errno
;
939 kill (emacs_pid
, signalnum
);
941 signal (signalnum
, pass_signal_to_emacs
);
945 /* Signal handler for SIGCONT; notify the Emacs process that it can
946 now resume our tty frame. */
949 handle_sigcont (int signalnum
)
951 int old_errno
= errno
;
953 if (tcgetpgrp (1) == getpgrp ())
955 /* We are in the foreground. */
956 SEND_STRING ("-resume \n");
960 /* We are in the background; cancel the continue. */
961 kill (getpid (), SIGSTOP
);
964 signal (signalnum
, handle_sigcont
);
968 /* Signal handler for SIGTSTP; notify the Emacs process that we are
969 going to sleep. Normally the suspend is initiated by Emacs via
970 server-handle-suspend-tty, but if the server gets out of sync with
971 reality, we may get a SIGTSTP on C-z. Handling this signal and
972 notifying Emacs about it should get things under control again. */
975 handle_sigtstp (int signalnum
)
977 int old_errno
= errno
;
981 SEND_STRING ("-suspend \n");
983 /* Unblock this signal and call the default handler by temprarily
984 changing the handler and resignalling. */
985 sigprocmask (SIG_BLOCK
, NULL
, &set
);
986 sigdelset (&set
, signalnum
);
987 signal (signalnum
, SIG_DFL
);
988 kill (getpid (), signalnum
);
989 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
990 signal (signalnum
, handle_sigtstp
);
994 /* Set up signal handlers before opening a frame on the current tty. */
999 /* Set up signal handlers. */
1000 signal (SIGWINCH
, pass_signal_to_emacs
);
1002 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1003 deciding which terminal the signal came from. C-g is now a
1004 normal input event on secondary terminals. */
1006 signal (SIGINT
, pass_signal_to_emacs
);
1007 signal (SIGQUIT
, pass_signal_to_emacs
);
1010 signal (SIGCONT
, handle_sigcont
);
1011 signal (SIGTSTP
, handle_sigtstp
);
1012 signal (SIGTTOU
, handle_sigtstp
);
1020 struct sockaddr_un server
;
1023 * Open up an AF_UNIX socket in this person's home directory
1026 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1028 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1029 return INVALID_SOCKET
;
1032 server
.sun_family
= AF_UNIX
;
1035 int sock_status
= 0;
1036 int default_sock
= !socket_name
;
1037 int saved_errno
= 0;
1039 char *server_name
= "server";
1041 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
1042 { /* socket_name is a file name component. */
1043 server_name
= socket_name
;
1045 default_sock
= 1; /* Try both UIDs. */
1050 socket_name
= alloca (100 + strlen (server_name
));
1051 sprintf (socket_name
, "/tmp/emacs%d/%s",
1052 (int) geteuid (), server_name
);
1055 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1056 strcpy (server
.sun_path
, socket_name
);
1059 message (TRUE
, "%s: socket-name %s too long",
1060 progname
, socket_name
);
1064 /* See if the socket exists, and if it's owned by us. */
1065 sock_status
= socket_status (server
.sun_path
);
1066 saved_errno
= errno
;
1067 if (sock_status
&& default_sock
)
1069 /* Failing that, see if LOGNAME or USER exist and differ from
1070 our euid. If so, look for a socket based on the UID
1071 associated with the name. This is reminiscent of the logic
1072 that init_editfns uses to set the global Vuser_full_name. */
1074 char *user_name
= (char *) getenv ("LOGNAME");
1077 user_name
= (char *) getenv ("USER");
1081 struct passwd
*pw
= getpwnam (user_name
);
1083 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1085 /* We're running under su, apparently. */
1086 socket_name
= alloca (100 + strlen (server_name
));
1087 sprintf (socket_name
, "/tmp/emacs%d/%s",
1088 (int) pw
->pw_uid
, server_name
);
1090 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1091 strcpy (server
.sun_path
, socket_name
);
1094 message (TRUE
, "%s: socket-name %s too long",
1095 progname
, socket_name
);
1096 exit (EXIT_FAILURE
);
1099 sock_status
= socket_status (server
.sun_path
);
1100 saved_errno
= errno
;
1103 errno
= saved_errno
;
1107 switch (sock_status
)
1110 /* There's a socket, but it isn't owned by us. This is OK if
1112 if (0 != geteuid ())
1114 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1115 return INVALID_SOCKET
;
1121 if (saved_errno
== ENOENT
)
1123 "%s: can't find socket; have you started the server?\n\
1124 To start the server in Emacs, type \"M-x server-start\".\n",
1127 message (TRUE
, "%s: can't stat %s: %s\n",
1128 progname
, server
.sun_path
, strerror (saved_errno
));
1129 return INVALID_SOCKET
;
1133 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1136 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1137 return INVALID_SOCKET
;
1142 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1151 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1152 /* Explicit --socket-name argument. */
1155 s
= set_local_socket ();
1156 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1158 message (TRUE
, "%s: error accessing socket \"%s\"",
1159 progname
, socket_name
);
1160 exit (EXIT_FAILURE
);
1164 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1166 server_file
= getenv ("EMACS_SERVER_FILE");
1170 s
= set_tcp_socket ();
1171 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1174 message (TRUE
, "%s: error accessing server file \"%s\"",
1175 progname
, server_file
);
1176 exit (EXIT_FAILURE
);
1179 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1180 /* Implicit local socket. */
1181 s
= set_local_socket ();
1182 if (s
!= INVALID_SOCKET
)
1186 /* Implicit server file. */
1187 server_file
= "server";
1188 s
= set_tcp_socket ();
1189 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1192 /* No implicit or explicit socket, and no alternate editor. */
1193 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1194 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1197 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1198 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1200 exit (EXIT_FAILURE
);
1204 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1205 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1208 w32_find_emacs_process (hWnd
, lParam
)
1215 /* Reject any window not of class "Emacs". */
1216 if (! get_wc (hWnd
, class, sizeof (class))
1217 || strcmp (class, "Emacs"))
1220 /* We only need the process id, not the thread id. */
1221 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1223 /* Not the one we're looking for. */
1224 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1226 /* OK, let's raise it. */
1229 /* Stop enumeration. */
1234 * Search for a window of class "Emacs" and owned by a process with
1235 * process id = emacs_pid. If found, allow it to grab the focus.
1242 /* It shouldn't happen when dealing with TCP sockets. */
1243 if (!emacs_pid
) return;
1245 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
1247 /* Modern Windows restrict which processes can set the foreground window.
1248 emacsclient can allow Emacs to grab the focus by calling the function
1249 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1250 NT) lack this function, so we have to check its availability. */
1251 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
1252 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
1253 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1255 FreeLibrary (hUser32
);
1264 int i
, rl
, needlf
= 0;
1266 char string
[BUFSIZ
+1];
1272 /* Process options. */
1273 decode_options (argc
, argv
);
1275 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
1277 message (TRUE
, "%s: file name or argument required\n"
1278 "Try `%s --help' for more information\n",
1279 progname
, progname
);
1280 exit (EXIT_FAILURE
);
1283 if ((emacs_socket
= set_socket ()) == INVALID_SOCKET
)
1287 cwd
= get_current_dir_name ();
1290 /* getwd puts message in STRING if it fails. */
1291 message (TRUE
, "%s: %s\n", progname
,
1292 "Cannot get current working directory");
1300 /* First of all, send our version number for verification. */
1301 SEND_STRING ("-version ");
1302 SEND_STRING (VERSION
);
1305 /* Send over our environment. */
1308 extern char **environ
;
1310 for (i
= 0; environ
[i
]; i
++)
1312 char *name
= xstrdup (environ
[i
]);
1313 char *value
= strchr (name
, '=');
1314 SEND_STRING ("-env ");
1315 SEND_QUOTED (environ
[i
]);
1320 /* Send over our current directory. */
1323 SEND_STRING ("-dir ");
1331 SEND_STRING ("-nowait ");
1334 SEND_STRING ("-current-frame ");
1338 SEND_STRING ("-display ");
1339 SEND_QUOTED (display
);
1345 char *tty_name
= NULL
;
1347 tty_name
= ttyname (fileno (stdin
));
1349 char *type
= getenv ("TERM");
1353 message (TRUE
, "%s: could not get terminal name\n", progname
);
1359 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1364 if (! strcmp (type
, "eterm"))
1366 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1367 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1368 " is not supported\n", progname
);
1371 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1375 SEND_STRING ("-tty ");
1376 SEND_QUOTED (tty_name
);
1383 SEND_STRING ("-window-system ");
1385 if ((argc
- optind
> 0))
1387 for (i
= optind
; i
< argc
; i
++)
1393 /* Don't prepend cwd or anything like that. */
1394 SEND_STRING ("-eval ");
1395 SEND_QUOTED (argv
[i
]);
1400 if (*argv
[i
] == '+')
1402 char *p
= argv
[i
] + 1;
1403 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1406 SEND_STRING ("-position ");
1407 SEND_QUOTED (argv
[i
]);
1414 else if (! file_name_absolute_p (argv
[i
]))
1417 SEND_STRING ("-file ");
1423 SEND_QUOTED (argv
[i
]);
1429 if (!tty
&& !window_system
)
1431 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1434 SEND_STRING ("-eval ");
1436 SEND_STRING ("-file ");
1445 /* Wait for an answer. */
1446 if (!eval
&& !tty
&& !nowait
)
1448 printf ("Waiting for Emacs...");
1454 /* Now, wait for an answer and print any messages. */
1455 while ((rl
= recv (emacs_socket
, string
, BUFSIZ
, 0)) > 0)
1460 p
= string
+ strlen (string
) - 1;
1461 while (p
> string
&& *p
== '\n')
1464 if (strprefix ("-good-version ", string
))
1466 /* -good-version: The versions match. */
1468 else if (strprefix ("-emacs-pid ", string
))
1470 /* -emacs-pid PID: The process id of the Emacs process. */
1471 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1473 else if (strprefix ("-window-system-unsupported ", string
))
1475 /* -window-system-unsupported: Emacs was compiled without X
1476 support. Try again on the terminal. */
1482 else if (strprefix ("-print ", string
))
1484 /* -print STRING: Print STRING on the terminal. */
1485 str
= unquote_argument (string
+ strlen ("-print "));
1489 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1491 else if (strprefix ("-error ", string
))
1493 /* -error DESCRIPTION: Signal an error on the terminal. */
1494 str
= unquote_argument (string
+ strlen ("-error "));
1497 fprintf (stderr
, "*ERROR*: %s", str
);
1498 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1501 else if (strprefix ("-suspend ", string
))
1503 /* -suspend: Suspend this terminal, i.e., stop the process. */
1512 /* Unknown command. */
1515 printf ("*ERROR*: Unknown message: %s", string
);
1516 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1525 CLOSE_SOCKET (emacs_socket
);
1526 return EXIT_SUCCESS
;
1529 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1532 #ifndef HAVE_STRERROR
1537 extern char *sys_errlist
[];
1538 extern int sys_nerr
;
1540 if (errnum
>= 0 && errnum
< sys_nerr
)
1541 return sys_errlist
[errnum
];
1542 return (char *) "Unknown error";
1545 #endif /* ! HAVE_STRERROR */
1547 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1548 (do not change this comment) */
1550 /* emacsclient.c ends here */