* lisp/vc/vc/git.el: Fix previous.
[emacs/old-mirror.git] / src / emacs.c
blob62f03c6ea12fa04f46023ef955eba3ff430b0488
1 /* Fully extensible Emacs, running on Unix, intended for GNU.
3 Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2014
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #define INLINE EXTERN_INLINE
22 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
27 #include <sys/types.h>
28 #include <sys/file.h>
29 #include <unistd.h>
31 #include <close-stream.h>
33 #define MAIN_PROGRAM
34 #include "lisp.h"
36 #ifdef WINDOWSNT
37 #include <fcntl.h>
38 #include <sys/socket.h>
39 #include <mbstring.h>
40 #include "w32.h"
41 #include "w32heap.h"
42 #endif
44 #if defined WINDOWSNT || defined HAVE_NTGUI
45 #include "w32select.h"
46 #include "w32font.h"
47 #include "w32common.h"
48 #endif
50 #if defined CYGWIN
51 #include "cygw32.h"
52 #endif
54 #ifdef MSDOS
55 #include <binary-io.h>
56 #endif
58 #ifdef HAVE_WINDOW_SYSTEM
59 #include TERM_HEADER
60 #endif /* HAVE_WINDOW_SYSTEM */
62 #ifdef NS_IMPL_GNUSTEP
63 /* At least under Debian, GSConfig is in a subdirectory. --Stef */
64 #include <GNUstepBase/GSConfig.h>
65 #endif
67 #include "commands.h"
68 #include "intervals.h"
69 #include "character.h"
70 #include "buffer.h"
71 #include "window.h"
73 #include "systty.h"
74 #include "atimer.h"
75 #include "blockinput.h"
76 #include "syssignal.h"
77 #include "process.h"
78 #include "frame.h"
79 #include "termhooks.h"
80 #include "keyboard.h"
81 #include "keymap.h"
82 #include "category.h"
83 #include "charset.h"
84 #include "composite.h"
85 #include "dispextern.h"
86 #include "regex.h"
87 #include "syntax.h"
88 #include "sysselect.h"
89 #include "systime.h"
91 #ifdef HAVE_GNUTLS
92 #include "gnutls.h"
93 #endif
95 #if (defined PROFILING \
96 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__))
97 # include <sys/gmon.h>
98 extern void moncontrol (int mode);
99 #endif
101 #ifdef HAVE_SETLOCALE
102 #include <locale.h>
103 #endif
105 #ifdef HAVE_SETRLIMIT
106 #include <sys/time.h>
107 #include <sys/resource.h>
108 #endif
110 #ifdef HAVE_PERSONALITY_LINUX32
111 #include <sys/personality.h>
112 #endif
114 static const char emacs_version[] = PACKAGE_VERSION;
115 static const char emacs_copyright[] = COPYRIGHT;
116 static const char emacs_bugreport[] = PACKAGE_BUGREPORT;
118 /* Empty lisp strings. To avoid having to build any others. */
119 Lisp_Object empty_unibyte_string, empty_multibyte_string;
121 #ifdef WINDOWSNT
122 /* Cache for externally loaded libraries. */
123 Lisp_Object Vlibrary_cache;
124 #endif
126 /* Set after Emacs has started up the first time.
127 Prevents reinitialization of the Lisp world and keymaps
128 on subsequent starts. */
129 bool initialized;
131 /* Set to true if this instance of Emacs might dump. */
132 bool might_dump;
134 #ifdef DARWIN_OS
135 extern void unexec_init_emacs_zone (void);
136 #endif
138 #ifdef DOUG_LEA_MALLOC
139 /* Preserves a pointer to the memory allocated that copies that
140 static data inside glibc's malloc. */
141 static void *malloc_state_ptr;
142 /* From glibc, a routine that returns a copy of the malloc internal state. */
143 extern void *malloc_get_state (void);
144 /* From glibc, a routine that overwrites the malloc internal state. */
145 extern int malloc_set_state (void *);
146 /* True if the MALLOC_CHECK_ environment variable was set while
147 dumping. Used to work around a bug in glibc's malloc. */
148 static bool malloc_using_checking;
149 #elif defined HAVE_PTHREAD && !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
150 extern void malloc_enable_thread (void);
151 #endif
153 Lisp_Object Qfile_name_handler_alist;
155 Lisp_Object Qrisky_local_variable;
157 Lisp_Object Qkill_emacs;
158 static Lisp_Object Qkill_emacs_hook;
160 /* If true, Emacs should not attempt to use a window-specific code,
161 but instead should use the virtual terminal under which it was started. */
162 bool inhibit_window_system;
164 /* If true, a filter or a sentinel is running. Tested to save the match
165 data on the first attempt to change it inside asynchronous code. */
166 bool running_asynch_code;
168 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
169 /* If true, -d was specified, meaning we're using some window system. */
170 bool display_arg;
171 #endif
173 /* An address near the bottom of the stack.
174 Tells GC how to save a copy of the stack. */
175 char *stack_bottom;
177 #if defined (DOUG_LEA_MALLOC) || defined (GNU_LINUX)
178 /* The address where the heap starts (from the first sbrk (0) call). */
179 static void *my_heap_start;
180 #endif
182 #ifdef GNU_LINUX
183 /* The gap between BSS end and heap start as far as we can tell. */
184 static uprintmax_t heap_bss_diff;
185 #endif
187 /* To run as a daemon under Cocoa or Windows, we must do a fork+exec,
188 not a simple fork.
190 On Cocoa, CoreFoundation lib fails in forked process:
191 http://developer.apple.com/ReleaseNotes/
192 CoreFoundation/CoreFoundation.html)
194 On Windows, a Cygwin fork child cannot access the USER subsystem.
196 We mark being in the exec'd process by a daemon name argument of
197 form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
198 NAME is the original daemon name, if any. */
199 #if defined NS_IMPL_COCOA || (defined HAVE_NTGUI && defined CYGWIN)
200 # define DAEMON_MUST_EXEC
201 #endif
203 /* True means running Emacs without interactive terminal. */
204 bool noninteractive;
206 /* True means remove site-lisp directories from load-path. */
207 bool no_site_lisp;
209 /* Name for the server started by the daemon.*/
210 static char *daemon_name;
212 /* Pipe used to send exit notification to the daemon parent at
213 startup. */
214 int daemon_pipe[2];
216 /* Save argv and argc. */
217 char **initial_argv;
218 int initial_argc;
220 static void sort_args (int argc, char **argv);
221 static void syms_of_emacs (void);
223 /* C99 needs each string to be at most 4095 characters, and the usage
224 strings below are split to not overflow this limit. */
225 static char const *const usage_message[] =
226 { "\
228 Run Emacs, the extensible, customizable, self-documenting real-time\n\
229 display editor. The recommended way to start Emacs for normal editing\n\
230 is with no options at all.\n\
232 Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
233 read the main documentation for these command-line arguments.\n\
235 Initialization options:\n\
239 --batch do not do interactive display; implies -q\n\
240 --chdir DIR change to directory DIR\n\
241 --daemon start a server in the background\n\
242 --debug-init enable Emacs Lisp debugger for init file\n\
243 --display, -d DISPLAY use X server DISPLAY\n\
246 --no-desktop do not load a saved desktop\n\
247 --no-init-file, -q load neither ~/.emacs nor default.el\n\
248 --no-shared-memory, -nl do not use shared memory\n\
249 --no-site-file do not load site-start.el\n\
250 --no-site-lisp, -nsl do not add site-lisp directories to load-path\n\
251 --no-splash do not display a splash screen on startup\n\
252 --no-window-system, -nw do not communicate with X, ignoring $DISPLAY\n\
255 --quick, -Q equivalent to:\n\
256 -q --no-site-file --no-site-lisp --no-splash\n\
257 --script FILE run FILE as an Emacs Lisp script\n\
258 --terminal, -t DEVICE use DEVICE for terminal I/O\n\
259 --user, -u USER load ~USER/.emacs instead of your own\n\
263 Action options:\n\
265 FILE visit FILE using find-file\n\
266 +LINE go to line LINE in next FILE\n\
267 +LINE:COLUMN go to line LINE, column COLUMN, in next FILE\n\
268 --directory, -L DIR prepend DIR to load-path (with :DIR, append DIR)\n\
269 --eval EXPR evaluate Emacs Lisp expression EXPR\n\
270 --execute EXPR evaluate Emacs Lisp expression EXPR\n\
273 --file FILE visit FILE using find-file\n\
274 --find-file FILE visit FILE using find-file\n\
275 --funcall, -f FUNC call Emacs Lisp function FUNC with no arguments\n\
276 --insert FILE insert contents of FILE into current buffer\n\
277 --kill exit without asking for confirmation\n\
278 --load, -l FILE load Emacs Lisp FILE using the load function\n\
279 --visit FILE visit FILE using find-file\n\
283 Display options:\n\
285 --background-color, -bg COLOR window background color\n\
286 --basic-display, -D disable many display features;\n\
287 used for debugging Emacs\n\
288 --border-color, -bd COLOR main border color\n\
289 --border-width, -bw WIDTH width of main border\n\
292 --color, --color=MODE override color mode for character terminals;\n\
293 MODE defaults to `auto', and\n\
294 can also be `never', `always',\n\
295 or a mode name like `ansi8'\n\
296 --cursor-color, -cr COLOR color of the Emacs cursor indicating point\n\
297 --font, -fn FONT default font; must be fixed-width\n\
298 --foreground-color, -fg COLOR window foreground color\n\
301 --fullheight, -fh make the first frame high as the screen\n\
302 --fullscreen, -fs make the first frame fullscreen\n\
303 --fullwidth, -fw make the first frame wide as the screen\n\
304 --maximized, -mm make the first frame maximized\n\
305 --geometry, -g GEOMETRY window geometry\n\
308 --no-bitmap-icon, -nbi do not use picture of gnu for Emacs icon\n\
309 --iconic start Emacs in iconified state\n\
310 --internal-border, -ib WIDTH width between text and main border\n\
311 --line-spacing, -lsp PIXELS additional space to put between lines\n\
312 --mouse-color, -ms COLOR mouse cursor color in Emacs window\n\
313 --name NAME title for initial Emacs frame\n\
316 --no-blinking-cursor, -nbc disable blinking cursor\n\
317 --reverse-video, -r, -rv switch foreground and background\n\
318 --title, -T TITLE title for initial Emacs frame\n\
319 --vertical-scroll-bars, -vb enable vertical scroll bars\n\
320 --xrm XRESOURCES set additional X resources\n\
321 --parent-id XID set parent window\n\
322 --help display this help and exit\n\
323 --version output version information and exit\n\
327 You can generally also specify long option names with a single -; for\n\
328 example, -batch as well as --batch. You can use any unambiguous\n\
329 abbreviation for a --option.\n\
331 Various environment variables and window system resources also affect\n\
332 the operation of Emacs. See the main documentation.\n\
334 Report bugs to " PACKAGE_BUGREPORT ". First, please see the Bugs\n\
335 section of the Emacs manual or the file BUGS.\n"
339 /* True if handling a fatal error already. */
340 bool fatal_error_in_progress;
342 #ifdef HAVE_NS
343 /* NS autrelease pool, for memory management. */
344 static void *ns_pool;
345 #endif
347 #if !HAVE_SETLOCALE
348 static char *
349 setlocale (int cat, char const *locale)
351 return 0;
353 #endif
356 /* Report a fatal error due to signal SIG, output a backtrace of at
357 most BACKTRACE_LIMIT lines, and exit. */
358 _Noreturn void
359 terminate_due_to_signal (int sig, int backtrace_limit)
361 signal (sig, SIG_DFL);
362 totally_unblock_input ();
364 /* If fatal error occurs in code below, avoid infinite recursion. */
365 if (! fatal_error_in_progress)
367 fatal_error_in_progress = 1;
369 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
370 Fkill_emacs (make_number (sig));
372 shut_down_emacs (sig, Qnil);
373 emacs_backtrace (backtrace_limit);
376 /* Signal the same code; this time it will really be fatal.
377 Since we're in a signal handler, the signal is blocked, so we
378 have to unblock it if we want to really receive it. */
379 #ifndef MSDOS
381 sigset_t unblocked;
382 sigemptyset (&unblocked);
383 sigaddset (&unblocked, sig);
384 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
386 #endif
388 emacs_raise (sig);
390 /* This shouldn't be executed, but it prevents a warning. */
391 exit (1);
394 /* Code for dealing with Lisp access to the Unix command line. */
396 static void
397 init_cmdargs (int argc, char **argv, int skip_args, char *original_pwd)
399 int i;
400 Lisp_Object name, dir, handler;
401 ptrdiff_t count = SPECPDL_INDEX ();
402 Lisp_Object raw_name;
403 AUTO_STRING (slash_colon, "/:");
405 initial_argv = argv;
406 initial_argc = argc;
408 #ifdef WINDOWSNT
409 /* Must use argv[0] converted to UTF-8, as it begets many standard
410 file and directory names. */
412 char argv0[MAX_UTF8_PATH];
414 if (filename_from_ansi (argv[0], argv0) == 0)
415 raw_name = build_unibyte_string (argv0);
416 else
417 raw_name = build_unibyte_string (argv[0]);
419 #else
420 raw_name = build_unibyte_string (argv[0]);
421 #endif
423 /* Add /: to the front of the name
424 if it would otherwise be treated as magic. */
425 handler = Ffind_file_name_handler (raw_name, Qt);
426 if (! NILP (handler))
427 raw_name = concat2 (slash_colon, raw_name);
429 Vinvocation_name = Ffile_name_nondirectory (raw_name);
430 Vinvocation_directory = Ffile_name_directory (raw_name);
432 /* If we got no directory in argv[0], search PATH to find where
433 Emacs actually came from. */
434 if (NILP (Vinvocation_directory))
436 Lisp_Object found;
437 int yes = openp (Vexec_path, Vinvocation_name,
438 Vexec_suffixes, &found, make_number (X_OK), false);
439 if (yes == 1)
441 /* Add /: to the front of the name
442 if it would otherwise be treated as magic. */
443 handler = Ffind_file_name_handler (found, Qt);
444 if (! NILP (handler))
445 found = concat2 (slash_colon, found);
446 Vinvocation_directory = Ffile_name_directory (found);
450 if (!NILP (Vinvocation_directory)
451 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
452 /* Emacs was started with relative path, like ./emacs.
453 Make it absolute. */
455 Lisp_Object odir =
456 original_pwd ? build_unibyte_string (original_pwd) : Qnil;
458 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, odir);
461 Vinstallation_directory = Qnil;
463 if (!NILP (Vinvocation_directory))
465 dir = Vinvocation_directory;
466 #ifdef WINDOWSNT
467 /* If we are running from the build directory, set DIR to the
468 src subdirectory of the Emacs tree, like on Posix
469 platforms. */
470 if (SBYTES (dir) > sizeof ("/i386/") - 1
471 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
472 "/i386/"))
473 dir = Fexpand_file_name (build_string ("../.."), dir);
474 #else /* !WINDOWSNT */
475 #endif
476 name = Fexpand_file_name (Vinvocation_name, dir);
477 while (1)
479 Lisp_Object tem, lib_src_exists;
480 Lisp_Object etc_exists, info_exists;
482 /* See if dir contains subdirs for use by Emacs.
483 Check for the ones that would exist in a build directory,
484 not including lisp and info. */
485 tem = Fexpand_file_name (build_string ("lib-src"), dir);
486 lib_src_exists = Ffile_exists_p (tem);
488 #ifdef MSDOS
489 /* MSDOS installations frequently remove lib-src, but we still
490 must set installation-directory, or else info won't find
491 its files (it uses the value of installation-directory). */
492 tem = Fexpand_file_name (build_string ("info"), dir);
493 info_exists = Ffile_exists_p (tem);
494 #else
495 info_exists = Qnil;
496 #endif
498 if (!NILP (lib_src_exists) || !NILP (info_exists))
500 tem = Fexpand_file_name (build_string ("etc"), dir);
501 etc_exists = Ffile_exists_p (tem);
502 if (!NILP (etc_exists))
504 Vinstallation_directory
505 = Ffile_name_as_directory (dir);
506 break;
510 /* See if dir's parent contains those subdirs. */
511 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
512 lib_src_exists = Ffile_exists_p (tem);
515 #ifdef MSDOS
516 /* See the MSDOS commentary above. */
517 tem = Fexpand_file_name (build_string ("../info"), dir);
518 info_exists = Ffile_exists_p (tem);
519 #else
520 info_exists = Qnil;
521 #endif
523 if (!NILP (lib_src_exists) || !NILP (info_exists))
525 tem = Fexpand_file_name (build_string ("../etc"), dir);
526 etc_exists = Ffile_exists_p (tem);
527 if (!NILP (etc_exists))
529 tem = Fexpand_file_name (build_string (".."), dir);
530 Vinstallation_directory
531 = Ffile_name_as_directory (tem);
532 break;
536 /* If the Emacs executable is actually a link,
537 next try the dir that the link points into. */
538 tem = Ffile_symlink_p (name);
539 if (!NILP (tem))
541 name = Fexpand_file_name (tem, dir);
542 dir = Ffile_name_directory (name);
544 else
545 break;
549 Vcommand_line_args = Qnil;
551 for (i = argc - 1; i >= 0; i--)
553 if (i == 0 || i > skip_args)
554 /* For the moment, we keep arguments as is in unibyte strings.
555 They are decoded in the function command-line after we know
556 locale-coding-system. */
557 Vcommand_line_args
558 = Fcons (build_unibyte_string (argv[i]), Vcommand_line_args);
561 unbind_to (count, Qnil);
564 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
565 doc: /* Return the program name that was used to run Emacs.
566 Any directory names are omitted. */)
567 (void)
569 return Fcopy_sequence (Vinvocation_name);
572 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
573 0, 0, 0,
574 doc: /* Return the directory name in which the Emacs executable was located. */)
575 (void)
577 return Fcopy_sequence (Vinvocation_directory);
581 /* Test whether the next argument in ARGV matches SSTR or a prefix of
582 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
583 (the argument is supposed to have a value) store in *VALPTR either
584 the next argument or the portion of this one after the equal sign.
585 ARGV is read starting at position *SKIPPTR; this index is advanced
586 by the number of arguments used.
588 Too bad we can't just use getopt for all of this, but we don't have
589 enough information to do it right. */
591 static bool
592 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
593 int minlen, char **valptr, int *skipptr)
595 char *p = NULL;
596 ptrdiff_t arglen;
597 char *arg;
599 /* Don't access argv[argc]; give up in advance. */
600 if (argc <= *skipptr + 1)
601 return 0;
603 arg = argv[*skipptr+1];
604 if (arg == NULL)
605 return 0;
606 if (strcmp (arg, sstr) == 0)
608 if (valptr != NULL)
610 *valptr = argv[*skipptr+2];
611 *skipptr += 2;
613 else
614 *skipptr += 1;
615 return 1;
617 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
618 ? p - arg : strlen (arg));
619 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
620 return 0;
621 else if (valptr == NULL)
623 *skipptr += 1;
624 return 1;
626 else if (p != NULL)
628 *valptr = p+1;
629 *skipptr += 1;
630 return 1;
632 else if (argv[*skipptr+2] != NULL)
634 *valptr = argv[*skipptr+2];
635 *skipptr += 2;
636 return 1;
638 else
640 return 0;
644 #ifdef DOUG_LEA_MALLOC
646 /* malloc can be invoked even before main (e.g. by the dynamic
647 linker), so the dumped malloc state must be restored as early as
648 possible using this special hook. */
650 static void
651 malloc_initialize_hook (void)
653 if (initialized)
655 if (!malloc_using_checking)
656 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
657 ignored if the heap to be restored was constructed without
658 malloc checking. Can't use unsetenv, since that calls malloc. */
660 char **p;
662 for (p = environ; p && *p; p++)
663 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
666 *p = p[1];
667 while (*++p);
668 break;
672 malloc_set_state (malloc_state_ptr);
673 #ifndef XMALLOC_OVERRUN_CHECK
674 free (malloc_state_ptr);
675 #endif
677 else
679 if (my_heap_start == 0)
680 my_heap_start = sbrk (0);
681 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
685 void (*__malloc_initialize_hook) (void) EXTERNALLY_VISIBLE = malloc_initialize_hook;
687 #endif /* DOUG_LEA_MALLOC */
689 /* Close standard output and standard error, reporting any write
690 errors as best we can. This is intended for use with atexit. */
691 static void
692 close_output_streams (void)
694 if (close_stream (stdout) != 0)
696 emacs_perror ("Write error to standard output");
697 _exit (EXIT_FAILURE);
700 if (close_stream (stderr) != 0)
701 _exit (EXIT_FAILURE);
704 /* ARGSUSED */
706 main (int argc, char **argv)
708 #if GC_MARK_STACK
709 Lisp_Object dummy;
710 #endif
711 char stack_bottom_variable;
712 bool do_initial_setlocale;
713 bool dumping;
714 int skip_args = 0;
715 #ifdef HAVE_SETRLIMIT
716 struct rlimit rlim;
717 #endif
718 bool no_loadup = 0;
719 char *junk = 0;
720 char *dname_arg = 0;
721 #ifdef DAEMON_MUST_EXEC
722 char dname_arg2[80];
723 #endif
724 char *ch_to_dir = 0;
726 /* If we use --chdir, this records the original directory. */
727 char *original_pwd = 0;
729 #if GC_MARK_STACK
730 stack_base = &dummy;
731 #endif
733 #ifndef CANNOT_DUMP
734 might_dump = !initialized;
735 #endif
737 #ifdef GNU_LINUX
738 if (!initialized)
740 if (my_heap_start == 0)
741 my_heap_start = sbrk (0);
743 heap_bss_diff = (char *)my_heap_start - max (my_endbss, my_endbss_static);
745 #endif
747 #if defined WINDOWSNT || defined HAVE_NTGUI
748 /* Set global variables used to detect Windows version. Do this as
749 early as possible. (unexw32.c calls this function as well, but
750 the additional call here is harmless.) */
751 cache_system_info ();
752 #ifdef WINDOWSNT
753 /* On Windows 9X, we have to load UNICOWS.DLL as early as possible,
754 to have non-stub implementations of APIs we need to convert file
755 names between UTF-8 and the system's ANSI codepage. */
756 maybe_load_unicows_dll ();
757 #endif
758 #endif
760 #ifdef RUN_TIME_REMAP
761 if (initialized)
762 run_time_remap (argv[0]);
763 #endif
765 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
766 #ifdef DARWIN_OS
767 if (!initialized)
768 unexec_init_emacs_zone ();
769 #endif
771 atexit (close_output_streams);
773 sort_args (argc, argv);
774 argc = 0;
775 while (argv[argc]) argc++;
777 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
779 const char *version, *copyright;
780 if (initialized)
782 Lisp_Object tem, tem2;
783 tem = Fsymbol_value (intern_c_string ("emacs-version"));
784 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
785 if (!STRINGP (tem))
787 fprintf (stderr, "Invalid value of `emacs-version'\n");
788 exit (1);
790 if (!STRINGP (tem2))
792 fprintf (stderr, "Invalid value of `emacs-copyright'\n");
793 exit (1);
795 else
797 version = SSDATA (tem);
798 copyright = SSDATA (tem2);
801 else
803 version = emacs_version;
804 copyright = emacs_copyright;
806 printf ("GNU Emacs %s\n", version);
807 printf ("%s\n", copyright);
808 printf ("GNU Emacs comes with ABSOLUTELY NO WARRANTY.\n");
809 printf ("You may redistribute copies of Emacs\n");
810 printf ("under the terms of the GNU General Public License.\n");
811 printf ("For more information about these matters, ");
812 printf ("see the file named COPYING.\n");
813 exit (0);
816 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
818 #ifdef WINDOWSNT
819 /* argv[] array is kept in its original ANSI codepage encoding,
820 we need to convert to UTF-8, for chdir to work. */
821 char newdir[MAX_UTF8_PATH];
823 filename_from_ansi (ch_to_dir, newdir);
824 ch_to_dir = newdir;
825 #endif
826 original_pwd = get_current_dir_name ();
827 if (chdir (ch_to_dir) != 0)
829 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
830 argv[0], ch_to_dir, strerror (errno));
831 exit (1);
835 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
836 || strcmp (argv[argc - 1], "bootstrap") == 0);
838 #ifdef HAVE_PERSONALITY_LINUX32
839 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
841 /* Set this so we only do this once. */
842 xputenv ("EMACS_HEAP_EXEC=true");
844 /* A flag to turn off address randomization which is introduced
845 in linux kernel shipped with fedora core 4 */
846 #define ADD_NO_RANDOMIZE 0x0040000
847 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
848 #undef ADD_NO_RANDOMIZE
850 execvp (argv[0], argv);
852 /* If the exec fails, try to dump anyway. */
853 emacs_perror (argv[0]);
855 #endif /* HAVE_PERSONALITY_LINUX32 */
857 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK)
858 /* Extend the stack space available.
859 Don't do that if dumping, since some systems (e.g. DJGPP)
860 might define a smaller stack limit at that time. */
861 if (1
862 #ifndef CANNOT_DUMP
863 && (!noninteractive || initialized)
864 #endif
865 && !getrlimit (RLIMIT_STACK, &rlim))
867 long newlim;
868 /* Approximate the amount regex.c needs per unit of re_max_failures. */
869 int ratio = 20 * sizeof (char *);
870 /* Then add 33% to cover the size of the smaller stacks that regex.c
871 successively allocates and discards, on its way to the maximum. */
872 ratio += ratio / 3;
873 /* Add in some extra to cover
874 what we're likely to use for other reasons. */
875 newlim = re_max_failures * ratio + 200000;
876 #ifdef __NetBSD__
877 /* NetBSD (at least NetBSD 1.2G and former) has a bug in its
878 stack allocation routine for new process that the allocation
879 fails if stack limit is not on page boundary. So, round up the
880 new limit to page boundary. */
881 newlim = (newlim + getpagesize () - 1) / getpagesize () * getpagesize ();
882 #endif
883 if (newlim > rlim.rlim_max)
885 newlim = rlim.rlim_max;
886 /* Don't let regex.c overflow the stack we have. */
887 re_max_failures = (newlim - 200000) / ratio;
889 if (rlim.rlim_cur < newlim)
890 rlim.rlim_cur = newlim;
892 setrlimit (RLIMIT_STACK, &rlim);
894 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK */
896 /* Record (approximately) where the stack begins. */
897 stack_bottom = &stack_bottom_variable;
899 clearerr (stdin);
901 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
902 /* Arrange to get warning messages as memory fills up. */
903 memory_warnings (0, malloc_warning);
905 /* Call malloc at least once, to run malloc_initialize_hook.
906 Also call realloc and free for consistency. */
907 free (realloc (malloc (4), 4));
909 #endif /* not SYSTEM_MALLOC and not HYBRID_MALLOC */
911 #ifdef MSDOS
912 SET_BINARY (fileno (stdin));
913 fflush (stdout);
914 SET_BINARY (fileno (stdout));
915 #endif /* MSDOS */
917 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
918 The build procedure uses this while dumping, to ensure that the
919 dumped Emacs does not have its system locale tables initialized,
920 as that might cause screwups when the dumped Emacs starts up. */
922 char *lc_all = getenv ("LC_ALL");
923 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
926 /* Set locale now, so that initial error messages are localized properly.
927 fixup_locale must wait until later, since it builds strings. */
928 if (do_initial_setlocale)
929 setlocale (LC_ALL, "");
931 inhibit_window_system = 0;
933 /* Handle the -t switch, which specifies filename to use as terminal. */
934 while (1)
936 char *term;
937 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
939 int result;
940 emacs_close (0);
941 emacs_close (1);
942 result = emacs_open (term, O_RDWR, 0);
943 if (result < 0 || fcntl (0, F_DUPFD_CLOEXEC, 1) < 0)
945 char *errstring = strerror (errno);
946 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
947 exit (1);
949 if (! isatty (0))
951 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
952 exit (1);
954 fprintf (stderr, "Using %s\n", term);
955 #ifdef HAVE_WINDOW_SYSTEM
956 inhibit_window_system = 1; /* -t => -nw */
957 #endif
959 else
960 break;
963 /* Command line option --no-windows is deprecated and thus not mentioned
964 in the manual and usage information. */
965 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
966 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
967 inhibit_window_system = 1;
969 /* Handle the -batch switch, which means don't do interactive display. */
970 noninteractive = 0;
971 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
973 noninteractive = 1;
974 Vundo_outer_limit = Qnil;
976 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
978 noninteractive = 1; /* Set batch mode. */
979 /* Convert --script to -scriptload, un-skip it, and sort again
980 so that it will be handled in proper sequence. */
981 /* FIXME broken for --script=FILE - is that supposed to work? */
982 argv[skip_args - 1] = (char *) "-scriptload";
983 skip_args -= 2;
984 sort_args (argc, argv);
987 /* Handle the --help option, which gives a usage message. */
988 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
990 int i;
991 printf ("Usage: %s [OPTION-OR-FILENAME]...\n", argv[0]);
992 for (i = 0; i < ARRAYELTS (usage_message); i++)
993 fputs (usage_message[i], stdout);
994 exit (0);
997 /* Make sure IS_DAEMON starts up as false. */
998 daemon_pipe[1] = 0;
1000 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
1001 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
1003 #ifndef DOS_NT
1004 pid_t f;
1006 /* Start as a daemon: fork a new child process which will run the
1007 rest of the initialization code, then exit.
1009 Detaching a daemon requires the following steps:
1010 - fork
1011 - setsid
1012 - exit the parent
1013 - close the tty file-descriptors
1015 We only want to do the last 2 steps once the daemon is ready to
1016 serve requests, i.e. after loading .emacs (initialization).
1017 OTOH initialization may start subprocesses (e.g. ispell) and these
1018 should be run from the proper process (the one that will end up
1019 running as daemon) and with the proper "session id" in order for
1020 them to keep working after detaching, so fork and setsid need to be
1021 performed before initialization.
1023 We want to avoid exiting before the server socket is ready, so
1024 use a pipe for synchronization. The parent waits for the child
1025 to close its end of the pipe (using `daemon-initialized')
1026 before exiting. */
1027 if (emacs_pipe (daemon_pipe) != 0)
1029 fprintf (stderr, "Cannot pipe!\n");
1030 exit (1);
1033 #ifndef DAEMON_MUST_EXEC
1034 #ifdef USE_GTK
1035 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
1036 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
1037 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
1038 #endif /* USE_GTK */
1039 f = fork ();
1040 #else /* DAEMON_MUST_EXEC */
1041 if (!dname_arg || !strchr (dname_arg, '\n'))
1042 f = fork (); /* in orig */
1043 else
1044 f = 0; /* in exec'd */
1045 #endif /* !DAEMON_MUST_EXEC */
1046 if (f > 0)
1048 int retval;
1049 char buf[1];
1051 /* Close unused writing end of the pipe. */
1052 emacs_close (daemon_pipe[1]);
1054 /* Just wait for the child to close its end of the pipe. */
1057 retval = read (daemon_pipe[0], &buf, 1);
1059 while (retval == -1 && errno == EINTR);
1061 if (retval < 0)
1063 fprintf (stderr, "Error reading status from child\n");
1064 exit (1);
1066 else if (retval == 0)
1068 fprintf (stderr, "Error: server did not start correctly\n");
1069 exit (1);
1072 emacs_close (daemon_pipe[0]);
1073 exit (0);
1075 if (f < 0)
1077 emacs_perror ("fork");
1078 exit (EXIT_CANCELED);
1081 #ifdef DAEMON_MUST_EXEC
1083 /* In orig process, forked as child, OR in exec'd. */
1084 if (!dname_arg || !strchr (dname_arg, '\n'))
1085 { /* In orig, child: now exec w/special daemon name. */
1086 char fdStr[80];
1087 int fdStrlen =
1088 snprintf (fdStr, sizeof fdStr,
1089 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1090 daemon_pipe[1], dname_arg ? dname_arg : "");
1092 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1094 fprintf (stderr, "daemon: child name too long\n");
1095 exit (EXIT_CANNOT_INVOKE);
1098 argv[skip_args] = fdStr;
1100 fcntl (daemon_pipe[0], F_SETFD, 0);
1101 fcntl (daemon_pipe[1], F_SETFD, 0);
1102 execvp (argv[0], argv);
1103 emacs_perror (argv[0]);
1104 exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1107 /* In exec'd: parse special dname into pipe and name info. */
1108 if (!dname_arg || !strchr (dname_arg, '\n')
1109 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1111 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1112 exit (EXIT_CANNOT_INVOKE);
1114 dname_arg2[0] = '\0';
1115 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1116 dname_arg2);
1117 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1118 fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
1120 #endif /* DAEMON_MUST_EXEC */
1122 if (dname_arg)
1123 daemon_name = xstrdup (dname_arg);
1124 /* Close unused reading end of the pipe. */
1125 emacs_close (daemon_pipe[0]);
1127 setsid ();
1128 #else /* DOS_NT */
1129 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1130 exit (1);
1131 #endif /* DOS_NT */
1134 #if defined HAVE_PTHREAD && !defined SYSTEM_MALLOC \
1135 && !defined DOUG_LEA_MALLOC && !defined HYBRID_MALLOC
1136 # ifndef CANNOT_DUMP
1137 /* Do not make gmalloc thread-safe when creating bootstrap-emacs, as
1138 that causes an infinite recursive loop with FreeBSD. See
1139 Bug#14569. The part of this bug involving Cygwin is no longer
1140 relevant, now that Cygwin defines HYBRID_MALLOC. */
1141 if (!noninteractive || initialized)
1142 # endif
1143 malloc_enable_thread ();
1144 #endif
1146 init_signals (dumping);
1148 noninteractive1 = noninteractive;
1150 /* Perform basic initializations (not merely interning symbols). */
1152 if (!initialized)
1154 init_alloc_once ();
1155 init_obarray ();
1156 init_eval_once ();
1157 init_charset_once ();
1158 init_coding_once ();
1159 init_syntax_once (); /* Create standard syntax table. */
1160 init_category_once (); /* Create standard category table. */
1161 init_casetab_once (); /* Must be done before init_buffer_once. */
1162 init_buffer_once (); /* Create buffer table and some buffers. */
1163 init_minibuf_once (); /* Create list of minibuffers. */
1164 /* Must precede init_window_once. */
1166 /* Call syms_of_xfaces before init_window_once because that
1167 function creates Vterminal_frame. Termcap frames now use
1168 faces, and the face implementation uses some symbols as
1169 face names. */
1170 syms_of_xfaces ();
1171 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1172 be better to arrange things not to have this dependency. */
1173 syms_of_keymap ();
1174 /* Call syms_of_keyboard before init_window_once because
1175 keyboard sets up symbols that include some face names that
1176 the X support will want to use. This can happen when
1177 CANNOT_DUMP is defined. */
1178 syms_of_keyboard ();
1180 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1181 syms_of_data ();
1182 syms_of_fns (); /* Before syms_of_charset which uses hashtables. */
1183 syms_of_fileio ();
1184 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1185 syms_of_alloc ();
1186 /* May call Ffuncall and so GC, thus the latter should be initialized. */
1187 init_print_once ();
1188 /* Before syms_of_coding because it initializes Qcharsetp. */
1189 syms_of_charset ();
1190 /* Before init_window_once, because it sets up the
1191 Vcoding_system_hash_table. */
1192 syms_of_coding (); /* This should be after syms_of_fileio. */
1194 init_window_once (); /* Init the window system. */
1195 #ifdef HAVE_WINDOW_SYSTEM
1196 init_fringe_once (); /* Swap bitmaps if necessary. */
1197 #endif /* HAVE_WINDOW_SYSTEM */
1200 init_alloc ();
1202 if (do_initial_setlocale)
1204 fixup_locale ();
1205 Vsystem_messages_locale = Vprevious_system_messages_locale;
1206 Vsystem_time_locale = Vprevious_system_time_locale;
1209 init_eval ();
1210 init_atimer ();
1211 running_asynch_code = 0;
1212 init_random ();
1214 no_loadup
1215 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1217 no_site_lisp
1218 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1220 #ifdef HAVE_NS
1221 ns_pool = ns_alloc_autorelease_pool ();
1222 #ifdef NS_IMPL_GNUSTEP
1223 /* GNUstep stupidly resets our locale settings after we made them. */
1224 fixup_locale ();
1225 #endif
1227 if (!noninteractive)
1229 #ifdef NS_IMPL_COCOA
1230 /* Started from GUI? */
1231 /* FIXME: Do the right thing if getenv returns NULL, or if
1232 chdir fails. */
1233 if (! inhibit_window_system && ! isatty (0) && ! ch_to_dir)
1234 chdir (getenv ("HOME"));
1235 if (skip_args < argc)
1237 if (!strncmp (argv[skip_args], "-psn", 4))
1239 skip_args += 1;
1240 if (! ch_to_dir) chdir (getenv ("HOME"));
1242 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1244 skip_args += 2;
1245 if (! ch_to_dir) chdir (getenv ("HOME"));
1248 #endif /* COCOA */
1250 #endif /* HAVE_NS */
1252 #ifdef HAVE_X_WINDOWS
1253 /* Stupid kludge to catch command-line display spec. We can't
1254 handle this argument entirely in window system dependent code
1255 because we don't even know which window system dependent code
1256 to run until we've recognized this argument. */
1258 char *displayname = 0;
1259 int count_before = skip_args;
1261 /* Skip any number of -d options, but only use the last one. */
1262 while (1)
1264 int count_before_this = skip_args;
1266 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1267 display_arg = 1;
1268 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1269 display_arg = 1;
1270 else
1271 break;
1273 count_before = count_before_this;
1276 /* If we have the form --display=NAME,
1277 convert it into -d name.
1278 This requires inserting a new element into argv. */
1279 if (displayname && count_before < skip_args)
1281 if (skip_args == count_before + 1)
1283 memmove (argv + count_before + 3, argv + count_before + 2,
1284 (argc - (count_before + 2)) * sizeof *argv);
1285 argv[count_before + 2] = displayname;
1286 argc++;
1288 argv[count_before + 1] = (char *) "-d";
1291 if (! no_site_lisp)
1293 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1294 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1295 no_site_lisp = 1;
1298 /* Don't actually discard this arg. */
1299 skip_args = count_before;
1301 #else /* !HAVE_X_WINDOWS */
1302 if (! no_site_lisp)
1304 int count_before = skip_args;
1306 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1307 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1308 no_site_lisp = 1;
1310 skip_args = count_before;
1312 #endif
1314 /* argmatch must not be used after here,
1315 except when building temacs
1316 because the -d argument has not been skipped in skip_args. */
1318 #ifdef MSDOS
1319 /* Call early 'cause init_environment needs it. */
1320 init_dosfns ();
1321 /* Set defaults for several environment variables. */
1322 if (initialized)
1323 init_environment (argc, argv, skip_args);
1324 else
1325 tzset ();
1326 #endif /* MSDOS */
1328 #ifdef HAVE_GFILENOTIFY
1329 globals_of_gfilenotify ();
1330 #endif
1332 #ifdef WINDOWSNT
1333 globals_of_w32 ();
1334 #ifdef HAVE_W32NOTIFY
1335 globals_of_w32notify ();
1336 #endif
1337 /* Initialize environment from registry settings. */
1338 init_environment (argv);
1339 init_ntproc (dumping); /* must precede init_editfns. */
1340 #endif
1342 /* Initialize and GC-protect Vinitial_environment and
1343 Vprocess_environment before set_initial_environment fills them
1344 in. */
1345 if (!initialized)
1346 syms_of_callproc ();
1347 /* egetenv is a pretty low-level facility, which may get called in
1348 many circumstances; it seems flimsy to put off initializing it
1349 until calling init_callproc. Do not do it when dumping. */
1350 if (! dumping)
1351 set_initial_environment ();
1353 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1354 if this is not done. Do it after set_global_environment so that we
1355 don't pollute Vglobal_environment. */
1356 /* Setting LANG here will defeat the startup locale processing... */
1357 #ifdef AIX
1358 xputenv ("LANG=C");
1359 #endif
1361 /* Init buffer storage and default directory of main buffer. */
1362 init_buffer (initialized);
1364 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1366 /* Must precede init_lread. */
1367 init_cmdargs (argc, argv, skip_args, original_pwd);
1369 if (initialized)
1371 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1372 Lisp_Object old_log_max;
1373 old_log_max = Vmessage_log_max;
1374 XSETFASTINT (Vmessage_log_max, 0);
1375 message_dolog ("", 0, 1, 0);
1376 Vmessage_log_max = old_log_max;
1379 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1380 init_fileio ();
1381 init_lread ();
1382 #ifdef WINDOWSNT
1383 /* Check to see if Emacs has been installed correctly. */
1384 check_windows_init_file ();
1385 #endif
1387 /* Intern the names of all standard functions and variables;
1388 define standard keys. */
1390 if (!initialized)
1392 /* The basic levels of Lisp must come first. Note that
1393 syms_of_data and some others have already been called. */
1394 syms_of_chartab ();
1395 syms_of_lread ();
1396 syms_of_print ();
1397 syms_of_eval ();
1398 syms_of_floatfns ();
1400 syms_of_buffer ();
1401 syms_of_bytecode ();
1402 syms_of_callint ();
1403 syms_of_casefiddle ();
1404 syms_of_casetab ();
1405 syms_of_category ();
1406 syms_of_ccl ();
1407 syms_of_character ();
1408 syms_of_cmds ();
1409 syms_of_dired ();
1410 syms_of_display ();
1411 syms_of_doc ();
1412 syms_of_editfns ();
1413 syms_of_emacs ();
1414 syms_of_filelock ();
1415 syms_of_indent ();
1416 syms_of_insdel ();
1417 /* syms_of_keymap (); */
1418 syms_of_macros ();
1419 syms_of_marker ();
1420 syms_of_minibuf ();
1421 syms_of_process ();
1422 syms_of_search ();
1423 syms_of_frame ();
1424 syms_of_syntax ();
1425 syms_of_terminal ();
1426 syms_of_term ();
1427 syms_of_undo ();
1428 #ifdef HAVE_SOUND
1429 syms_of_sound ();
1430 #endif
1431 syms_of_textprop ();
1432 syms_of_composite ();
1433 #ifdef WINDOWSNT
1434 syms_of_ntproc ();
1435 #endif /* WINDOWSNT */
1436 #if defined CYGWIN
1437 syms_of_cygw32 ();
1438 #endif
1439 syms_of_window ();
1440 syms_of_xdisp ();
1441 syms_of_font ();
1442 #ifdef HAVE_WINDOW_SYSTEM
1443 syms_of_fringe ();
1444 syms_of_image ();
1445 #endif /* HAVE_WINDOW_SYSTEM */
1446 #ifdef HAVE_X_WINDOWS
1447 syms_of_xterm ();
1448 syms_of_xfns ();
1449 syms_of_xmenu ();
1450 syms_of_fontset ();
1451 syms_of_xsettings ();
1452 #ifdef HAVE_X_SM
1453 syms_of_xsmfns ();
1454 #endif
1455 #ifdef HAVE_X11
1456 syms_of_xselect ();
1457 #endif
1458 #endif /* HAVE_X_WINDOWS */
1460 #ifdef HAVE_LIBXML2
1461 syms_of_xml ();
1462 #endif
1464 #ifdef HAVE_ZLIB
1465 syms_of_decompress ();
1466 #endif
1468 syms_of_menu ();
1470 #ifdef HAVE_NTGUI
1471 syms_of_w32term ();
1472 syms_of_w32fns ();
1473 syms_of_w32menu ();
1474 syms_of_fontset ();
1475 #endif /* HAVE_NTGUI */
1477 #if defined WINDOWSNT || defined HAVE_NTGUI
1478 syms_of_w32select ();
1479 #endif
1481 #ifdef MSDOS
1482 syms_of_xmenu ();
1483 syms_of_dosfns ();
1484 syms_of_msdos ();
1485 syms_of_win16select ();
1486 #endif /* MSDOS */
1488 #ifdef HAVE_NS
1489 syms_of_nsterm ();
1490 syms_of_nsfns ();
1491 syms_of_nsmenu ();
1492 syms_of_nsselect ();
1493 syms_of_fontset ();
1494 #endif /* HAVE_NS */
1496 #ifdef HAVE_GNUTLS
1497 syms_of_gnutls ();
1498 #endif
1500 #ifdef HAVE_GFILENOTIFY
1501 syms_of_gfilenotify ();
1502 #endif /* HAVE_GFILENOTIFY */
1504 #ifdef HAVE_INOTIFY
1505 syms_of_inotify ();
1506 #endif /* HAVE_INOTIFY */
1508 #ifdef HAVE_DBUS
1509 syms_of_dbusbind ();
1510 #endif /* HAVE_DBUS */
1512 #ifdef WINDOWSNT
1513 syms_of_ntterm ();
1514 #ifdef HAVE_W32NOTIFY
1515 syms_of_w32notify ();
1516 #endif /* HAVE_W32NOTIFY */
1517 #endif /* WINDOWSNT */
1519 syms_of_profiler ();
1521 keys_of_casefiddle ();
1522 keys_of_cmds ();
1523 keys_of_buffer ();
1524 keys_of_keyboard ();
1525 keys_of_keymap ();
1526 keys_of_window ();
1528 else
1530 /* Initialization that must be done even if the global variable
1531 initialized is non zero. */
1532 #ifdef HAVE_NTGUI
1533 globals_of_w32font ();
1534 globals_of_w32fns ();
1535 globals_of_w32menu ();
1536 #endif /* HAVE_NTGUI */
1538 #if defined WINDOWSNT || defined HAVE_NTGUI
1539 globals_of_w32select ();
1540 #endif
1543 init_charset ();
1545 /* This calls putenv and so must precede init_process_emacs. Also,
1546 it sets Voperating_system_release, which init_process_emacs uses. */
1547 init_editfns ();
1549 /* These two call putenv. */
1550 #ifdef HAVE_DBUS
1551 init_dbusbind ();
1552 #endif
1553 #ifdef USE_GTK
1554 init_xterm ();
1555 #endif
1557 /* This can create a thread that may call getenv, so it must follow
1558 all calls to putenv and setenv. Also, this sets up
1559 add_keyboard_wait_descriptor, which init_display uses. */
1560 init_process_emacs ();
1562 init_keyboard (); /* This too must precede init_sys_modes. */
1563 if (!noninteractive)
1564 init_display (); /* Determine terminal type. Calls init_sys_modes. */
1565 #if HAVE_W32NOTIFY
1566 else
1567 init_crit (); /* w32notify.c needs this in batch mode. */
1568 #endif /* HAVE_W32NOTIFY */
1569 init_xdisp ();
1570 #ifdef HAVE_WINDOW_SYSTEM
1571 init_fringe ();
1572 #endif /* HAVE_WINDOW_SYSTEM */
1573 init_macros ();
1574 init_window ();
1575 init_font ();
1577 if (!initialized)
1579 char *file;
1580 /* Handle -l loadup, args passed by Makefile. */
1581 if (argmatch (argv, argc, "-l", "--load", 3, &file, &skip_args))
1583 #ifdef WINDOWSNT
1584 char file_utf8[MAX_UTF8_PATH];
1586 if (filename_from_ansi (file, file_utf8) == 0)
1587 file = file_utf8;
1588 #endif
1589 Vtop_level = list2 (intern_c_string ("load"),
1590 build_unibyte_string (file));
1592 /* Unless next switch is -nl, load "loadup.el" first thing. */
1593 if (! no_loadup)
1594 Vtop_level = list2 (intern_c_string ("load"),
1595 build_string ("loadup.el"));
1598 /* Set up for profiling. This is known to work on FreeBSD,
1599 GNU/Linux and MinGW. It might work on some other systems too.
1600 Give it a try and tell us if it works on your system. To compile
1601 for profiling, use the configure option --enable-profiling. */
1602 #if defined (__FreeBSD__) || defined (GNU_LINUX) || defined (__MINGW32__)
1603 #ifdef PROFILING
1604 if (initialized)
1606 #ifdef __MINGW32__
1607 extern unsigned char etext asm ("etext");
1608 #else
1609 extern char etext;
1610 #endif
1612 atexit (_mcleanup);
1613 monstartup ((uintptr_t) __executable_start, (uintptr_t) &etext);
1615 else
1616 moncontrol (0);
1617 #endif
1618 #endif
1620 initialized = 1;
1622 /* Enter editor command loop. This never returns. */
1623 Frecursive_edit ();
1624 /* NOTREACHED */
1625 return 0;
1628 /* Sort the args so we can find the most important ones
1629 at the beginning of argv. */
1631 /* First, here's a table of all the standard options. */
1633 struct standard_args
1635 const char *name;
1636 const char *longname;
1637 int priority;
1638 int nargs;
1641 static const struct standard_args standard_args[] =
1643 { "-version", "--version", 150, 0 },
1644 { "-chdir", "--chdir", 130, 1 },
1645 { "-t", "--terminal", 120, 1 },
1646 { "-nw", "--no-window-system", 110, 0 },
1647 { "-nw", "--no-windows", 110, 0 },
1648 { "-batch", "--batch", 100, 0 },
1649 { "-script", "--script", 100, 1 },
1650 { "-daemon", "--daemon", 99, 0 },
1651 { "-help", "--help", 90, 0 },
1652 { "-nl", "--no-loadup", 70, 0 },
1653 { "-nsl", "--no-site-lisp", 65, 0 },
1654 /* -d must come last before the options handled in startup.el. */
1655 { "-d", "--display", 60, 1 },
1656 { "-display", 0, 60, 1 },
1657 /* Now for the options handled in `command-line' (startup.el). */
1658 /* (Note that to imply -nsl, -Q is partially handled here.) */
1659 { "-Q", "--quick", 55, 0 },
1660 { "-quick", 0, 55, 0 },
1661 { "-q", "--no-init-file", 50, 0 },
1662 { "-no-init-file", 0, 50, 0 },
1663 { "-no-site-file", "--no-site-file", 40, 0 },
1664 { "-u", "--user", 30, 1 },
1665 { "-user", 0, 30, 1 },
1666 { "-debug-init", "--debug-init", 20, 0 },
1667 { "-iconic", "--iconic", 15, 0 },
1668 { "-D", "--basic-display", 12, 0},
1669 { "-basic-display", 0, 12, 0},
1670 { "-nbc", "--no-blinking-cursor", 12, 0 },
1671 /* Now for the options handled in `command-line-1' (startup.el). */
1672 { "-nbi", "--no-bitmap-icon", 10, 0 },
1673 { "-bg", "--background-color", 10, 1 },
1674 { "-background", 0, 10, 1 },
1675 { "-fg", "--foreground-color", 10, 1 },
1676 { "-foreground", 0, 10, 1 },
1677 { "-bd", "--border-color", 10, 1 },
1678 { "-bw", "--border-width", 10, 1 },
1679 { "-ib", "--internal-border", 10, 1 },
1680 { "-ms", "--mouse-color", 10, 1 },
1681 { "-cr", "--cursor-color", 10, 1 },
1682 { "-fn", "--font", 10, 1 },
1683 { "-font", 0, 10, 1 },
1684 { "-fs", "--fullscreen", 10, 0 },
1685 { "-fw", "--fullwidth", 10, 0 },
1686 { "-fh", "--fullheight", 10, 0 },
1687 { "-mm", "--maximized", 10, 0 },
1688 { "-g", "--geometry", 10, 1 },
1689 { "-geometry", 0, 10, 1 },
1690 { "-T", "--title", 10, 1 },
1691 { "-title", 0, 10, 1 },
1692 { "-name", "--name", 10, 1 },
1693 { "-xrm", "--xrm", 10, 1 },
1694 { "-parent-id", "--parent-id", 10, 1 },
1695 { "-r", "--reverse-video", 5, 0 },
1696 { "-rv", 0, 5, 0 },
1697 { "-reverse", 0, 5, 0 },
1698 { "-hb", "--horizontal-scroll-bars", 5, 0 },
1699 { "-vb", "--vertical-scroll-bars", 5, 0 },
1700 { "-color", "--color", 5, 0},
1701 { "-no-splash", "--no-splash", 3, 0 },
1702 { "-no-desktop", "--no-desktop", 3, 0 },
1703 #ifdef HAVE_NS
1704 { "-NSAutoLaunch", 0, 5, 1 },
1705 { "-NXAutoLaunch", 0, 5, 1 },
1706 { "-_NSMachLaunch", 0, 85, 1 },
1707 { "-MachLaunch", 0, 85, 1 },
1708 { "-macosx", 0, 85, 0 },
1709 { "-NSHost", 0, 85, 1 },
1710 #endif
1711 /* These have the same priority as ordinary file name args,
1712 so they are not reordered with respect to those. */
1713 { "-L", "--directory", 0, 1 },
1714 { "-directory", 0, 0, 1 },
1715 { "-l", "--load", 0, 1 },
1716 { "-load", 0, 0, 1 },
1717 /* This has no longname, because using --scriptload confuses sort_args,
1718 because then the --script long option seems to match twice; ie
1719 you can't have a long option which is a prefix of another long
1720 option. In any case, this is entirely an internal option. */
1721 { "-scriptload", NULL, 0, 1 },
1722 { "-f", "--funcall", 0, 1 },
1723 { "-funcall", 0, 0, 1 },
1724 { "-eval", "--eval", 0, 1 },
1725 { "-execute", "--execute", 0, 1 },
1726 { "-find-file", "--find-file", 0, 1 },
1727 { "-visit", "--visit", 0, 1 },
1728 { "-file", "--file", 0, 1 },
1729 { "-insert", "--insert", 0, 1 },
1730 #ifdef HAVE_NS
1731 { "-NXOpen", 0, 0, 1 },
1732 { "-NXOpenTemp", 0, 0, 1 },
1733 { "-NSOpen", 0, 0, 1 },
1734 { "-NSOpenTemp", 0, 0, 1 },
1735 { "-GSFilePath", 0, 0, 1 },
1736 #endif
1737 /* This should be processed after ordinary file name args and the like. */
1738 { "-kill", "--kill", -10, 0 },
1741 /* Reorder the elements of ARGV (assumed to have ARGC elements)
1742 so that the highest priority ones come first.
1743 Do not change the order of elements of equal priority.
1744 If an option takes an argument, keep it and its argument together.
1746 If an option that takes no argument appears more
1747 than once, eliminate all but one copy of it. */
1749 static void
1750 sort_args (int argc, char **argv)
1752 char **new = xmalloc (argc * sizeof *new);
1753 /* For each element of argv,
1754 the corresponding element of options is:
1755 0 for an option that takes no arguments,
1756 1 for an option that takes one argument, etc.
1757 -1 for an ordinary non-option argument. */
1758 int *options = xnmalloc (argc, sizeof *options);
1759 int *priority = xnmalloc (argc, sizeof *priority);
1760 int to = 1;
1761 int incoming_used = 1;
1762 int from;
1763 int i;
1765 /* Categorize all the options,
1766 and figure out which argv elts are option arguments. */
1767 for (from = 1; from < argc; from++)
1769 options[from] = -1;
1770 priority[from] = 0;
1771 if (argv[from][0] == '-')
1773 int match;
1775 /* If we have found "--", don't consider
1776 any more arguments as options. */
1777 if (argv[from][1] == '-' && argv[from][2] == 0)
1779 /* Leave the "--", and everything following it, at the end. */
1780 for (; from < argc; from++)
1782 priority[from] = -100;
1783 options[from] = -1;
1785 break;
1788 /* Look for a match with a known old-fashioned option. */
1789 for (i = 0; i < ARRAYELTS (standard_args); i++)
1790 if (!strcmp (argv[from], standard_args[i].name))
1792 options[from] = standard_args[i].nargs;
1793 priority[from] = standard_args[i].priority;
1794 if (from + standard_args[i].nargs >= argc)
1795 fatal ("Option `%s' requires an argument\n", argv[from]);
1796 from += standard_args[i].nargs;
1797 goto done;
1800 /* Look for a match with a known long option.
1801 MATCH is -1 if no match so far, -2 if two or more matches so far,
1802 >= 0 (the table index of the match) if just one match so far. */
1803 if (argv[from][1] == '-')
1805 char const *equals = strchr (argv[from], '=');
1806 ptrdiff_t thislen =
1807 equals ? equals - argv[from] : strlen (argv[from]);
1809 match = -1;
1811 for (i = 0; i < ARRAYELTS (standard_args); i++)
1812 if (standard_args[i].longname
1813 && !strncmp (argv[from], standard_args[i].longname,
1814 thislen))
1816 if (match == -1)
1817 match = i;
1818 else
1819 match = -2;
1822 /* If we found exactly one match, use that. */
1823 if (match >= 0)
1825 options[from] = standard_args[match].nargs;
1826 priority[from] = standard_args[match].priority;
1827 /* If --OPTION=VALUE syntax is used,
1828 this option uses just one argv element. */
1829 if (equals != 0)
1830 options[from] = 0;
1831 if (from + options[from] >= argc)
1832 fatal ("Option `%s' requires an argument\n", argv[from]);
1833 from += options[from];
1835 /* FIXME When match < 0, shouldn't there be some error,
1836 or at least indication to the user that there was a
1837 problem? */
1839 done: ;
1843 /* Copy the arguments, in order of decreasing priority, to NEW. */
1844 new[0] = argv[0];
1845 while (incoming_used < argc)
1847 int best = -1;
1848 int best_priority = -9999;
1850 /* Find the highest priority remaining option.
1851 If several have equal priority, take the first of them. */
1852 for (from = 1; from < argc; from++)
1854 if (argv[from] != 0 && priority[from] > best_priority)
1856 best_priority = priority[from];
1857 best = from;
1859 /* Skip option arguments--they are tied to the options. */
1860 if (options[from] > 0)
1861 from += options[from];
1864 if (best < 0)
1865 emacs_abort ();
1867 /* Copy the highest priority remaining option, with its args, to NEW.
1868 Unless it is a duplicate of the previous one. */
1869 if (! (options[best] == 0
1870 && ! strcmp (new[to - 1], argv[best])))
1872 new[to++] = argv[best];
1873 for (i = 0; i < options[best]; i++)
1874 new[to++] = argv[best + i + 1];
1877 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1879 /* Clear out this option in ARGV. */
1880 argv[best] = 0;
1881 for (i = 0; i < options[best]; i++)
1882 argv[best + i + 1] = 0;
1885 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1886 while (to < argc)
1887 new[to++] = 0;
1889 memcpy (argv, new, sizeof (char *) * argc);
1891 xfree (options);
1892 xfree (new);
1893 xfree (priority);
1896 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1897 doc: /* Exit the Emacs job and kill it.
1898 If ARG is an integer, return ARG as the exit program code.
1899 If ARG is a string, stuff it as keyboard input.
1901 This function is called upon receipt of the signals SIGTERM
1902 or SIGHUP, and upon SIGINT in batch mode.
1904 The value of `kill-emacs-hook', if not void,
1905 is a list of functions (of no args),
1906 all of which are called before Emacs is actually killed. */)
1907 (Lisp_Object arg)
1909 struct gcpro gcpro1;
1910 int exit_code;
1912 GCPRO1 (arg);
1914 if (feof (stdin))
1915 arg = Qt;
1917 /* Fsignal calls emacs_abort () if it sees that waiting_for_input is
1918 set. */
1919 waiting_for_input = 0;
1920 Frun_hooks (1, &Qkill_emacs_hook);
1921 UNGCPRO;
1923 #ifdef HAVE_X_WINDOWS
1924 /* Transfer any clipboards we own to the clipboard manager. */
1925 x_clipboard_manager_save_all ();
1926 #endif
1928 shut_down_emacs (0, STRINGP (arg) ? arg : Qnil);
1930 #ifdef HAVE_NS
1931 ns_release_autorelease_pool (ns_pool);
1932 #endif
1934 /* If we have an auto-save list file,
1935 kill it because we are exiting Emacs deliberately (not crashing).
1936 Do it after shut_down_emacs, which does an auto-save. */
1937 if (STRINGP (Vauto_save_list_file_name))
1939 Lisp_Object listfile;
1940 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
1941 unlink (SSDATA (listfile));
1944 if (INTEGERP (arg))
1945 exit_code = (XINT (arg) < 0
1946 ? XINT (arg) | INT_MIN
1947 : XINT (arg) & INT_MAX);
1948 else
1949 exit_code = EXIT_SUCCESS;
1950 exit (exit_code);
1954 /* Perform an orderly shutdown of Emacs. Autosave any modified
1955 buffers, kill any child processes, clean up the terminal modes (if
1956 we're in the foreground), and other stuff like that. Don't perform
1957 any redisplay; this may be called when Emacs is shutting down in
1958 the background, or after its X connection has died.
1960 If SIG is a signal number, print a message for it.
1962 This is called by fatal signal handlers, X protocol error handlers,
1963 and Fkill_emacs. */
1965 void
1966 shut_down_emacs (int sig, Lisp_Object stuff)
1968 /* Prevent running of hooks from now on. */
1969 Vrun_hooks = Qnil;
1971 /* Don't update display from now on. */
1972 Vinhibit_redisplay = Qt;
1974 /* If we are controlling the terminal, reset terminal modes. */
1975 #ifndef DOS_NT
1977 pid_t pgrp = getpgrp ();
1978 pid_t tpgrp = tcgetpgrp (0);
1979 if ((tpgrp != -1) && tpgrp == pgrp)
1981 reset_all_sys_modes ();
1982 if (sig && sig != SIGTERM)
1984 static char const format[] = "Fatal error %d: ";
1985 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
1986 int buflen = sprintf (buf, format, sig);
1987 char const *sig_desc = safe_strsignal (sig);
1988 emacs_write (STDERR_FILENO, buf, buflen);
1989 emacs_write (STDERR_FILENO, sig_desc, strlen (sig_desc));
1993 #else
1994 fflush (stdout);
1995 reset_all_sys_modes ();
1996 #endif
1998 stuff_buffered_input (stuff);
2000 inhibit_sentinels = 1;
2001 kill_buffer_processes (Qnil);
2002 Fdo_auto_save (Qt, Qnil);
2004 unlock_all_files ();
2006 /* There is a tendency for a SIGIO signal to arrive within exit,
2007 and cause a SIGHUP because the input descriptor is already closed. */
2008 unrequest_sigio ();
2009 ignore_sigio ();
2011 /* Do this only if terminating normally, we want glyph matrices
2012 etc. in a core dump. */
2013 if (sig == 0 || sig == SIGTERM)
2015 check_glyph_memory ();
2016 check_message_stack ();
2019 #ifdef MSDOS
2020 dos_cleanup ();
2021 #endif
2023 #ifdef HAVE_NS
2024 ns_term_shutdown (sig);
2025 #endif
2027 #ifdef HAVE_LIBXML2
2028 xml_cleanup_parser ();
2029 #endif
2031 #ifdef WINDOWSNT
2032 term_ntproc (0);
2033 #endif
2038 #ifndef CANNOT_DUMP
2040 #include "unexec.h"
2042 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
2043 doc: /* Dump current state of Emacs into executable file FILENAME.
2044 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
2045 This is used in the file `loadup.el' when building Emacs.
2047 You must run Emacs in batch mode in order to dump it. */)
2048 (Lisp_Object filename, Lisp_Object symfile)
2050 Lisp_Object tem;
2051 Lisp_Object symbol;
2052 ptrdiff_t count = SPECPDL_INDEX ();
2054 check_pure_size ();
2056 if (! noninteractive)
2057 error ("Dumping Emacs works only in batch mode");
2059 if (!might_dump)
2060 error ("Emacs can be dumped only once");
2062 #ifdef GNU_LINUX
2064 /* Warn if the gap between BSS end and heap start is larger than this. */
2065 # define MAX_HEAP_BSS_DIFF (1024*1024)
2067 if (heap_bss_diff > MAX_HEAP_BSS_DIFF)
2069 fprintf (stderr, "**************************************************\n");
2070 fprintf (stderr, "Warning: Your system has a gap between BSS and the\n");
2071 fprintf (stderr, "heap (%"pMu" bytes). This usually means that exec-shield\n",
2072 heap_bss_diff);
2073 fprintf (stderr, "or something similar is in effect. The dump may\n");
2074 fprintf (stderr, "fail because of this. See the section about\n");
2075 fprintf (stderr, "exec-shield in etc/PROBLEMS for more information.\n");
2076 fprintf (stderr, "**************************************************\n");
2078 #endif /* GNU_LINUX */
2080 /* Bind `command-line-processed' to nil before dumping,
2081 so that the dumped Emacs will process its command line
2082 and set up to work with X windows if appropriate. */
2083 symbol = intern ("command-line-processed");
2084 specbind (symbol, Qnil);
2086 CHECK_STRING (filename);
2087 filename = Fexpand_file_name (filename, Qnil);
2088 filename = ENCODE_FILE (filename);
2089 if (!NILP (symfile))
2091 CHECK_STRING (symfile);
2092 if (SCHARS (symfile))
2094 symfile = Fexpand_file_name (symfile, Qnil);
2095 symfile = ENCODE_FILE (symfile);
2099 tem = Vpurify_flag;
2100 Vpurify_flag = Qnil;
2102 fflush (stdout);
2103 /* Tell malloc where start of impure now is. */
2104 /* Also arrange for warnings when nearly out of space. */
2105 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
2106 #ifndef WINDOWSNT
2107 /* On Windows, this was done before dumping, and that once suffices.
2108 Meanwhile, my_edata is not valid on Windows. */
2109 memory_warnings (my_edata, malloc_warning);
2110 #endif /* not WINDOWSNT */
2111 #endif /* not SYSTEM_MALLOC and not HYBRID_MALLOC */
2112 #ifdef DOUG_LEA_MALLOC
2113 malloc_state_ptr = malloc_get_state ();
2114 #endif
2116 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2118 #ifdef DOUG_LEA_MALLOC
2119 free (malloc_state_ptr);
2120 #endif
2122 #ifdef WINDOWSNT
2123 Vlibrary_cache = Qnil;
2124 #endif
2125 #ifdef HAVE_WINDOW_SYSTEM
2126 reset_image_types ();
2127 #endif
2129 Vpurify_flag = tem;
2131 return unbind_to (count, Qnil);
2134 #endif /* not CANNOT_DUMP */
2136 #if HAVE_SETLOCALE
2137 /* Recover from setlocale (LC_ALL, ""). */
2138 void
2139 fixup_locale (void)
2141 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2142 so that numbers are read and printed properly for Emacs Lisp. */
2143 setlocale (LC_NUMERIC, "C");
2146 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2147 DESIRED_LOCALE. */
2148 static void
2149 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2151 if (! EQ (*plocale, desired_locale))
2153 *plocale = desired_locale;
2154 setlocale (category, (STRINGP (desired_locale)
2155 ? SSDATA (desired_locale)
2156 : ""));
2160 /* Set system time locale to match Vsystem_time_locale, if possible. */
2161 void
2162 synchronize_system_time_locale (void)
2164 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2165 Vsystem_time_locale);
2168 /* Set system messages locale to match Vsystem_messages_locale, if
2169 possible. */
2170 void
2171 synchronize_system_messages_locale (void)
2173 #ifdef LC_MESSAGES
2174 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2175 Vsystem_messages_locale);
2176 #endif
2178 #endif /* HAVE_SETLOCALE */
2181 Lisp_Object
2182 decode_env_path (const char *evarname, const char *defalt, bool empty)
2184 const char *path, *p;
2185 Lisp_Object lpath, element, tem;
2186 /* Default is to use "." for empty path elements.
2187 But if argument EMPTY is true, use nil instead. */
2188 Lisp_Object empty_element = empty ? Qnil : build_string (".");
2189 #ifdef WINDOWSNT
2190 bool defaulted = 0;
2191 static const char *emacs_dir_env = "%emacs_dir%/";
2192 const size_t emacs_dir_len = strlen (emacs_dir_env);
2193 const char *edir = egetenv ("emacs_dir");
2194 char emacs_dir[MAX_UTF8_PATH];
2196 /* egetenv looks in process-environment, which holds the variables
2197 in their original system-locale encoding. We need emacs_dir to
2198 be in UTF-8. */
2199 if (edir)
2200 filename_from_ansi (edir, emacs_dir);
2201 #endif
2203 /* It's okay to use getenv here, because this function is only used
2204 to initialize variables when Emacs starts up, and isn't called
2205 after that. */
2206 if (evarname != 0)
2207 path = getenv (evarname);
2208 else
2209 path = 0;
2210 if (!path)
2212 path = defalt;
2213 #ifdef WINDOWSNT
2214 defaulted = 1;
2215 #endif
2217 #ifdef DOS_NT
2218 /* Ensure values from the environment use the proper directory separator. */
2219 if (path)
2221 char *path_copy;
2223 #ifdef WINDOWSNT
2224 char *path_utf8, *q, *d;
2225 int cnv_result;
2227 /* Convert each element of PATH to UTF-8. */
2228 p = path_copy = alloca (strlen (path) + 1);
2229 strcpy (path_copy, path);
2230 d = path_utf8 = alloca (4 * strlen (path) + 1);
2231 *d = '\0';
2232 do {
2233 q = _mbschr (p, SEPCHAR);
2234 if (q)
2235 *q = '\0';
2236 cnv_result = filename_from_ansi (p, d);
2237 if (q)
2239 *q++ = SEPCHAR;
2240 p = q;
2241 /* If conversion of this PATH elements fails, make sure
2242 destination pointer will stay put, thus effectively
2243 ignoring the offending element. */
2244 if (cnv_result == 0)
2246 d += strlen (d);
2247 *d++ = SEPCHAR;
2250 else if (cnv_result != 0 && d > path_utf8)
2251 d[-1] = '\0'; /* remove last semi-colon and null-terminate PATH */
2252 } while (q);
2253 path_copy = path_utf8;
2254 #else /* MSDOS */
2255 path_copy = alloca (strlen (path) + 1);
2256 strcpy (path_copy, path);
2257 #endif
2258 dostounix_filename (path_copy);
2259 path = path_copy;
2261 #endif
2262 lpath = Qnil;
2263 while (1)
2265 p = strchr (path, SEPCHAR);
2266 if (!p)
2267 p = path + strlen (path);
2268 element = (p - path ? make_unibyte_string (path, p - path)
2269 : empty_element);
2270 if (! NILP (element))
2272 #ifdef WINDOWSNT
2273 /* Relative file names in the default path are interpreted as
2274 being relative to $emacs_dir. */
2275 if (edir && defaulted
2276 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2277 element = Fexpand_file_name (Fsubstring
2278 (element,
2279 make_number (emacs_dir_len),
2280 Qnil),
2281 build_unibyte_string (emacs_dir));
2282 #endif
2284 /* Add /: to the front of the name
2285 if it would otherwise be treated as magic. */
2286 tem = Ffind_file_name_handler (element, Qt);
2288 /* However, if the handler says "I'm safe",
2289 don't bother adding /:. */
2290 if (SYMBOLP (tem))
2292 Lisp_Object prop;
2293 prop = Fget (tem, intern ("safe-magic"));
2294 if (! NILP (prop))
2295 tem = Qnil;
2298 if (! NILP (tem))
2300 AUTO_STRING (slash_colon, "/:");
2301 element = concat2 (slash_colon, element);
2303 } /* !NILP (element) */
2305 lpath = Fcons (element, lpath);
2306 if (*p)
2307 path = p + 1;
2308 else
2309 break;
2311 return Fnreverse (lpath);
2314 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2315 doc: /* Return non-nil if the current emacs process is a daemon.
2316 If the daemon was given a name argument, return that name. */)
2317 (void)
2319 if (IS_DAEMON)
2320 if (daemon_name)
2321 return build_string (daemon_name);
2322 else
2323 return Qt;
2324 else
2325 return Qnil;
2328 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2329 doc: /* Mark the Emacs daemon as being initialized.
2330 This finishes the daemonization process by doing the other half of detaching
2331 from the parent process and its tty file descriptors. */)
2332 (void)
2334 int nfd;
2335 bool err = 0;
2337 if (!IS_DAEMON)
2338 error ("This function can only be called if emacs is run as a daemon");
2340 if (daemon_pipe[1] < 0)
2341 error ("The daemon has already been initialized");
2343 if (NILP (Vafter_init_time))
2344 error ("This function can only be called after loading the init files");
2346 /* Get rid of stdin, stdout and stderr. */
2347 nfd = emacs_open ("/dev/null", O_RDWR, 0);
2348 err |= nfd < 0;
2349 err |= dup2 (nfd, 0) < 0;
2350 err |= dup2 (nfd, 1) < 0;
2351 err |= dup2 (nfd, 2) < 0;
2352 err |= emacs_close (nfd) != 0;
2354 /* Closing the pipe will notify the parent that it can exit.
2355 FIXME: In case some other process inherited the pipe, closing it here
2356 won't notify the parent because it's still open elsewhere, so we
2357 additionally send a byte, just to make sure the parent really exits.
2358 Instead, we should probably close the pipe in start-process and
2359 call-process to make sure the pipe is never inherited by
2360 subprocesses. */
2361 err |= write (daemon_pipe[1], "\n", 1) < 0;
2362 err |= emacs_close (daemon_pipe[1]) != 0;
2363 /* Set it to an invalid value so we know we've already run this function. */
2364 daemon_pipe[1] = -1;
2366 if (err)
2367 error ("I/O error during daemon initialization");
2368 return Qt;
2371 void
2372 syms_of_emacs (void)
2374 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2375 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2376 DEFSYM (Qkill_emacs, "kill-emacs");
2377 DEFSYM (Qkill_emacs_hook, "kill-emacs-hook");
2379 #ifndef CANNOT_DUMP
2380 defsubr (&Sdump_emacs);
2381 #endif
2383 defsubr (&Skill_emacs);
2385 defsubr (&Sinvocation_name);
2386 defsubr (&Sinvocation_directory);
2387 defsubr (&Sdaemonp);
2388 defsubr (&Sdaemon_initialized);
2390 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2391 doc: /* Args passed by shell to Emacs, as a list of strings.
2392 Many arguments are deleted from the list as they are processed. */);
2394 DEFVAR_LISP ("system-type", Vsystem_type,
2395 doc: /* The value is a symbol indicating the type of operating system you are using.
2396 Special values:
2397 `gnu' compiled for a GNU Hurd system.
2398 `gnu/linux' compiled for a GNU/Linux system.
2399 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2400 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2401 `ms-dos' compiled as an MS-DOS application.
2402 `windows-nt' compiled as a native W32 application.
2403 `cygwin' compiled using the Cygwin library.
2404 Anything else (in Emacs 24.1, the possibilities are: aix, berkeley-unix,
2405 hpux, irix, usg-unix-v) indicates some sort of Unix system. */);
2406 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2407 /* See configure.ac (and config.nt) for the possible SYSTEM_TYPEs. */
2409 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2410 doc: /* Value is string indicating configuration Emacs was built for.
2411 On MS-Windows, the value reflects the OS flavor and version on which
2412 Emacs is running. */);
2413 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2415 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2416 doc: /* String containing the configuration options Emacs was built with. */);
2417 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2419 DEFVAR_LISP ("system-configuration-features", Vsystem_configuration_features,
2420 doc: /* String listing some of the main features this Emacs was compiled with.
2421 An element of the form \"FOO\" generally means that HAVE_FOO was
2422 defined during the build. */);
2423 Vsystem_configuration_features = build_string (EMACS_CONFIG_FEATURES);
2425 DEFVAR_BOOL ("noninteractive", noninteractive1,
2426 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2428 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2429 doc: /* Hook run when `kill-emacs' is called.
2430 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2431 in other similar situations), functions placed on this hook should not
2432 expect to be able to interact with the user. To ask for confirmation,
2433 see `kill-emacs-query-functions' instead.
2435 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2436 `noninteractive' was non-nil. */);
2437 Vkill_emacs_hook = Qnil;
2439 DEFVAR_LISP ("path-separator", Vpath_separator,
2440 doc: /* String containing the character that separates directories in
2441 search paths, such as PATH and other similar environment variables. */);
2443 char c = SEPCHAR;
2444 Vpath_separator = make_string (&c, 1);
2447 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2448 doc: /* The program name that was used to run Emacs.
2449 Any directory names are omitted. */);
2451 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2452 doc: /* The directory in which the Emacs executable was found, to run it.
2453 The value is nil if that directory's name is not known. */);
2455 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2456 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2457 In an installed Emacs, this is normally nil. It is non-nil if
2458 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2459 within the variable `invocation-directory' or its parent. For example,
2460 this is the case when running an uninstalled Emacs executable from its
2461 build directory. */);
2462 Vinstallation_directory = Qnil;
2464 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2465 doc: /* System locale for messages. */);
2466 Vsystem_messages_locale = Qnil;
2468 DEFVAR_LISP ("previous-system-messages-locale",
2469 Vprevious_system_messages_locale,
2470 doc: /* Most recently used system locale for messages. */);
2471 Vprevious_system_messages_locale = Qnil;
2473 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2474 doc: /* System locale for time. */);
2475 Vsystem_time_locale = Qnil;
2477 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2478 doc: /* Most recently used system locale for time. */);
2479 Vprevious_system_time_locale = Qnil;
2481 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2482 doc: /* Value of `current-time' before Emacs begins initialization. */);
2483 Vbefore_init_time = Qnil;
2485 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2486 doc: /* Value of `current-time' after loading the init files.
2487 This is nil during initialization. */);
2488 Vafter_init_time = Qnil;
2490 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2491 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2492 inhibit_x_resources = 0;
2494 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2495 doc: /* Short copyright string for this version of Emacs. */);
2496 Vemacs_copyright = build_string (emacs_copyright);
2498 DEFVAR_LISP ("emacs-version", Vemacs_version,
2499 doc: /* Version numbers of this version of Emacs. */);
2500 Vemacs_version = build_string (emacs_version);
2502 DEFVAR_LISP ("report-emacs-bug-address", Vreport_emacs_bug_address,
2503 doc: /* Address of mailing list for GNU Emacs bugs. */);
2504 Vreport_emacs_bug_address = build_string (emacs_bugreport);
2506 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2507 doc: /* Alist of dynamic libraries vs external files implementing them.
2508 Each element is a list (LIBRARY FILE...), where the car is a symbol
2509 representing a supported external library, and the rest are strings giving
2510 alternate filenames for that library.
2512 Emacs tries to load the library from the files in the order they appear on
2513 the list; if none is loaded, the running session of Emacs won't have access
2514 to that library.
2516 Note that image types `pbm' and `xbm' do not need entries in this variable
2517 because they do not depend on external libraries and are always available.
2519 Also note that this is not a generic facility for accessing external
2520 libraries; only those already known by Emacs will be loaded. */);
2521 Vdynamic_library_alist = Qnil;
2522 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2524 #ifdef WINDOWSNT
2525 Vlibrary_cache = Qnil;
2526 staticpro (&Vlibrary_cache);
2527 #endif