Fix C-p and C-n when wrap-prefix is too wide
[emacs.git] / lib-src / emacsclient.c
blobb139b2fe3f60349b812a661d2113c8c3abc9cc8f
1 /* Client process that communicates with GNU Emacs acting as server.
3 Copyright (C) 1986-1987, 1994, 1999-2018 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 of the License, or (at
10 your option) any later version.
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. If not, see <https://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #ifdef WINDOWSNT
25 /* ms-w32.h defines these, which disables sockets altogether! */
26 # undef _WINSOCKAPI_
27 # undef _WINSOCK_H
29 # include <malloc.h>
30 # include <stdlib.h>
31 # include <windows.h>
32 # include <commctrl.h>
33 # include <io.h>
34 # include <winsock2.h>
36 # define NO_SOCKETS_IN_FILE_SYSTEM
38 # define HSOCKET SOCKET
39 # define CLOSE_SOCKET closesocket
40 # define INITIALIZE() (initialize_sockets ())
42 char *w32_getenv (const char *);
43 #define egetenv(VAR) w32_getenv(VAR)
45 #else /* !WINDOWSNT */
47 # ifdef HAVE_NTGUI
48 # include <windows.h>
49 # endif /* HAVE_NTGUI */
51 # include "syswait.h"
53 # ifdef HAVE_INET_SOCKETS
54 # include <netinet/in.h>
55 # ifdef HAVE_SOCKETS
56 # include <sys/types.h>
57 # include <sys/socket.h>
58 # include <sys/un.h>
59 # endif /* HAVE_SOCKETS */
60 # endif
61 # include <arpa/inet.h>
63 # define INVALID_SOCKET -1
64 # define HSOCKET int
65 # define CLOSE_SOCKET close
66 # define INITIALIZE()
68 #define egetenv(VAR) getenv(VAR)
70 #endif /* !WINDOWSNT */
72 #undef signal
74 #include <stdarg.h>
75 #include <ctype.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <getopt.h>
79 #include <unistd.h>
81 #include <pwd.h>
82 #include <sys/stat.h>
83 #include <signal.h>
84 #include <errno.h>
86 #include <unlocked-io.h>
88 #ifndef VERSION
89 #define VERSION "unspecified"
90 #endif
93 #ifndef EXIT_SUCCESS
94 #define EXIT_SUCCESS 0
95 #endif
97 #ifndef EXIT_FAILURE
98 #define EXIT_FAILURE 1
99 #endif
101 /* Additional space when allocating buffers for filenames, etc. */
102 #define EXTRA_SPACE 100
104 #ifdef min
105 #undef min
106 #endif
107 #define min(x, y) (((x) < (y)) ? (x) : (y))
110 /* Name used to invoke this program. */
111 const char *progname;
113 /* The first argument to main. */
114 int main_argc;
116 /* The second argument to main. */
117 char **main_argv;
119 /* Nonzero means don't wait for a response from Emacs. --no-wait. */
120 int nowait = 0;
122 /* Nonzero means don't print messages for successful operations. --quiet. */
123 int quiet = 0;
125 /* Nonzero means don't print values returned from emacs. --suppress-output. */
126 int suppress_output = 0;
128 /* Nonzero means args are expressions to be evaluated. --eval. */
129 int eval = 0;
131 /* Nonzero means don't open a new frame. Inverse of --create-frame. */
132 int current_frame = 1;
134 /* The display on which Emacs should work. --display. */
135 const char *display = NULL;
137 /* The alternate display we should try if Emacs does not support display. */
138 const char *alt_display = NULL;
140 /* The parent window ID, if we are opening a frame via XEmbed. */
141 char *parent_id = NULL;
143 /* Nonzero means open a new Emacs frame on the current terminal. */
144 int tty = 0;
146 /* If non-NULL, the name of an editor to fallback to if the server
147 is not running. --alternate-editor. */
148 const char *alternate_editor = NULL;
150 /* If non-NULL, the filename of the UNIX socket. */
151 const char *socket_name = NULL;
153 /* If non-NULL, the filename of the authentication file. */
154 const char *server_file = NULL;
156 /* If non-NULL, the tramp prefix emacs must use to find the files. */
157 const char *tramp_prefix = NULL;
159 /* PID of the Emacs server process. */
160 int emacs_pid = 0;
162 /* If non-NULL, a string that should form a frame parameter alist to
163 be used for the new frame. */
164 const char *frame_parameters = NULL;
166 static _Noreturn void print_help_and_exit (void);
169 struct option longopts[] =
171 { "no-wait", no_argument, NULL, 'n' },
172 { "quiet", no_argument, NULL, 'q' },
173 { "suppress-output", no_argument, NULL, 'u' },
174 { "eval", no_argument, NULL, 'e' },
175 { "help", no_argument, NULL, 'H' },
176 { "version", no_argument, NULL, 'V' },
177 { "tty", no_argument, NULL, 't' },
178 { "nw", no_argument, NULL, 't' },
179 { "create-frame", no_argument, NULL, 'c' },
180 { "alternate-editor", required_argument, NULL, 'a' },
181 { "frame-parameters", required_argument, NULL, 'F' },
182 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
183 { "socket-name", required_argument, NULL, 's' },
184 #endif
185 { "server-file", required_argument, NULL, 'f' },
186 { "display", required_argument, NULL, 'd' },
187 { "parent-id", required_argument, NULL, 'p' },
188 { "tramp", required_argument, NULL, 'T' },
189 { 0, 0, 0, 0 }
193 /* Like malloc but get fatal error if memory is exhausted. */
195 static void *
196 xmalloc (size_t size)
198 void *result = malloc (size);
199 if (result == NULL)
201 perror ("malloc");
202 exit (EXIT_FAILURE);
204 return result;
207 /* Like realloc but get fatal error if memory is exhausted. */
209 static void *
210 xrealloc (void *ptr, size_t size)
212 void *result = realloc (ptr, size);
213 if (result == NULL)
215 perror ("realloc");
216 exit (EXIT_FAILURE);
218 return result;
221 /* Like strdup but get a fatal error if memory is exhausted. */
222 char *xstrdup (const char *);
224 char *
225 xstrdup (const char *s)
227 char *result = strdup (s);
228 if (result == NULL)
230 perror ("strdup");
231 exit (EXIT_FAILURE);
233 return result;
236 /* From sysdep.c */
237 #if !defined (HAVE_GET_CURRENT_DIR_NAME) || defined (BROKEN_GET_CURRENT_DIR_NAME)
239 char *get_current_dir_name (void);
241 /* Return the current working directory. Returns NULL on errors.
242 Any other returned value must be freed with free. This is used
243 only when get_current_dir_name is not defined on the system. */
244 char *
245 get_current_dir_name (void)
247 char *buf;
248 const char *pwd;
249 struct stat dotstat, pwdstat;
250 /* If PWD is accurate, use it instead of calling getcwd. PWD is
251 sometimes a nicer name, and using it may avoid a fatal error if a
252 parent directory is searchable but not readable. */
253 if ((pwd = egetenv ("PWD")) != 0
254 && (IS_DIRECTORY_SEP (*pwd) || (*pwd && IS_DEVICE_SEP (pwd[1])))
255 && stat (pwd, &pwdstat) == 0
256 && stat (".", &dotstat) == 0
257 && dotstat.st_ino == pwdstat.st_ino
258 && dotstat.st_dev == pwdstat.st_dev
259 #ifdef MAXPATHLEN
260 && strlen (pwd) < MAXPATHLEN
261 #endif
264 buf = (char *) xmalloc (strlen (pwd) + 1);
265 strcpy (buf, pwd);
267 else
269 size_t buf_size = 1024;
270 for (;;)
272 int tmp_errno;
273 buf = malloc (buf_size);
274 if (! buf)
275 break;
276 if (getcwd (buf, buf_size) == buf)
277 break;
278 tmp_errno = errno;
279 free (buf);
280 if (tmp_errno != ERANGE)
282 errno = tmp_errno;
283 return NULL;
285 buf_size *= 2;
286 if (! buf_size)
288 errno = ENOMEM;
289 return NULL;
293 return buf;
295 #endif
297 #ifdef WINDOWSNT
299 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
301 char *w32_get_resource (HKEY, const char *, LPDWORD);
303 /* Retrieve an environment variable from the Emacs subkeys of the registry.
304 Return NULL if the variable was not found, or it was empty.
305 This code is based on w32_get_resource (w32.c). */
306 char *
307 w32_get_resource (HKEY predefined, const char *key, LPDWORD type)
309 HKEY hrootkey = NULL;
310 char *result = NULL;
311 DWORD cbData;
313 if (RegOpenKeyEx (predefined, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
315 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS)
317 result = (char *) xmalloc (cbData);
319 if ((RegQueryValueEx (hrootkey, key, NULL, type, (LPBYTE)result, &cbData) != ERROR_SUCCESS)
320 || (*result == 0))
322 free (result);
323 result = NULL;
327 RegCloseKey (hrootkey);
330 return result;
334 getenv wrapper for Windows
336 Value is allocated on the heap, and can be free'd.
338 This is needed to duplicate Emacs's behavior, which is to look for
339 environment variables in the registry if they don't appear in the
340 environment. */
341 char *
342 w32_getenv (const char *envvar)
344 char *value;
345 DWORD dwType;
347 if ((value = getenv (envvar)))
348 /* Found in the environment. strdup it, because values returned
349 by getenv cannot be free'd. */
350 return xstrdup (value);
352 if (! (value = w32_get_resource (HKEY_CURRENT_USER, envvar, &dwType)) &&
353 ! (value = w32_get_resource (HKEY_LOCAL_MACHINE, envvar, &dwType)))
355 /* "w32console" is what Emacs on Windows uses for tty-type under -nw. */
356 if (strcmp (envvar, "TERM") == 0)
357 return xstrdup ("w32console");
358 /* Found neither in the environment nor in the registry. */
359 return NULL;
362 if (dwType == REG_SZ)
363 /* Registry; no need to expand. */
364 return value;
366 if (dwType == REG_EXPAND_SZ)
368 DWORD size;
370 if ((size = ExpandEnvironmentStrings (value, NULL, 0)))
372 char *buffer = (char *) xmalloc (size);
373 if (ExpandEnvironmentStrings (value, buffer, size))
375 /* Found and expanded. */
376 free (value);
377 return buffer;
380 /* Error expanding. */
381 free (buffer);
385 /* Not the right type, or not correctly expanded. */
386 free (value);
387 return NULL;
390 int w32_window_app (void);
393 w32_window_app (void)
395 static int window_app = -1;
396 char szTitle[MAX_PATH];
398 if (window_app < 0)
400 /* Checking for STDOUT does not work; it's a valid handle also in
401 nonconsole apps. Testing for the console title seems to work. */
402 window_app = (GetConsoleTitleA (szTitle, MAX_PATH) == 0);
403 if (window_app)
404 InitCommonControls ();
407 return window_app;
410 /* execvp wrapper for Windows. Quotes arguments with embedded spaces.
412 This is necessary due to the broken implementation of exec* routines in
413 the Microsoft libraries: they concatenate the arguments together without
414 quoting special characters, and pass the result to CreateProcess, with
415 predictably bad results. By contrast, POSIX execvp passes the arguments
416 directly into the argv array of the child process. */
418 int w32_execvp (const char *, char **);
421 w32_execvp (const char *path, char **argv)
423 int i;
425 /* Required to allow a .BAT script as alternate editor. */
426 argv[0] = (char *) alternate_editor;
428 for (i = 0; argv[i]; i++)
429 if (strchr (argv[i], ' '))
431 char *quoted = alloca (strlen (argv[i]) + 3);
432 sprintf (quoted, "\"%s\"", argv[i]);
433 argv[i] = quoted;
436 return execvp (path, argv);
439 #undef execvp
440 #define execvp w32_execvp
442 /* Emulation of ttyname for Windows. */
443 const char *ttyname (int);
444 const char *
445 ttyname (int fd)
447 return "CONOUT$";
450 #endif /* WINDOWSNT */
452 /* Display a normal or error message.
453 On Windows, use a message box if compiled as a Windows app. */
454 static void message (bool, const char *, ...) ATTRIBUTE_FORMAT_PRINTF (2, 3);
455 static void
456 message (bool is_error, const char *format, ...)
458 va_list args;
460 va_start (args, format);
462 #ifdef WINDOWSNT
463 if (w32_window_app ())
465 char msg[2048];
466 vsnprintf (msg, sizeof msg, format, args);
467 msg[sizeof msg - 1] = '\0';
469 if (is_error)
470 MessageBox (NULL, msg, "Emacsclient ERROR", MB_ICONERROR);
471 else
472 MessageBox (NULL, msg, "Emacsclient", MB_ICONINFORMATION);
474 else
475 #endif
477 FILE *f = is_error ? stderr : stdout;
479 vfprintf (f, format, args);
480 fflush (f);
483 va_end (args);
486 /* Decode the options from argv and argc.
487 The global variable `optind' will say how many arguments we used up. */
489 static void
490 decode_options (int argc, char **argv)
492 alternate_editor = egetenv ("ALTERNATE_EDITOR");
493 tramp_prefix = egetenv ("EMACSCLIENT_TRAMP");
495 while (1)
497 int opt = getopt_long_only (argc, argv,
498 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
499 "VHnequa:s:f:d:F:tcT:",
500 #else
501 "VHnequa:f:d:F:tcT:",
502 #endif
503 longopts, 0);
505 if (opt == EOF)
506 break;
508 switch (opt)
510 case 0:
511 /* If getopt returns 0, then it has already processed a
512 long-named option. We should do nothing. */
513 break;
515 case 'a':
516 alternate_editor = optarg;
517 break;
519 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
520 case 's':
521 socket_name = optarg;
522 break;
523 #endif
525 case 'f':
526 server_file = optarg;
527 break;
529 /* We used to disallow this argument in w32, but it seems better
530 to allow it, for the occasional case where the user is
531 connecting with a w32 client to a server compiled with X11
532 support. */
533 case 'd':
534 display = optarg;
535 break;
537 case 'n':
538 nowait = 1;
539 break;
541 case 'e':
542 eval = 1;
543 break;
545 case 'q':
546 quiet = 1;
547 break;
549 case 'u':
550 suppress_output = 1;
551 break;
553 case 'V':
554 message (false, "emacsclient %s\n", VERSION);
555 exit (EXIT_SUCCESS);
556 break;
558 case 't':
559 tty = 1;
560 current_frame = 0;
561 break;
563 case 'c':
564 current_frame = 0;
565 break;
567 case 'p':
568 parent_id = optarg;
569 current_frame = 0;
570 break;
572 case 'H':
573 print_help_and_exit ();
574 break;
576 case 'F':
577 frame_parameters = optarg;
578 break;
580 case 'T':
581 tramp_prefix = optarg;
582 break;
584 default:
585 message (true, "Try '%s --help' for more information\n", progname);
586 exit (EXIT_FAILURE);
587 break;
591 /* If the -c option is used (without -t) and no --display argument
592 is provided, try $DISPLAY.
593 Without the -c option, we used to set `display' to $DISPLAY by
594 default, but this changed the default behavior and is sometimes
595 inconvenient. So we force users to use "--display $DISPLAY" if
596 they want Emacs to connect to their current display.
598 Some window systems have a notion of default display not
599 reflected in the DISPLAY variable. If the user didn't give us an
600 explicit display, try this platform-specific after trying the
601 display in DISPLAY (if any). */
602 if (!current_frame && !tty && !display)
604 /* Set these here so we use a default_display only when the user
605 didn't give us an explicit display. */
606 #if defined (NS_IMPL_COCOA)
607 alt_display = "ns";
608 #elif defined (HAVE_NTGUI)
609 alt_display = "w32";
610 #endif
612 display = egetenv ("DISPLAY");
615 if (!display)
617 display = alt_display;
618 alt_display = NULL;
621 /* A null-string display is invalid. */
622 if (display && strlen (display) == 0)
623 display = NULL;
625 /* If no display is available, new frames are tty frames. */
626 if (!current_frame && !display)
627 tty = 1;
629 #ifdef WINDOWSNT
630 /* Emacs on Windows does not support graphical and text terminal
631 frames in the same instance. So, treat the -t and -c options as
632 equivalent, and open a new frame on the server's terminal.
633 Ideally, we would only set tty = 1 when the serve is running in a
634 console, but alas we don't know that. As a workaround, always
635 ask for a tty frame, and let server.el figure it out. */
636 if (!current_frame)
638 display = NULL;
639 tty = 1;
641 #endif /* WINDOWSNT */
645 static _Noreturn void
646 print_help_and_exit (void)
648 /* Spaces and tabs are significant in this message; they're chosen so the
649 message aligns properly both in a tty and in a Windows message box.
650 Please try to preserve them; otherwise the output is very hard to read
651 when using emacsclientw. */
652 message (false,
653 "Usage: %s [OPTIONS] FILE...\n%s%s%s", progname, "\
654 Tell the Emacs server to visit the specified files.\n\
655 Every FILE can be either just a FILENAME or [+LINE[:COLUMN]] FILENAME.\n\
657 The following OPTIONS are accepted:\n\
658 -V, --version Just print version info and return\n\
659 -H, --help Print this usage information message\n\
660 -nw, -t, --tty Open a new Emacs frame on the current terminal\n\
661 -c, --create-frame Create a new frame instead of trying to\n\
662 use the current Emacs frame\n\
663 ", "\
664 -F ALIST, --frame-parameters=ALIST\n\
665 Set the parameters of a new frame\n\
666 -e, --eval Evaluate the FILE arguments as ELisp expressions\n\
667 -n, --no-wait Don't wait for the server to return\n\
668 -q, --quiet Don't display messages on success\n\
669 -u, --suppress-output Don't display return values from the server\n\
670 -d DISPLAY, --display=DISPLAY\n\
671 Visit the file in the given display\n\
672 ", "\
673 --parent-id=ID Open in parent window ID, via XEmbed\n"
674 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
675 "-s SOCKET, --socket-name=SOCKET\n\
676 Set filename of the UNIX socket for communication\n"
677 #endif
678 "-f SERVER, --server-file=SERVER\n\
679 Set filename of the TCP authentication file\n\
680 -a EDITOR, --alternate-editor=EDITOR\n\
681 Editor to fallback to if the server is not running\n"
682 " If EDITOR is the empty string, start Emacs in daemon\n\
683 mode and try connecting again\n"
684 "-T PREFIX, --tramp=PREFIX\n\
685 PREFIX to prepend to filenames sent by emacsclient\n\
686 for locating files remotely via Tramp\n"
687 "\n\
688 Report bugs with M-x report-emacs-bug.\n");
689 exit (EXIT_SUCCESS);
692 /* Try to run a different command, or --if no alternate editor is
693 defined-- exit with an error code.
694 Uses argv, but gets it from the global variable main_argv. */
696 static _Noreturn void
697 fail (void)
699 if (alternate_editor)
701 size_t extra_args_size = (main_argc - optind + 1) * sizeof (char *);
702 size_t new_argv_size = extra_args_size;
703 char **new_argv = xmalloc (new_argv_size);
704 char *s = xstrdup (alternate_editor);
705 unsigned toks = 0;
707 /* Unpack alternate_editor's space-separated tokens into new_argv. */
708 for (char *tok = s; tok != NULL && *tok != '\0';)
710 /* Allocate new token. */
711 ++toks;
712 new_argv = xrealloc (new_argv, new_argv_size + toks * sizeof (char *));
714 /* Skip leading delimiters, and set separator, skipping any
715 opening quote. */
716 size_t skip = strspn (tok, " \"");
717 tok += skip;
718 char sep = (skip > 0 && tok[-1] == '"') ? '"' : ' ';
720 /* Record start of token. */
721 new_argv[toks - 1] = tok;
723 /* Find end of token and overwrite it with NUL. */
724 tok = strchr (tok, sep);
725 if (tok != NULL)
726 *tok++ = '\0';
729 /* Append main_argv arguments to new_argv. */
730 memcpy (&new_argv[toks], main_argv + optind, extra_args_size);
732 execvp (*new_argv, new_argv);
733 message (true, "%s: error executing alternate editor \"%s\"\n",
734 progname, alternate_editor);
736 exit (EXIT_FAILURE);
740 #if !defined (HAVE_SOCKETS) || !defined (HAVE_INET_SOCKETS)
743 main (int argc, char **argv)
745 main_argc = argc;
746 main_argv = argv;
747 progname = argv[0];
748 message (true, "%s: Sorry, the Emacs server is supported only\n"
749 "on systems with Berkeley sockets.\n",
750 argv[0]);
751 fail ();
754 #else /* HAVE_SOCKETS && HAVE_INET_SOCKETS */
756 #define AUTH_KEY_LENGTH 64
757 #define SEND_BUFFER_SIZE 4096
759 /* Buffer to accumulate data to send in TCP connections. */
760 char send_buffer[SEND_BUFFER_SIZE + 1];
761 int sblen = 0; /* Fill pointer for the send buffer. */
762 /* Socket used to communicate with the Emacs server process. */
763 HSOCKET emacs_socket = 0;
765 /* On Windows, the socket library was historically separate from the
766 standard C library, so errors are handled differently. */
768 static void
769 sock_err_message (const char *function_name)
771 #ifdef WINDOWSNT
772 char* msg = NULL;
774 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
775 | FORMAT_MESSAGE_ALLOCATE_BUFFER
776 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
777 NULL, WSAGetLastError (), 0, (LPTSTR)&msg, 0, NULL);
779 message (true, "%s: %s: %s\n", progname, function_name, msg);
781 LocalFree (msg);
782 #else
783 message (true, "%s: %s: %s\n", progname, function_name, strerror (errno));
784 #endif
788 /* Let's send the data to Emacs when either
789 - the data ends in "\n", or
790 - the buffer is full (but this shouldn't happen)
791 Otherwise, we just accumulate it. */
792 static void
793 send_to_emacs (HSOCKET s, const char *data)
795 size_t dlen;
797 if (!data)
798 return;
800 dlen = strlen (data);
801 while (*data)
803 size_t part = min (dlen, SEND_BUFFER_SIZE - sblen);
804 memcpy (&send_buffer[sblen], data, part);
805 data += part;
806 sblen += part;
808 if (sblen == SEND_BUFFER_SIZE
809 || (sblen > 0 && send_buffer[sblen-1] == '\n'))
811 int sent = send (s, send_buffer, sblen, 0);
812 if (sent < 0)
814 message (true, "%s: failed to send %d bytes to socket: %s\n",
815 progname, sblen, strerror (errno));
816 fail ();
818 if (sent != sblen)
819 memmove (send_buffer, &send_buffer[sent], sblen - sent);
820 sblen -= sent;
823 dlen -= part;
828 /* In STR, insert a & before each &, each space, each newline, and
829 any initial -. Change spaces to underscores, too, so that the
830 return value never contains a space.
832 Does not change the string. Outputs the result to S. */
833 static void
834 quote_argument (HSOCKET s, const char *str)
836 char *copy = (char *) xmalloc (strlen (str) * 2 + 1);
837 const char *p;
838 char *q;
840 p = str;
841 q = copy;
842 while (*p)
844 if (*p == ' ')
846 *q++ = '&';
847 *q++ = '_';
848 p++;
850 else if (*p == '\n')
852 *q++ = '&';
853 *q++ = 'n';
854 p++;
856 else
858 if (*p == '&' || (*p == '-' && p == str))
859 *q++ = '&';
860 *q++ = *p++;
863 *q++ = 0;
865 send_to_emacs (s, copy);
867 free (copy);
871 /* The inverse of quote_argument. Removes quoting in string STR by
872 modifying the string in place. Returns STR. */
874 static char *
875 unquote_argument (char *str)
877 char *p, *q;
879 if (! str)
880 return str;
882 p = str;
883 q = str;
884 while (*p)
886 if (*p == '&')
888 p++;
889 if (*p == '&')
890 *p = '&';
891 else if (*p == '_')
892 *p = ' ';
893 else if (*p == 'n')
894 *p = '\n';
895 else if (*p == '-')
896 *p = '-';
898 *q++ = *p++;
900 *q = 0;
901 return str;
905 static int
906 file_name_absolute_p (const char *filename)
908 /* Sanity check, it shouldn't happen. */
909 if (! filename) return false;
911 /* /xxx is always an absolute path. */
912 if (filename[0] == '/') return true;
914 /* Empty filenames (which shouldn't happen) are relative. */
915 if (filename[0] == '\0') return false;
917 #ifdef WINDOWSNT
918 /* X:\xxx is always absolute. */
919 if (isalpha ((unsigned char) filename[0])
920 && filename[1] == ':' && (filename[2] == '\\' || filename[2] == '/'))
921 return true;
923 /* Both \xxx and \\xxx\yyy are absolute. */
924 if (filename[0] == '\\') return true;
925 #endif
927 return false;
930 #ifdef WINDOWSNT
931 /* Wrapper to make WSACleanup a cdecl, as required by atexit. */
932 void __cdecl close_winsock (void);
933 void __cdecl
934 close_winsock (void)
936 WSACleanup ();
939 /* Initialize the WinSock2 library. */
940 void initialize_sockets (void);
941 void
942 initialize_sockets (void)
944 WSADATA wsaData;
946 if (WSAStartup (MAKEWORD (2, 0), &wsaData))
948 message (true, "%s: error initializing WinSock2\n", progname);
949 exit (EXIT_FAILURE);
952 atexit (close_winsock);
954 #endif /* WINDOWSNT */
957 /* Read the information needed to set up a TCP comm channel with
958 the Emacs server: host, port, and authentication string. */
960 static int
961 get_server_config (const char *config_file, struct sockaddr_in *server,
962 char *authentication)
964 char dotted[32];
965 char *port;
966 FILE *config = NULL;
968 if (file_name_absolute_p (config_file))
969 config = fopen (config_file, "rb");
970 else
972 const char *home = egetenv ("HOME");
974 if (home)
976 char *path = xmalloc (strlen (home) + strlen (config_file)
977 + EXTRA_SPACE);
978 char *z = stpcpy (path, home);
979 z = stpcpy (z, "/.emacs.d/server/");
980 strcpy (z, config_file);
981 config = fopen (path, "rb");
982 free (path);
984 #ifdef WINDOWSNT
985 if (!config && (home = egetenv ("APPDATA")))
987 char *path = xmalloc (strlen (home) + strlen (config_file)
988 + EXTRA_SPACE);
989 char *z = stpcpy (path, home);
990 z = stpcpy (z, "/.emacs.d/server/");
991 strcpy (z, config_file);
992 config = fopen (path, "rb");
993 free (path);
995 #endif
998 if (! config)
999 return false;
1001 if (fgets (dotted, sizeof dotted, config)
1002 && (port = strchr (dotted, ':')))
1003 *port++ = '\0';
1004 else
1006 message (true, "%s: invalid configuration info\n", progname);
1007 exit (EXIT_FAILURE);
1010 server->sin_family = AF_INET;
1011 server->sin_addr.s_addr = inet_addr (dotted);
1012 server->sin_port = htons (atoi (port));
1014 if (! fread (authentication, AUTH_KEY_LENGTH, 1, config))
1016 message (true, "%s: cannot read authentication info\n", progname);
1017 exit (EXIT_FAILURE);
1020 fclose (config);
1022 return true;
1025 static HSOCKET
1026 set_tcp_socket (const char *local_server_file)
1028 HSOCKET s;
1029 struct sockaddr_in server;
1030 struct linger l_arg = {1, 1};
1031 char auth_string[AUTH_KEY_LENGTH + 1];
1033 if (! get_server_config (local_server_file, &server, auth_string))
1034 return INVALID_SOCKET;
1036 if (server.sin_addr.s_addr != inet_addr ("127.0.0.1") && !quiet)
1037 message (false, "%s: connected to remote socket at %s\n",
1038 progname, inet_ntoa (server.sin_addr));
1040 /* Open up an AF_INET socket. */
1041 if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
1043 /* Since we have an alternate to try out, this is not an error
1044 yet; popping out a modal dialog at this stage would make -a
1045 option totally useless for emacsclientw -- the user will
1046 still get an error message if the alternate editor fails. */
1047 #ifdef WINDOWSNT
1048 if(!(w32_window_app () && alternate_editor))
1049 #endif
1050 sock_err_message ("socket");
1051 return INVALID_SOCKET;
1054 /* Set up the socket. */
1055 if (connect (s, (struct sockaddr *) &server, sizeof server) < 0)
1057 #ifdef WINDOWSNT
1058 if(!(w32_window_app () && alternate_editor))
1059 #endif
1060 sock_err_message ("connect");
1061 return INVALID_SOCKET;
1064 setsockopt (s, SOL_SOCKET, SO_LINGER, (char *) &l_arg, sizeof l_arg);
1066 /* Send the authentication. */
1067 auth_string[AUTH_KEY_LENGTH] = '\0';
1069 send_to_emacs (s, "-auth ");
1070 send_to_emacs (s, auth_string);
1071 send_to_emacs (s, " ");
1073 return s;
1077 /* Returns 1 if PREFIX is a prefix of STRING. */
1078 static int
1079 strprefix (const char *prefix, const char *string)
1081 return !strncmp (prefix, string, strlen (prefix));
1084 /* Get tty name and type. If successful, return the type in TTY_TYPE
1085 and the name in TTY_NAME, and return 1. Otherwise, fail if NOABORT
1086 is zero, or return 0 if NOABORT is non-zero. */
1088 static int
1089 find_tty (const char **tty_type, const char **tty_name, int noabort)
1091 const char *type = egetenv ("TERM");
1092 const char *name = ttyname (fileno (stdout));
1094 if (!name)
1096 if (noabort)
1097 return 0;
1098 else
1100 message (true, "%s: could not get terminal name\n", progname);
1101 fail ();
1105 if (!type)
1107 if (noabort)
1108 return 0;
1109 else
1111 message (true, "%s: please set the TERM variable to your terminal type\n",
1112 progname);
1113 fail ();
1117 if (strcmp (type, "eterm") == 0)
1119 if (noabort)
1120 return 0;
1121 else
1123 /* This causes nasty, MULTI_KBOARD-related input lockouts. */
1124 message (true, "%s: opening a frame in an Emacs term buffer"
1125 " is not supported\n", progname);
1126 fail ();
1130 *tty_name = name;
1131 *tty_type = type;
1132 return 1;
1136 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1138 /* Three possibilities:
1139 2 - can't be `stat'ed (sets errno)
1140 1 - isn't owned by us
1141 0 - success: none of the above */
1143 static int
1144 socket_status (const char *name)
1146 struct stat statbfr;
1148 if (stat (name, &statbfr) == -1)
1149 return 2;
1151 if (statbfr.st_uid != geteuid ())
1152 return 1;
1154 return 0;
1158 /* A signal handler that passes the signal to the Emacs process.
1159 Useful for SIGWINCH. */
1161 static void
1162 pass_signal_to_emacs (int signalnum)
1164 int old_errno = errno;
1166 if (emacs_pid)
1167 kill (emacs_pid, signalnum);
1169 signal (signalnum, pass_signal_to_emacs);
1170 errno = old_errno;
1173 /* Signal handler for SIGCONT; notify the Emacs process that it can
1174 now resume our tty frame. */
1176 static void
1177 handle_sigcont (int signalnum)
1179 int old_errno = errno;
1180 pid_t pgrp = getpgrp ();
1181 pid_t tcpgrp = tcgetpgrp (1);
1183 if (tcpgrp == pgrp)
1185 /* We are in the foreground. */
1186 send_to_emacs (emacs_socket, "-resume \n");
1188 else if (0 <= tcpgrp && tty)
1190 /* We are in the background; cancel the continue. */
1191 kill (-pgrp, SIGTTIN);
1194 signal (signalnum, handle_sigcont);
1195 errno = old_errno;
1198 /* Signal handler for SIGTSTP; notify the Emacs process that we are
1199 going to sleep. Normally the suspend is initiated by Emacs via
1200 server-handle-suspend-tty, but if the server gets out of sync with
1201 reality, we may get a SIGTSTP on C-z. Handling this signal and
1202 notifying Emacs about it should get things under control again. */
1204 static void
1205 handle_sigtstp (int signalnum)
1207 int old_errno = errno;
1208 sigset_t set;
1210 if (emacs_socket)
1211 send_to_emacs (emacs_socket, "-suspend \n");
1213 /* Unblock this signal and call the default handler by temporarily
1214 changing the handler and resignaling. */
1215 sigprocmask (SIG_BLOCK, NULL, &set);
1216 sigdelset (&set, signalnum);
1217 signal (signalnum, SIG_DFL);
1218 raise (signalnum);
1219 sigprocmask (SIG_SETMASK, &set, NULL); /* Let's the above signal through. */
1220 signal (signalnum, handle_sigtstp);
1222 errno = old_errno;
1226 /* Set up signal handlers before opening a frame on the current tty. */
1228 static void
1229 init_signals (void)
1231 /* Set up signal handlers. */
1232 signal (SIGWINCH, pass_signal_to_emacs);
1234 /* Don't pass SIGINT and SIGQUIT to Emacs, because it has no way of
1235 deciding which terminal the signal came from. C-g is now a
1236 normal input event on secondary terminals. */
1237 #if 0
1238 signal (SIGINT, pass_signal_to_emacs);
1239 signal (SIGQUIT, pass_signal_to_emacs);
1240 #endif
1242 signal (SIGCONT, handle_sigcont);
1243 signal (SIGTSTP, handle_sigtstp);
1244 signal (SIGTTOU, handle_sigtstp);
1248 static HSOCKET
1249 set_local_socket (const char *local_socket_name)
1251 HSOCKET s;
1252 struct sockaddr_un server;
1254 /* Open up an AF_UNIX socket in this person's home directory. */
1255 if ((s = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
1257 message (true, "%s: socket: %s\n", progname, strerror (errno));
1258 return INVALID_SOCKET;
1261 server.sun_family = AF_UNIX;
1264 int sock_status;
1265 int saved_errno;
1266 const char *server_name = local_socket_name;
1267 const char *tmpdir = NULL;
1268 char *tmpdir_storage = NULL;
1269 char *socket_name_storage = NULL;
1271 if (!strchr (local_socket_name, '/') && !strchr (local_socket_name, '\\'))
1273 /* socket_name is a file name component. */
1274 long uid = geteuid ();
1275 tmpdir = egetenv ("TMPDIR");
1276 if (!tmpdir)
1278 #ifdef DARWIN_OS
1279 #ifndef _CS_DARWIN_USER_TEMP_DIR
1280 #define _CS_DARWIN_USER_TEMP_DIR 65537
1281 #endif
1282 size_t n = confstr (_CS_DARWIN_USER_TEMP_DIR, NULL, (size_t) 0);
1283 if (n > 0)
1285 tmpdir = tmpdir_storage = xmalloc (n);
1286 confstr (_CS_DARWIN_USER_TEMP_DIR, tmpdir_storage, n);
1288 else
1289 #endif
1290 tmpdir = "/tmp";
1292 socket_name_storage =
1293 xmalloc (strlen (tmpdir) + strlen (server_name) + EXTRA_SPACE);
1294 char *z = stpcpy (socket_name_storage, tmpdir);
1295 z += sprintf (z, "/emacs%ld/", uid);
1296 strcpy (z, server_name);
1297 local_socket_name = socket_name_storage;
1300 if (strlen (local_socket_name) < sizeof (server.sun_path))
1301 strcpy (server.sun_path, local_socket_name);
1302 else
1304 message (true, "%s: socket-name %s too long\n",
1305 progname, local_socket_name);
1306 fail ();
1309 /* See if the socket exists, and if it's owned by us. */
1310 sock_status = socket_status (server.sun_path);
1311 saved_errno = errno;
1312 if (sock_status && tmpdir)
1314 /* Failing that, see if LOGNAME or USER exist and differ from
1315 our euid. If so, look for a socket based on the UID
1316 associated with the name. This is reminiscent of the logic
1317 that init_editfns uses to set the global Vuser_full_name. */
1319 const char *user_name = egetenv ("LOGNAME");
1321 if (!user_name)
1322 user_name = egetenv ("USER");
1324 if (user_name)
1326 struct passwd *pw = getpwnam (user_name);
1328 if (pw && (pw->pw_uid != geteuid ()))
1330 /* We're running under su, apparently. */
1331 long uid = pw->pw_uid;
1332 char *user_socket_name
1333 = xmalloc (strlen (tmpdir) + strlen (server_name)
1334 + EXTRA_SPACE);
1335 char *z = stpcpy (user_socket_name, tmpdir);
1336 z += sprintf (z, "/emacs%ld/", uid);
1337 strcpy (z, server_name);
1339 if (strlen (user_socket_name) < sizeof (server.sun_path))
1340 strcpy (server.sun_path, user_socket_name);
1341 else
1343 message (true, "%s: socket-name %s too long\n",
1344 progname, user_socket_name);
1345 exit (EXIT_FAILURE);
1347 free (user_socket_name);
1349 sock_status = socket_status (server.sun_path);
1350 saved_errno = errno;
1352 else
1353 errno = saved_errno;
1357 free (socket_name_storage);
1358 free (tmpdir_storage);
1360 switch (sock_status)
1362 case 1:
1363 /* There's a socket, but it isn't owned by us. This is OK if
1364 we are root. */
1365 if (0 != geteuid ())
1367 message (true, "%s: Invalid socket owner\n", progname);
1368 return INVALID_SOCKET;
1370 break;
1372 case 2:
1373 /* `stat' failed */
1374 if (saved_errno == ENOENT)
1375 message (true,
1376 "%s: can't find socket; have you started the server?\n\
1377 To start the server in Emacs, type \"M-x server-start\".\n",
1378 progname);
1379 else
1380 message (true, "%s: can't stat %s: %s\n",
1381 progname, server.sun_path, strerror (saved_errno));
1382 return INVALID_SOCKET;
1386 if (connect (s, (struct sockaddr *) &server, strlen (server.sun_path) + 2)
1387 < 0)
1389 message (true, "%s: connect: %s\n", progname, strerror (errno));
1390 return INVALID_SOCKET;
1393 return s;
1395 #endif /* ! NO_SOCKETS_IN_FILE_SYSTEM */
1397 static HSOCKET
1398 set_socket (int no_exit_if_error)
1400 HSOCKET s;
1401 const char *local_server_file = server_file;
1403 INITIALIZE ();
1405 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1406 /* Explicit --socket-name argument. */
1407 if (socket_name)
1409 s = set_local_socket (socket_name);
1410 if ((s != INVALID_SOCKET) || no_exit_if_error)
1411 return s;
1412 message (true, "%s: error accessing socket \"%s\"\n",
1413 progname, socket_name);
1414 exit (EXIT_FAILURE);
1416 #endif
1418 /* Explicit --server-file arg or EMACS_SERVER_FILE variable. */
1419 if (!local_server_file)
1420 local_server_file = egetenv ("EMACS_SERVER_FILE");
1422 if (local_server_file)
1424 s = set_tcp_socket (local_server_file);
1425 if ((s != INVALID_SOCKET) || no_exit_if_error)
1426 return s;
1428 message (true, "%s: error accessing server file \"%s\"\n",
1429 progname, local_server_file);
1430 exit (EXIT_FAILURE);
1433 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1434 /* Implicit local socket. */
1435 s = set_local_socket ("server");
1436 if (s != INVALID_SOCKET)
1437 return s;
1438 #endif
1440 /* Implicit server file. */
1441 s = set_tcp_socket ("server");
1442 if ((s != INVALID_SOCKET) || no_exit_if_error)
1443 return s;
1445 /* No implicit or explicit socket, and no alternate editor. */
1446 message (true, "%s: No socket or alternate editor. Please use:\n\n"
1447 #ifndef NO_SOCKETS_IN_FILE_SYSTEM
1448 "\t--socket-name\n"
1449 #endif
1450 "\t--server-file (or environment variable EMACS_SERVER_FILE)\n\
1451 \t--alternate-editor (or environment variable ALTERNATE_EDITOR)\n",
1452 progname);
1453 exit (EXIT_FAILURE);
1456 #ifdef HAVE_NTGUI
1457 FARPROC set_fg; /* Pointer to AllowSetForegroundWindow. */
1458 FARPROC get_wc; /* Pointer to RealGetWindowClassA. */
1460 void w32_set_user_model_id (void);
1462 void
1463 w32_set_user_model_id (void)
1465 HMODULE shell;
1466 HRESULT (WINAPI * set_user_model) (const wchar_t * id);
1468 /* On Windows 7 and later, we need to set the user model ID
1469 to associate emacsclient launched files with Emacs frames
1470 in the UI. */
1471 shell = LoadLibrary ("shell32.dll");
1472 if (shell)
1474 set_user_model
1475 = (void *) GetProcAddress (shell,
1476 "SetCurrentProcessExplicitAppUserModelID");
1477 /* If the function is defined, then we are running on Windows 7
1478 or newer, and the UI uses this to group related windows
1479 together. Since emacs, runemacs, emacsclient are related, we
1480 want them grouped even though the executables are different,
1481 so we need to set a consistent ID between them. */
1482 if (set_user_model)
1483 set_user_model (L"GNU.Emacs");
1485 FreeLibrary (shell);
1489 BOOL CALLBACK w32_find_emacs_process (HWND, LPARAM);
1491 BOOL CALLBACK
1492 w32_find_emacs_process (HWND hWnd, LPARAM lParam)
1494 DWORD pid;
1495 char class[6];
1497 /* Reject any window not of class "Emacs". */
1498 if (! get_wc (hWnd, class, sizeof (class))
1499 || strcmp (class, "Emacs"))
1500 return TRUE;
1502 /* We only need the process id, not the thread id. */
1503 (void) GetWindowThreadProcessId (hWnd, &pid);
1505 /* Not the one we're looking for. */
1506 if (pid != (DWORD) emacs_pid) return TRUE;
1508 /* OK, let's raise it. */
1509 set_fg (emacs_pid);
1511 /* Stop enumeration. */
1512 return FALSE;
1515 /* Search for a window of class "Emacs" and owned by a process with
1516 process id = emacs_pid. If found, allow it to grab the focus. */
1517 void w32_give_focus (void);
1519 void
1520 w32_give_focus (void)
1522 HANDLE user32;
1524 /* It shouldn't happen when dealing with TCP sockets. */
1525 if (!emacs_pid) return;
1527 user32 = GetModuleHandle ("user32.dll");
1529 if (!user32)
1530 return;
1532 /* Modern Windows restrict which processes can set the foreground window.
1533 emacsclient can allow Emacs to grab the focus by calling the function
1534 AllowSetForegroundWindow. Unfortunately, older Windows (W95, W98 and
1535 NT) lack this function, so we have to check its availability. */
1536 if ((set_fg = GetProcAddress (user32, "AllowSetForegroundWindow"))
1537 && (get_wc = GetProcAddress (user32, "RealGetWindowClassA")))
1538 EnumWindows (w32_find_emacs_process, (LPARAM) 0);
1540 #endif /* HAVE_NTGUI */
1542 /* Start the emacs daemon and try to connect to it. */
1544 static void
1545 start_daemon_and_retry_set_socket (void)
1547 #ifndef WINDOWSNT
1548 pid_t dpid;
1549 int status;
1551 dpid = fork ();
1553 if (dpid > 0)
1555 pid_t w;
1556 w = waitpid (dpid, &status, WUNTRACED | WCONTINUED);
1558 if ((w == -1) || !WIFEXITED (status) || WEXITSTATUS (status))
1560 message (true, "Error: Could not start the Emacs daemon\n");
1561 exit (EXIT_FAILURE);
1564 /* Try connecting, the daemon should have started by now. */
1565 message (true, "Emacs daemon should have started, trying to connect again\n");
1566 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1568 message (true, "Error: Cannot connect even after starting the Emacs daemon\n");
1569 exit (EXIT_FAILURE);
1572 else if (dpid < 0)
1574 fprintf (stderr, "Error: Cannot fork!\n");
1575 exit (EXIT_FAILURE);
1577 else
1579 char emacs[] = "emacs";
1580 char daemon_option[] = "--daemon";
1581 char *d_argv[3];
1582 d_argv[0] = emacs;
1583 d_argv[1] = daemon_option;
1584 d_argv[2] = 0;
1585 if (socket_name != NULL)
1587 /* Pass --daemon=socket_name as argument. */
1588 const char *deq = "--daemon=";
1589 char *daemon_arg = xmalloc (strlen (deq)
1590 + strlen (socket_name) + 1);
1591 strcpy (stpcpy (daemon_arg, deq), socket_name);
1592 d_argv[1] = daemon_arg;
1594 execvp ("emacs", d_argv);
1595 message (true, "%s: error starting emacs daemon\n", progname);
1597 #else /* WINDOWSNT */
1598 DWORD wait_result;
1599 HANDLE w32_daemon_event;
1600 STARTUPINFO si;
1601 PROCESS_INFORMATION pi;
1603 ZeroMemory (&si, sizeof si);
1604 si.cb = sizeof si;
1605 ZeroMemory (&pi, sizeof pi);
1607 /* We start Emacs in daemon mode, and then wait for it to signal us
1608 it is ready to accept client connections, by asserting an event
1609 whose name is known to the daemon (defined by nt/inc/ms-w32.h). */
1611 if (!CreateProcess (NULL, (LPSTR)"emacs --daemon", NULL, NULL, FALSE,
1612 CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
1614 char* msg = NULL;
1616 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1617 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1618 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1619 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1620 message (true, "%s: error starting emacs daemon (%s)\n", progname, msg);
1621 exit (EXIT_FAILURE);
1624 w32_daemon_event = CreateEvent (NULL, TRUE, FALSE, W32_DAEMON_EVENT);
1625 if (w32_daemon_event == NULL)
1627 message (true, "Couldn't create Windows daemon event");
1628 exit (EXIT_FAILURE);
1630 if ((wait_result = WaitForSingleObject (w32_daemon_event, INFINITE))
1631 != WAIT_OBJECT_0)
1633 const char *msg = NULL;
1635 switch (wait_result)
1637 case WAIT_ABANDONED:
1638 msg = "The daemon exited unexpectedly";
1639 break;
1640 case WAIT_TIMEOUT:
1641 /* Can't happen due to INFINITE. */
1642 default:
1643 case WAIT_FAILED:
1644 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
1645 | FORMAT_MESSAGE_ALLOCATE_BUFFER
1646 | FORMAT_MESSAGE_ARGUMENT_ARRAY,
1647 NULL, GetLastError (), 0, (LPTSTR)&msg, 0, NULL);
1648 break;
1650 message (true, "Error: Could not start the Emacs daemon: %s\n", msg);
1651 exit (EXIT_FAILURE);
1653 CloseHandle (w32_daemon_event);
1655 /* Try connecting, the daemon should have started by now. */
1656 /* It's just a progress message, so don't pop a dialog if this is
1657 emacsclientw. */
1658 if (!w32_window_app ())
1659 message (true,
1660 "Emacs daemon should have started, trying to connect again\n");
1661 if ((emacs_socket = set_socket (1)) == INVALID_SOCKET)
1663 message (true,
1664 "Error: Cannot connect even after starting the Emacs daemon\n");
1665 exit (EXIT_FAILURE);
1667 #endif /* WINDOWSNT */
1671 main (int argc, char **argv)
1673 int rl = 0, needlf = 0;
1674 char *cwd, *str;
1675 char string[BUFSIZ+1];
1676 int start_daemon_if_needed;
1677 int exit_status = EXIT_SUCCESS;
1679 main_argc = argc;
1680 main_argv = argv;
1681 progname = argv[0];
1683 #ifdef HAVE_NTGUI
1684 /* On Windows 7 and later, we need to explicitly associate
1685 emacsclient with emacs so the UI behaves sensibly. This
1686 association does no harm if we're not actually connecting to an
1687 Emacs using a window display. */
1688 w32_set_user_model_id ();
1689 #endif /* HAVE_NTGUI */
1691 /* Process options. */
1692 decode_options (argc, argv);
1694 if ((argc - optind < 1) && !eval && current_frame)
1696 message (true, "%s: file name or argument required\n"
1697 "Try '%s --help' for more information\n",
1698 progname, progname);
1699 exit (EXIT_FAILURE);
1702 #ifndef WINDOWSNT
1703 if (tty)
1705 pid_t pgrp = getpgrp ();
1706 pid_t tcpgrp = tcgetpgrp (1);
1707 if (0 <= tcpgrp && tcpgrp != pgrp)
1708 kill (-pgrp, SIGTTIN);
1710 #endif /* !WINDOWSNT */
1712 /* If alternate_editor is the empty string, start the emacs daemon
1713 in case of failure to connect. */
1714 start_daemon_if_needed = (alternate_editor
1715 && (alternate_editor[0] == '\0'));
1717 emacs_socket = set_socket (alternate_editor || start_daemon_if_needed);
1718 if (emacs_socket == INVALID_SOCKET)
1720 if (! start_daemon_if_needed)
1721 fail ();
1723 start_daemon_and_retry_set_socket ();
1726 cwd = get_current_dir_name ();
1727 if (cwd == 0)
1729 message (true, "%s: %s\n", progname,
1730 "Cannot get current working directory");
1731 fail ();
1734 #ifdef HAVE_NTGUI
1735 if (display && !strcmp (display, "w32"))
1736 w32_give_focus ();
1737 #endif /* HAVE_NTGUI */
1739 /* Send over our environment and current directory. */
1740 if (!current_frame)
1742 int i;
1743 for (i = 0; environ[i]; i++)
1745 send_to_emacs (emacs_socket, "-env ");
1746 quote_argument (emacs_socket, environ[i]);
1747 send_to_emacs (emacs_socket, " ");
1750 send_to_emacs (emacs_socket, "-dir ");
1751 if (tramp_prefix)
1752 quote_argument (emacs_socket, tramp_prefix);
1753 quote_argument (emacs_socket, cwd);
1754 free (cwd);
1755 send_to_emacs (emacs_socket, "/");
1756 send_to_emacs (emacs_socket, " ");
1758 retry:
1759 if (nowait)
1760 send_to_emacs (emacs_socket, "-nowait ");
1762 if (current_frame)
1763 send_to_emacs (emacs_socket, "-current-frame ");
1765 if (display)
1767 send_to_emacs (emacs_socket, "-display ");
1768 quote_argument (emacs_socket, display);
1769 send_to_emacs (emacs_socket, " ");
1772 if (parent_id)
1774 send_to_emacs (emacs_socket, "-parent-id ");
1775 quote_argument (emacs_socket, parent_id);
1776 send_to_emacs (emacs_socket, " ");
1779 if (frame_parameters && !current_frame)
1781 send_to_emacs (emacs_socket, "-frame-parameters ");
1782 quote_argument (emacs_socket, frame_parameters);
1783 send_to_emacs (emacs_socket, " ");
1786 /* Unless we are certain we don't want to occupy the tty, send our
1787 tty information to Emacs. For example, in daemon mode Emacs may
1788 need to occupy this tty if no other frame is available. */
1789 if (!current_frame || !eval)
1791 const char *tty_type, *tty_name;
1793 if (find_tty (&tty_type, &tty_name, !tty))
1795 #if !defined (NO_SOCKETS_IN_FILE_SYSTEM)
1796 init_signals ();
1797 #endif
1798 send_to_emacs (emacs_socket, "-tty ");
1799 quote_argument (emacs_socket, tty_name);
1800 send_to_emacs (emacs_socket, " ");
1801 quote_argument (emacs_socket, tty_type);
1802 send_to_emacs (emacs_socket, " ");
1806 if (!current_frame && !tty)
1807 send_to_emacs (emacs_socket, "-window-system ");
1809 if ((argc - optind > 0))
1811 int i;
1812 for (i = optind; i < argc; i++)
1815 if (eval)
1817 /* Don't prepend cwd or anything like that. */
1818 send_to_emacs (emacs_socket, "-eval ");
1819 quote_argument (emacs_socket, argv[i]);
1820 send_to_emacs (emacs_socket, " ");
1821 continue;
1824 if (*argv[i] == '+')
1826 char *p = argv[i] + 1;
1827 while (isdigit ((unsigned char) *p) || *p == ':') p++;
1828 if (*p == 0)
1830 send_to_emacs (emacs_socket, "-position ");
1831 quote_argument (emacs_socket, argv[i]);
1832 send_to_emacs (emacs_socket, " ");
1833 continue;
1836 #ifdef WINDOWSNT
1837 else if (! file_name_absolute_p (argv[i])
1838 && (isalpha (argv[i][0]) && argv[i][1] == ':'))
1839 /* Windows can have a different default directory for each
1840 drive, so the cwd passed via "-dir" is not sufficient
1841 to account for that.
1842 If the user uses <drive>:<relpath>, we hence need to be
1843 careful to expand <relpath> with the default directory
1844 corresponding to <drive>. */
1846 char *filename = (char *) xmalloc (MAX_PATH);
1847 DWORD size;
1849 size = GetFullPathName (argv[i], MAX_PATH, filename, NULL);
1850 if (size > 0 && size < MAX_PATH)
1851 argv[i] = filename;
1852 else
1853 free (filename);
1855 #endif
1857 send_to_emacs (emacs_socket, "-file ");
1858 if (tramp_prefix && file_name_absolute_p (argv[i]))
1859 quote_argument (emacs_socket, tramp_prefix);
1860 quote_argument (emacs_socket, argv[i]);
1861 send_to_emacs (emacs_socket, " ");
1864 else if (eval)
1866 /* Read expressions interactively. */
1867 while ((str = fgets (string, BUFSIZ, stdin)))
1869 send_to_emacs (emacs_socket, "-eval ");
1870 quote_argument (emacs_socket, str);
1872 send_to_emacs (emacs_socket, " ");
1875 send_to_emacs (emacs_socket, "\n");
1877 /* Wait for an answer. */
1878 if (!eval && !tty && !nowait && !quiet)
1880 printf ("Waiting for Emacs...");
1881 needlf = 2;
1883 fflush (stdout);
1884 while (fdatasync (1) != 0 && errno == EINTR)
1885 continue;
1887 /* Now, wait for an answer and print any messages. */
1888 while (exit_status == EXIT_SUCCESS)
1890 char *p, *end_p;
1893 errno = 0;
1894 rl = recv (emacs_socket, string, BUFSIZ, 0);
1896 /* If we receive a signal (e.g. SIGWINCH, which we pass
1897 through to Emacs), on some OSes we get EINTR and must retry. */
1898 while (rl < 0 && errno == EINTR);
1900 if (rl <= 0)
1901 break;
1903 string[rl] = '\0';
1905 /* Loop over all NL-terminated messages. */
1906 for (end_p = p = string; end_p != NULL && *end_p != '\0'; p = end_p)
1908 end_p = strchr (p, '\n');
1909 if (end_p != NULL)
1910 *end_p++ = '\0';
1912 if (strprefix ("-emacs-pid ", p))
1914 /* -emacs-pid PID: The process id of the Emacs process. */
1915 emacs_pid = strtol (p + strlen ("-emacs-pid"), NULL, 10);
1917 else if (strprefix ("-window-system-unsupported ", p))
1919 /* -window-system-unsupported: Emacs was compiled without support
1920 for whatever window system we tried. Try the alternate
1921 display, or, failing that, try the terminal. */
1922 if (alt_display)
1924 display = alt_display;
1925 alt_display = NULL;
1927 else
1929 nowait = 0;
1930 tty = 1;
1933 goto retry;
1935 else if (strprefix ("-print ", p))
1937 /* -print STRING: Print STRING on the terminal. */
1938 if (!suppress_output)
1940 str = unquote_argument (p + strlen ("-print "));
1941 if (needlf)
1942 printf ("\n");
1943 printf ("%s", str);
1944 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1947 else if (strprefix ("-print-nonl ", p))
1949 /* -print-nonl STRING: Print STRING on the terminal.
1950 Used to continue a preceding -print command. */
1951 if (!suppress_output)
1953 str = unquote_argument (p + strlen ("-print-nonl "));
1954 printf ("%s", str);
1955 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1958 else if (strprefix ("-error ", p))
1960 /* -error DESCRIPTION: Signal an error on the terminal. */
1961 str = unquote_argument (p + strlen ("-error "));
1962 if (needlf)
1963 printf ("\n");
1964 fprintf (stderr, "*ERROR*: %s", str);
1965 needlf = str[0] == '\0' ? needlf : str[strlen (str) - 1] != '\n';
1966 exit_status = EXIT_FAILURE;
1968 #ifdef SIGSTOP
1969 else if (strprefix ("-suspend ", p))
1971 /* -suspend: Suspend this terminal, i.e., stop the process. */
1972 if (needlf)
1973 printf ("\n");
1974 needlf = 0;
1975 kill (0, SIGSTOP);
1977 #endif
1978 else
1980 /* Unknown command. */
1981 if (needlf)
1982 printf ("\n");
1983 needlf = 0;
1984 printf ("*ERROR*: Unknown message: %s\n", p);
1989 if (needlf)
1990 printf ("\n");
1991 fflush (stdout);
1992 while (fdatasync (1) != 0 && errno == EINTR)
1993 continue;
1995 if (rl < 0)
1996 exit_status = EXIT_FAILURE;
1998 CLOSE_SOCKET (emacs_socket);
1999 return exit_status;
2002 #endif /* HAVE_SOCKETS && HAVE_INET_SOCKETS */