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! */
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 */
85 char *getenv (), *getwd ();
89 #define VERSION "unspecified"
94 #define EXIT_SUCCESS 0
98 #define EXIT_FAILURE 1
113 /* Name used to invoke this program. */
116 /* The second argument to main. */
119 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
122 /* Nonzero means args are expressions to be evaluated. --eval. */
125 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
126 int current_frame
= 1;
128 /* Nonzero means open a new graphical frame. */
129 int window_system
= 0;
131 /* The display on which Emacs should work. --display. */
132 char *display
= NULL
;
134 /* Nonzero means open a new Emacs frame on the current terminal. */
137 /* If non-NULL, the name of an editor to fallback to if the server
138 is not running. --alternate-editor. */
139 const char *alternate_editor
= NULL
;
141 /* If non-NULL, the filename of the UNIX socket. */
142 char *socket_name
= NULL
;
144 /* If non-NULL, the filename of the authentication file. */
145 char *server_file
= NULL
;
147 /* PID of the Emacs server process. */
150 void print_help_and_exit () NO_RETURN
;
152 struct option longopts
[] =
154 { "no-wait", no_argument
, NULL
, 'n' },
155 { "eval", no_argument
, NULL
, 'e' },
156 { "help", no_argument
, NULL
, 'H' },
157 { "version", no_argument
, NULL
, 'V' },
158 { "tty", no_argument
, NULL
, 't' },
159 { "create-frame", no_argument
, NULL
, 'c' },
160 { "alternate-editor", required_argument
, NULL
, 'a' },
161 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
162 { "socket-name", required_argument
, NULL
, 's' },
164 { "server-file", required_argument
, NULL
, 'f' },
165 { "display", required_argument
, NULL
, 'd' },
170 /* Like malloc but get fatal error if memory is exhausted. */
176 long *result
= (long *) malloc (size
);
185 /* Like strdup but get a fatal error if memory is exhausted. */
188 xstrdup (const char *s
)
190 char *result
= strdup (s
);
200 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
203 #ifndef DIRECTORY_SEP
204 #define DIRECTORY_SEP '/'
206 #ifndef IS_DIRECTORY_SEP
207 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
209 #ifndef IS_DEVICE_SEP
211 #define IS_DEVICE_SEP(_c_) 0
213 #define IS_DEVICE_SEP(_c_) ((_c_) == DEVICE_SEP)
217 #define IS_ANY_SEP(_c_) (IS_DIRECTORY_SEP (_c_))
221 /* Return the current working directory. Returns NULL on errors.
222 Any other returned value must be freed with free. This is used
223 only when get_current_dir_name is not defined on the system. */
225 get_current_dir_name ()
229 struct stat dotstat
, pwdstat
;
230 /* If PWD is accurate, use it instead of calling getwd. PWD is
231 sometimes a nicer name, and using it may avoid a fatal error if a
232 parent directory is searchable but not readable. */
233 if ((pwd
= getenv ("PWD")) != 0
234 && (IS_DIRECTORY_SEP (*pwd
) || (*pwd
&& IS_DEVICE_SEP (pwd
[1])))
235 && stat (pwd
, &pwdstat
) == 0
236 && stat (".", &dotstat
) == 0
237 && dotstat
.st_ino
== pwdstat
.st_ino
238 && dotstat
.st_dev
== pwdstat
.st_dev
240 && strlen (pwd
) < MAXPATHLEN
244 buf
= (char *) xmalloc (strlen (pwd
) + 1);
252 size_t buf_size
= 1024;
253 buf
= (char *) xmalloc (buf_size
);
258 if (getcwd (buf
, buf_size
) == buf
)
262 int tmp_errno
= errno
;
268 buf
= (char *) realloc (buf
, buf_size
);
276 /* We need MAXPATHLEN here. */
277 buf
= (char *) xmalloc (MAXPATHLEN
+ 1);
280 if (getwd (buf
) == NULL
)
282 int tmp_errno
= errno
;
293 /* Message functions. */
299 static int window_app
= -1;
300 char szTitle
[MAX_PATH
];
303 /* Checking for STDOUT does not work; it's a valid handle also in
304 nonconsole apps. Testing for the console title seems to work. */
305 window_app
= (GetConsoleTitleA (szTitle
, MAX_PATH
) == 0);
311 execvp wrapper for Windows. Quotes arguments with embedded spaces.
313 This is necessary due to the broken implementation of exec* routines in
314 the Microsoft libraries: they concatenate the arguments together without
315 quoting special characters, and pass the result to CreateProcess, with
316 predictably bad results. By contrast, Posix execvp passes the arguments
317 directly into the argv array of the child process.
320 w32_execvp (path
, argv
)
326 /* Required to allow a .BAT script as alternate editor. */
327 argv
[0] = (char *) alternate_editor
;
329 for (i
= 0; argv
[i
]; i
++)
330 if (strchr (argv
[i
], ' '))
332 char *quoted
= alloca (strlen (argv
[i
]) + 3);
333 sprintf (quoted
, "\"%s\"", argv
[i
]);
337 return execvp (path
, argv
);
341 #define execvp w32_execvp
343 #endif /* WINDOWSNT */
346 message (int is_error
, char *message
, ...)
351 va_start (args
, message
);
352 vsprintf (msg
, message
, args
);
356 if (w32_window_app ())
359 MessageBox (NULL
, msg
, "Emacsclient ERROR", MB_ICONERROR
);
361 MessageBox (NULL
, msg
, "Emacsclient", MB_ICONINFORMATION
);
366 FILE *f
= is_error
? stderr
: stdout
;
373 /* Decode the options from argv and argc.
374 The global variable `optind' will say how many arguments we used up. */
377 decode_options (argc
, argv
)
381 alternate_editor
= getenv ("ALTERNATE_EDITOR");
382 display
= getenv ("DISPLAY");
383 if (display
&& strlen (display
) == 0)
388 int opt
= getopt_long (argc
, argv
,
389 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
402 /* If getopt returns 0, then it has already processed a
403 long-named option. We should do nothing. */
407 alternate_editor
= optarg
;
410 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
412 socket_name
= optarg
;
417 server_file
= optarg
;
433 message (FALSE
, "emacsclient %s\n", VERSION
);
447 print_help_and_exit ();
451 message (TRUE
, "Try `%s --help' for more information\n", progname
);
459 #if !defined (WINDOWSNT) && !defined (HAVE_CARBON)
464 /* --no-wait implies --current-frame on ttys when there are file
465 arguments or expressions given. */
466 if (nowait
&& tty
&& argc
- optind
> 0)
481 print_help_and_exit ()
483 /* Spaces and tabs are significant in this message; they're chosen so the
484 message aligns properly both in a tty and in a Windows message box.
485 Please try to preserve them; otherwise the output is very hard to read
486 when using emacsclientw. */
488 "Usage: %s [OPTIONS] FILE...\n\
489 Tell the Emacs server to visit the specified files.\n\
490 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
492 The following OPTIONS are accepted:\n\
493 -V, --version Just print version info and return\n\
494 -H, --help Print this usage information message\n\
495 -t, --tty Open a new Emacs frame on the current terminal\n\
496 -c, --create-frame Create a new frame instead of trying to\n\
497 use the current Emacs frame\n\
498 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
499 -n, --no-wait Don't wait for the server to return\n\
500 -d, --display=DISPLAY Visit the file in the given display\n"
501 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
502 "-s, --socket-name=FILENAME\n\
503 Set filename of the UNIX socket for communication\n"
505 "-f, --server-file=FILENAME\n\
506 Set filename of the TCP authentication file\n\
507 -a, --alternate-editor=EDITOR\n\
508 Editor to fallback to if the server is not running\n\
510 Report bugs to bug-gnu-emacs@gnu.org.\n", progname
);
515 Try to run a different command, or --if no alternate editor is
516 defined-- exit with an errorcode.
517 Uses argv, but gets it from the global variable main_argv.
522 if (alternate_editor
)
526 execvp (alternate_editor
, main_argv
+ i
);
527 message (TRUE
, "%s: error executing alternate editor \"%s\"\n",
528 progname
, alternate_editor
);
534 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
543 message (TRUE
, "%s: Sorry, the Emacs server is supported only\n"
544 "on systems with Berkeley sockets.\n",
549 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
552 # include <winsock2.h>
554 # include <sys/types.h>
555 # include <sys/socket.h>
559 #define AUTH_KEY_LENGTH 64
560 #define SEND_BUFFER_SIZE 4096
562 extern char *strerror ();
565 /* Buffer to accumulate data to send in TCP connections. */
566 char send_buffer
[SEND_BUFFER_SIZE
+ 1];
567 int sblen
= 0; /* Fill pointer for the send buffer. */
568 /* Socket used to communicate with the Emacs server process. */
569 HSOCKET emacs_socket
= 0;
571 /* Let's send the data to Emacs when either
572 - the data ends in "\n", or
573 - the buffer is full (but this shouldn't happen)
574 Otherwise, we just accumulate it. */
576 send_to_emacs (s
, data
)
582 int dlen
= strlen (data
);
583 if (dlen
+ sblen
>= SEND_BUFFER_SIZE
)
585 int part
= SEND_BUFFER_SIZE
- sblen
;
586 strncpy (&send_buffer
[sblen
], data
, part
);
588 sblen
= SEND_BUFFER_SIZE
;
592 strcpy (&send_buffer
[sblen
], data
);
599 if (sblen
== SEND_BUFFER_SIZE
600 || (sblen
> 0 && send_buffer
[sblen
-1] == '\n'))
602 int sent
= send (s
, send_buffer
, sblen
, 0);
604 strcpy (send_buffer
, &send_buffer
[sent
]);
611 /* In STR, insert a & before each &, each space, each newline, and
612 any initial -. Change spaces to underscores, too, so that the
613 return value never contains a space.
615 Does not change the string. Outputs the result to STREAM. */
617 quote_argument (s
, str
)
621 char *copy
= (char *) xmalloc (strlen (str
) * 2 + 1);
642 if (*p
== '&' || (*p
== '-' && p
== str
))
649 send_to_emacs (s
, copy
);
655 /* The inverse of quote_argument. Removes quoting in string STR by
656 modifying the string in place. Returns STR. */
659 unquote_argument (str
)
691 file_name_absolute_p (filename
)
692 const unsigned char *filename
;
694 /* Sanity check, it shouldn't happen. */
695 if (! filename
) return FALSE
;
697 /* /xxx is always an absolute path. */
698 if (filename
[0] == '/') return TRUE
;
700 /* Empty filenames (which shouldn't happen) are relative. */
701 if (filename
[0] == '\0') return FALSE
;
704 /* X:\xxx is always absolute. */
705 if (isalpha (filename
[0])
706 && filename
[1] == ':' && (filename
[2] == '\\' || filename
[2] == '/'))
709 /* Both \xxx and \\xxx\yyy are absolute. */
710 if (filename
[0] == '\\') return TRUE
;
713 FIXME: There's a corner case not dealt with, "x:y", where:
715 1) x is a valid drive designation (usually a letter in the A-Z range)
716 and y is a path, relative to the current directory on drive x. This
717 is absolute, *after* fixing the y part to include the current
720 2) x is a relative file name, and y is an NTFS stream name. This is a
721 correct relative path, but it is very unusual.
723 The trouble is that first case items are also valid examples of the
724 second case, i.e., "c:test" can be understood as drive:path or as
727 The "right" fix would involve checking whether
728 - the current drive/partition is NTFS,
729 - x is a valid (and accesible) drive designator,
730 - x:y already exists as a file:stream in the current directory,
731 - y already exists on the current directory of drive x,
732 - the auspices are favorable,
733 and then taking an "informed decision" based on the above.
735 Whatever the result, Emacs currently does a very bad job of dealing
736 with NTFS file:streams: it cannot visit them, and the only way to
737 create one is by setting `buffer-file-name' to point to it (either
738 manually or with emacsclient). So perhaps resorting to 1) and ignoring
739 2) for now is the right thing to do.
741 Anyway, something to decide After the Release.
749 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
751 __cdecl
close_winsock ()
756 /* Initialize the WinSock2 library. */
758 initialize_sockets ()
762 if (WSAStartup (MAKEWORD (2, 0), &wsaData
))
764 message (TRUE
, "%s: error initializing WinSock2", progname
);
768 atexit (close_winsock
);
770 #endif /* WINDOWSNT */
774 * Read the information needed to set up a TCP comm channel with
775 * the Emacs server: host, port, pid and authentication string.
778 get_server_config (server
, authentication
)
779 struct sockaddr_in
*server
;
780 char *authentication
;
787 if (file_name_absolute_p (server_file
))
788 config
= fopen (server_file
, "rb");
791 char *home
= getenv ("HOME");
795 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
796 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
797 config
= fopen (path
, "rb");
800 if (!config
&& (home
= getenv ("APPDATA")))
802 char *path
= alloca (32 + strlen (home
) + strlen (server_file
));
803 sprintf (path
, "%s/.emacs.d/server/%s", home
, server_file
);
804 config
= fopen (path
, "rb");
812 if (fgets (dotted
, sizeof dotted
, config
)
813 && (port
= strchr (dotted
, ':'))
814 && (pid
= strchr (port
, ' ')))
821 message (TRUE
, "%s: invalid configuration info", progname
);
825 server
->sin_family
= AF_INET
;
826 server
->sin_addr
.s_addr
= inet_addr (dotted
);
827 server
->sin_port
= htons (atoi (port
));
829 if (! fread (authentication
, AUTH_KEY_LENGTH
, 1, config
))
831 message (TRUE
, "%s: cannot read authentication info", progname
);
837 emacs_pid
= atoi (pid
);
846 struct sockaddr_in server
;
847 struct linger l_arg
= {1, 1};
848 char auth_string
[AUTH_KEY_LENGTH
+ 1];
850 if (! get_server_config (&server
, auth_string
))
851 return INVALID_SOCKET
;
853 if (server
.sin_addr
.s_addr
!= inet_addr ("127.0.0.1"))
854 message (FALSE
, "%s: connected to remote socket at %s\n",
855 progname
, inet_ntoa (server
.sin_addr
));
858 * Open up an AF_INET socket
860 if ((s
= socket (AF_INET
, SOCK_STREAM
, IPPROTO_TCP
)) < 0)
862 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
863 return INVALID_SOCKET
;
869 if (connect (s
, (struct sockaddr
*) &server
, sizeof server
) < 0)
871 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
872 return INVALID_SOCKET
;
875 setsockopt (s
, SOL_SOCKET
, SO_LINGER
, (char *) &l_arg
, sizeof l_arg
);
878 * Send the authentication
880 auth_string
[AUTH_KEY_LENGTH
] = '\0';
882 send_to_emacs (s
, "-auth ");
883 send_to_emacs (s
, auth_string
);
884 send_to_emacs (s
, "\n");
890 /* Returns 1 if PREFIX is a prefix of STRING. */
892 strprefix (char *prefix
, char *string
)
894 return !strncmp (prefix
, string
, strlen (prefix
));
898 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
900 /* Three possibilities:
901 2 - can't be `stat'ed (sets errno)
902 1 - isn't owned by us
903 0 - success: none of the above */
906 socket_status (socket_name
)
911 if (stat (socket_name
, &statbfr
) == -1)
914 if (statbfr
.st_uid
!= geteuid ())
921 /* A signal handler that passes the signal to the Emacs process.
922 Useful for SIGWINCH. */
925 pass_signal_to_emacs (int signalnum
)
927 int old_errno
= errno
;
930 kill (emacs_pid
, signalnum
);
932 signal (signalnum
, pass_signal_to_emacs
);
936 /* Signal handler for SIGCONT; notify the Emacs process that it can
937 now resume our tty frame. */
940 handle_sigcont (int signalnum
)
942 int old_errno
= errno
;
944 if (tcgetpgrp (1) == getpgrp ())
946 /* We are in the foreground. */
947 send_to_emacs (emacs_socket
, "-resume \n");
951 /* We are in the background; cancel the continue. */
952 kill (getpid (), SIGSTOP
);
955 signal (signalnum
, handle_sigcont
);
959 /* Signal handler for SIGTSTP; notify the Emacs process that we are
960 going to sleep. Normally the suspend is initiated by Emacs via
961 server-handle-suspend-tty, but if the server gets out of sync with
962 reality, we may get a SIGTSTP on C-z. Handling this signal and
963 notifying Emacs about it should get things under control again. */
966 handle_sigtstp (int signalnum
)
968 int old_errno
= errno
;
972 send_to_emacs (emacs_socket
, "-suspend \n");
974 /* Unblock this signal and call the default handler by temprarily
975 changing the handler and resignalling. */
976 sigprocmask (SIG_BLOCK
, NULL
, &set
);
977 sigdelset (&set
, signalnum
);
978 signal (signalnum
, SIG_DFL
);
979 kill (getpid (), signalnum
);
980 sigprocmask (SIG_SETMASK
, &set
, NULL
); /* Let's the above signal through. */
981 signal (signalnum
, handle_sigtstp
);
985 /* Set up signal handlers before opening a frame on the current tty. */
990 /* Set up signal handlers. */
991 signal (SIGWINCH
, pass_signal_to_emacs
);
993 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
994 deciding which terminal the signal came from. C-g is now a
995 normal input event on secondary terminals. */
997 signal (SIGINT
, pass_signal_to_emacs
);
998 signal (SIGQUIT
, pass_signal_to_emacs
);
1001 signal (SIGCONT
, handle_sigcont
);
1002 signal (SIGTSTP
, handle_sigtstp
);
1003 signal (SIGTTOU
, handle_sigtstp
);
1011 struct sockaddr_un server
;
1014 * Open up an AF_UNIX socket in this person's home directory
1017 if ((s
= socket (AF_UNIX
, SOCK_STREAM
, 0)) < 0)
1019 message (TRUE
, "%s: socket: %s\n", progname
, strerror (errno
));
1020 return INVALID_SOCKET
;
1023 server
.sun_family
= AF_UNIX
;
1026 int sock_status
= 0;
1027 int default_sock
= !socket_name
;
1028 int saved_errno
= 0;
1029 char *server_name
= "server";
1031 if (socket_name
&& !index (socket_name
, '/') && !index (socket_name
, '\\'))
1032 { /* socket_name is a file name component. */
1033 server_name
= socket_name
;
1035 default_sock
= 1; /* Try both UIDs. */
1040 socket_name
= alloca (100 + strlen (server_name
));
1041 sprintf (socket_name
, "/tmp/emacs%d/%s",
1042 (int) geteuid (), server_name
);
1045 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1046 strcpy (server
.sun_path
, socket_name
);
1049 message (TRUE
, "%s: socket-name %s too long",
1050 progname
, socket_name
);
1054 /* See if the socket exists, and if it's owned by us. */
1055 sock_status
= socket_status (server
.sun_path
);
1056 saved_errno
= errno
;
1057 if (sock_status
&& default_sock
)
1059 /* Failing that, see if LOGNAME or USER exist and differ from
1060 our euid. If so, look for a socket based on the UID
1061 associated with the name. This is reminiscent of the logic
1062 that init_editfns uses to set the global Vuser_full_name. */
1064 char *user_name
= (char *) getenv ("LOGNAME");
1067 user_name
= (char *) getenv ("USER");
1071 struct passwd
*pw
= getpwnam (user_name
);
1073 if (pw
&& (pw
->pw_uid
!= geteuid ()))
1075 /* We're running under su, apparently. */
1076 socket_name
= alloca (100 + strlen (server_name
));
1077 sprintf (socket_name
, "/tmp/emacs%d/%s",
1078 (int) pw
->pw_uid
, server_name
);
1080 if (strlen (socket_name
) < sizeof (server
.sun_path
))
1081 strcpy (server
.sun_path
, socket_name
);
1084 message (TRUE
, "%s: socket-name %s too long",
1085 progname
, socket_name
);
1086 exit (EXIT_FAILURE
);
1089 sock_status
= socket_status (server
.sun_path
);
1090 saved_errno
= errno
;
1093 errno
= saved_errno
;
1097 switch (sock_status
)
1100 /* There's a socket, but it isn't owned by us. This is OK if
1102 if (0 != geteuid ())
1104 message (TRUE
, "%s: Invalid socket owner\n", progname
);
1105 return INVALID_SOCKET
;
1111 if (saved_errno
== ENOENT
)
1113 "%s: can't find socket; have you started the server?\n\
1114 To start the server in Emacs, type \"M-x server-start\".\n",
1117 message (TRUE
, "%s: can't stat %s: %s\n",
1118 progname
, server
.sun_path
, strerror (saved_errno
));
1119 return INVALID_SOCKET
;
1123 if (connect (s
, (struct sockaddr
*) &server
, strlen (server
.sun_path
) + 2)
1126 message (TRUE
, "%s: connect: %s\n", progname
, strerror (errno
));
1127 return INVALID_SOCKET
;
1132 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1141 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1142 /* Explicit --socket-name argument. */
1145 s
= set_local_socket ();
1146 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1148 message (TRUE
, "%s: error accessing socket \"%s\"",
1149 progname
, socket_name
);
1150 exit (EXIT_FAILURE
);
1154 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1156 server_file
= getenv ("EMACS_SERVER_FILE");
1160 s
= set_tcp_socket ();
1161 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1164 message (TRUE
, "%s: error accessing server file \"%s\"",
1165 progname
, server_file
);
1166 exit (EXIT_FAILURE
);
1169 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1170 /* Implicit local socket. */
1171 s
= set_local_socket ();
1172 if (s
!= INVALID_SOCKET
)
1176 /* Implicit server file. */
1177 server_file
= "server";
1178 s
= set_tcp_socket ();
1179 if ((s
!= INVALID_SOCKET
) || alternate_editor
)
1182 /* No implicit or explicit socket, and no alternate editor. */
1183 message (TRUE
, "%s: No socket or alternate editor. Please use:\n\n"
1184 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1187 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1188 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1190 exit (EXIT_FAILURE
);
1194 FARPROC set_fg
; /* Pointer to AllowSetForegroundWindow. */
1195 FARPROC get_wc
; /* Pointer to RealGetWindowClassA. */
1198 w32_find_emacs_process (hWnd
, lParam
)
1205 /* Reject any window not of class "Emacs". */
1206 if (! get_wc (hWnd
, class, sizeof (class))
1207 || strcmp (class, "Emacs"))
1210 /* We only need the process id, not the thread id. */
1211 (void) GetWindowThreadProcessId (hWnd
, &pid
);
1213 /* Not the one we're looking for. */
1214 if (pid
!= (DWORD
) emacs_pid
) return TRUE
;
1216 /* OK, let's raise it. */
1219 /* Stop enumeration. */
1224 * Search for a window of class "Emacs" and owned by a process with
1225 * process id = emacs_pid. If found, allow it to grab the focus.
1232 /* It shouldn't happen when dealing with TCP sockets. */
1233 if (!emacs_pid
) return;
1235 if (!(hUser32
= LoadLibrary ("user32.dll"))) return;
1237 /* Modern Windows restrict which processes can set the foreground window.
1238 emacsclient can allow Emacs to grab the focus by calling the function
1239 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1240 NT) lack this function, so we have to check its availability. */
1241 if ((set_fg
= GetProcAddress (hUser32
, "AllowSetForegroundWindow"))
1242 && (get_wc
= GetProcAddress (hUser32
, "RealGetWindowClassA")))
1243 EnumWindows (w32_find_emacs_process
, (LPARAM
) 0);
1245 FreeLibrary (hUser32
);
1254 int i
, rl
, needlf
= 0;
1256 char string
[BUFSIZ
+1];
1261 /* Process options. */
1262 decode_options (argc
, argv
);
1264 if ((argc
- optind
< 1) && !eval
&& !tty
&& !window_system
)
1266 message (TRUE
, "%s: file name or argument required\n"
1267 "Try `%s --help' for more information\n",
1268 progname
, progname
);
1269 exit (EXIT_FAILURE
);
1272 if ((emacs_socket
= set_socket ()) == INVALID_SOCKET
)
1276 cwd
= get_current_dir_name ();
1279 /* getwd puts message in STRING if it fails. */
1280 message (TRUE
, "%s: %s\n", progname
,
1281 "Cannot get current working directory");
1289 /* Send over our environment. */
1292 extern char **environ
;
1294 for (i
= 0; environ
[i
]; i
++)
1296 char *name
= xstrdup (environ
[i
]);
1297 char *value
= strchr (name
, '=');
1298 send_to_emacs (emacs_socket
, "-env ");
1299 quote_argument (emacs_socket
, environ
[i
]);
1300 send_to_emacs (emacs_socket
, " ");
1304 /* Send over our current directory. */
1307 send_to_emacs (emacs_socket
, "-dir ");
1308 quote_argument (emacs_socket
, cwd
);
1309 send_to_emacs (emacs_socket
, "/");
1310 send_to_emacs (emacs_socket
, " ");
1315 send_to_emacs (emacs_socket
, "-nowait ");
1318 send_to_emacs (emacs_socket
, "-current-frame ");
1322 send_to_emacs (emacs_socket
, "-display ");
1323 quote_argument (emacs_socket
, display
);
1324 send_to_emacs (emacs_socket
, " ");
1329 char *type
= getenv ("TERM");
1330 char *tty_name
= NULL
;
1332 tty_name
= ttyname (fileno (stdin
));
1337 message (TRUE
, "%s: could not get terminal name\n", progname
);
1343 message (TRUE
, "%s: please set the TERM variable to your terminal type\n",
1348 if (! strcmp (type
, "eterm"))
1350 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1351 message (TRUE
, "%s: opening a frame in an Emacs term buffer"
1352 " is not supported\n", progname
);
1355 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1359 send_to_emacs (emacs_socket
, "-tty ");
1360 quote_argument (emacs_socket
, tty_name
);
1361 send_to_emacs (emacs_socket
, " ");
1362 quote_argument (emacs_socket
, type
);
1363 send_to_emacs (emacs_socket
, " ");
1367 send_to_emacs (emacs_socket
, "-window-system ");
1369 if ((argc
- optind
> 0))
1371 for (i
= optind
; i
< argc
; i
++)
1377 /* Don't prepend cwd or anything like that. */
1378 send_to_emacs (emacs_socket
, "-eval ");
1379 quote_argument (emacs_socket
, argv
[i
]);
1380 send_to_emacs (emacs_socket
, " ");
1384 if (*argv
[i
] == '+')
1386 char *p
= argv
[i
] + 1;
1387 while (isdigit ((unsigned char) *p
) || *p
== ':') p
++;
1390 send_to_emacs (emacs_socket
, "-position ");
1391 quote_argument (emacs_socket
, argv
[i
]);
1392 send_to_emacs (emacs_socket
, " ");
1398 else if (! file_name_absolute_p (argv
[i
]))
1401 send_to_emacs (emacs_socket
, "-file ");
1404 quote_argument (emacs_socket
, cwd
);
1405 send_to_emacs (emacs_socket
, "/");
1407 quote_argument (emacs_socket
, argv
[i
]);
1408 send_to_emacs (emacs_socket
, " ");
1413 if (!tty
&& !window_system
)
1415 while ((str
= fgets (string
, BUFSIZ
, stdin
)))
1418 send_to_emacs (emacs_socket
, "-eval ");
1420 send_to_emacs (emacs_socket
, "-file ");
1421 quote_argument (emacs_socket
, str
);
1423 send_to_emacs (emacs_socket
, " ");
1427 send_to_emacs (emacs_socket
, "\n");
1429 /* Wait for an answer. */
1430 if (!eval
&& !tty
&& !nowait
)
1432 printf ("Waiting for Emacs...");
1438 /* Now, wait for an answer and print any messages. */
1439 while ((rl
= recv (emacs_socket
, string
, BUFSIZ
, 0)) > 0)
1444 p
= string
+ strlen (string
) - 1;
1445 while (p
> string
&& *p
== '\n')
1448 if (strprefix ("-emacs-pid ", string
))
1450 /* -emacs-pid PID: The process id of the Emacs process. */
1451 emacs_pid
= strtol (string
+ strlen ("-emacs-pid"), NULL
, 10);
1453 else if (strprefix ("-window-system-unsupported ", string
))
1455 /* -window-system-unsupported: Emacs was compiled without X
1456 support. Try again on the terminal. */
1462 else if (strprefix ("-print ", string
))
1464 /* -print STRING: Print STRING on the terminal. */
1465 str
= unquote_argument (string
+ strlen ("-print "));
1469 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1471 else if (strprefix ("-error ", string
))
1473 /* -error DESCRIPTION: Signal an error on the terminal. */
1474 str
= unquote_argument (string
+ strlen ("-error "));
1477 fprintf (stderr
, "*ERROR*: %s", str
);
1478 needlf
= str
[0] == '\0' ? needlf
: str
[strlen (str
) - 1] != '\n';
1481 else if (strprefix ("-suspend ", string
))
1483 /* -suspend: Suspend this terminal, i.e., stop the process. */
1492 /* Unknown command. */
1495 printf ("*ERROR*: Unknown message: %s", string
);
1496 needlf
= string
[0] == '\0' ? needlf
: string
[strlen (string
) - 1] != '\n';
1505 CLOSE_SOCKET (emacs_socket
);
1506 return EXIT_SUCCESS
;
1509 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
1512 #ifndef HAVE_STRERROR
1517 extern char *sys_errlist
[];
1518 extern int sys_nerr
;
1520 if (errnum
>= 0 && errnum
< sys_nerr
)
1521 return sys_errlist
[errnum
];
1522 return (char *) "Unknown error";
1525 #endif /* ! HAVE_STRERROR */
1527 /* arch-tag: f39bb9c4-73eb-477e-896d-50832e2ca9a7
1528 (do not change this comment) */
1530 /* emacsclient.c ends here */