Merge branch 'emacs-24' of git.sv.gnu.org:/srv/git/emacs into emacs-24
[emacs.git] / src / emacs.c
blob7367e0d35ea6cbb6caa2ad4969e750a0982ee10c
1 /* Fully extensible Emacs, running on Unix, intended for GNU.
3 Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2014 Free Software
4 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 HAVE_WINDOW_SYSTEM
55 #include TERM_HEADER
56 #endif /* HAVE_WINDOW_SYSTEM */
58 #ifdef NS_IMPL_GNUSTEP
59 /* At least under Debian, GSConfig is in a subdirectory. --Stef */
60 #include <GNUstepBase/GSConfig.h>
61 #endif
63 #include "commands.h"
64 #include "intervals.h"
65 #include "character.h"
66 #include "buffer.h"
67 #include "window.h"
69 #include "systty.h"
70 #include "atimer.h"
71 #include "blockinput.h"
72 #include "syssignal.h"
73 #include "process.h"
74 #include "frame.h"
75 #include "termhooks.h"
76 #include "keyboard.h"
77 #include "keymap.h"
78 #include "category.h"
79 #include "charset.h"
80 #include "composite.h"
81 #include "dispextern.h"
82 #include "syntax.h"
83 #include "systime.h"
85 #include "gnutls.h"
87 #if (defined PROFILING \
88 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__))
89 # include <sys/gmon.h>
90 extern void moncontrol (int mode);
91 #endif
93 #ifdef HAVE_SETLOCALE
94 #include <locale.h>
95 #endif
97 #ifdef HAVE_SETRLIMIT
98 #include <sys/time.h>
99 #include <sys/resource.h>
100 #endif
102 #ifdef HAVE_PERSONALITY_LINUX32
103 #include <sys/personality.h>
104 #endif
106 static const char emacs_version[] = VERSION;
107 static const char emacs_copyright[] = COPYRIGHT;
109 /* Empty lisp strings. To avoid having to build any others. */
110 Lisp_Object empty_unibyte_string, empty_multibyte_string;
112 #ifdef WINDOWSNT
113 /* Cache for externally loaded libraries. */
114 Lisp_Object Vlibrary_cache;
115 #endif
117 /* Set after Emacs has started up the first time.
118 Prevents reinitialization of the Lisp world and keymaps
119 on subsequent starts. */
120 bool initialized;
122 #ifdef DARWIN_OS
123 extern void unexec_init_emacs_zone (void);
124 #endif
126 #ifdef DOUG_LEA_MALLOC
127 /* Preserves a pointer to the memory allocated that copies that
128 static data inside glibc's malloc. */
129 static void *malloc_state_ptr;
130 /* From glibc, a routine that returns a copy of the malloc internal state. */
131 extern void *malloc_get_state (void);
132 /* From glibc, a routine that overwrites the malloc internal state. */
133 extern int malloc_set_state (void*);
134 /* True if the MALLOC_CHECK_ environment variable was set while
135 dumping. Used to work around a bug in glibc's malloc. */
136 static bool malloc_using_checking;
137 #elif defined HAVE_PTHREAD && !defined SYSTEM_MALLOC
138 extern void malloc_enable_thread (void);
139 #endif
141 Lisp_Object Qfile_name_handler_alist;
143 Lisp_Object Qrisky_local_variable;
145 Lisp_Object Qkill_emacs;
146 static Lisp_Object Qkill_emacs_hook;
148 /* If true, Emacs should not attempt to use a window-specific code,
149 but instead should use the virtual terminal under which it was started. */
150 bool inhibit_window_system;
152 /* If true, a filter or a sentinel is running. Tested to save the match
153 data on the first attempt to change it inside asynchronous code. */
154 bool running_asynch_code;
156 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
157 /* If true, -d was specified, meaning we're using some window system. */
158 bool display_arg;
159 #endif
161 /* An address near the bottom of the stack.
162 Tells GC how to save a copy of the stack. */
163 char *stack_bottom;
165 #if defined (DOUG_LEA_MALLOC) || defined (GNU_LINUX)
166 /* The address where the heap starts (from the first sbrk (0) call). */
167 static void *my_heap_start;
168 #endif
170 #ifdef GNU_LINUX
171 /* The gap between BSS end and heap start as far as we can tell. */
172 static uprintmax_t heap_bss_diff;
173 #endif
175 /* To run as a daemon under Cocoa or Windows, we must do a fork+exec,
176 not a simple fork.
178 On Cocoa, CoreFoundation lib fails in forked process:
179 http://developer.apple.com/ReleaseNotes/
180 CoreFoundation/CoreFoundation.html)
182 On Windows, a Cygwin fork child cannot access the USER subsystem.
184 We mark being in the exec'd process by a daemon name argument of
185 form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
186 NAME is the original daemon name, if any. */
187 #if defined NS_IMPL_COCOA || (defined HAVE_NTGUI && defined CYGWIN)
188 # define DAEMON_MUST_EXEC
189 #endif
191 /* True means running Emacs without interactive terminal. */
192 bool noninteractive;
194 /* True means remove site-lisp directories from load-path. */
195 bool no_site_lisp;
197 /* Name for the server started by the daemon.*/
198 static char *daemon_name;
200 /* Pipe used to send exit notification to the daemon parent at
201 startup. */
202 int daemon_pipe[2];
204 /* Save argv and argc. */
205 char **initial_argv;
206 int initial_argc;
208 static void sort_args (int argc, char **argv);
209 static void syms_of_emacs (void);
211 /* C89 needs each string be at most 509 characters, so the usage
212 strings below are split to not overflow this limit. */
213 static char const *const usage_message[] =
214 { "\
216 Run Emacs, the extensible, customizable, self-documenting real-time\n\
217 display editor. The recommended way to start Emacs for normal editing\n\
218 is with no options at all.\n\
220 Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
221 read the main documentation for these command-line arguments.\n\
223 Initialization options:\n\
227 --batch do not do interactive display; implies -q\n\
228 --chdir DIR change to directory DIR\n\
229 --daemon start a server in the background\n\
230 --debug-init enable Emacs Lisp debugger for init file\n\
231 --display, -d DISPLAY use X server DISPLAY\n\
234 --no-desktop do not load a saved desktop\n\
235 --no-init-file, -q load neither ~/.emacs nor default.el\n\
236 --no-shared-memory, -nl do not use shared memory\n\
237 --no-site-file do not load site-start.el\n\
238 --no-site-lisp, -nsl do not add site-lisp directories to load-path\n\
239 --no-splash do not display a splash screen on startup\n\
240 --no-window-system, -nw do not communicate with X, ignoring $DISPLAY\n\
243 --quick, -Q equivalent to:\n\
244 -q --no-site-file --no-site-lisp --no-splash\n\
245 --script FILE run FILE as an Emacs Lisp script\n\
246 --terminal, -t DEVICE use DEVICE for terminal I/O\n\
247 --user, -u USER load ~USER/.emacs instead of your own\n\
251 Action options:\n\
253 FILE visit FILE using find-file\n\
254 +LINE go to line LINE in next FILE\n\
255 +LINE:COLUMN go to line LINE, column COLUMN, in next FILE\n\
256 --directory, -L DIR prepend DIR to load-path (with :DIR, append DIR)\n\
257 --eval EXPR evaluate Emacs Lisp expression EXPR\n\
258 --execute EXPR evaluate Emacs Lisp expression EXPR\n\
261 --file FILE visit FILE using find-file\n\
262 --find-file FILE visit FILE using find-file\n\
263 --funcall, -f FUNC call Emacs Lisp function FUNC with no arguments\n\
264 --insert FILE insert contents of FILE into current buffer\n\
265 --kill exit without asking for confirmation\n\
266 --load, -l FILE load Emacs Lisp FILE using the load function\n\
267 --visit FILE visit FILE using find-file\n\
271 Display options:\n\
273 --background-color, -bg COLOR window background color\n\
274 --basic-display, -D disable many display features;\n\
275 used for debugging Emacs\n\
276 --border-color, -bd COLOR main border color\n\
277 --border-width, -bw WIDTH width of main border\n\
280 --color, --color=MODE override color mode for character terminals;\n\
281 MODE defaults to `auto', and\n\
282 can also be `never', `always',\n\
283 or a mode name like `ansi8'\n\
284 --cursor-color, -cr COLOR color of the Emacs cursor indicating point\n\
285 --font, -fn FONT default font; must be fixed-width\n\
286 --foreground-color, -fg COLOR window foreground color\n\
289 --fullheight, -fh make the first frame high as the screen\n\
290 --fullscreen, -fs make the first frame fullscreen\n\
291 --fullwidth, -fw make the first frame wide as the screen\n\
292 --maximized, -mm make the first frame maximized\n\
293 --geometry, -g GEOMETRY window geometry\n\
296 --no-bitmap-icon, -nbi do not use picture of gnu for Emacs icon\n\
297 --iconic start Emacs in iconified state\n\
298 --internal-border, -ib WIDTH width between text and main border\n\
299 --line-spacing, -lsp PIXELS additional space to put between lines\n\
300 --mouse-color, -ms COLOR mouse cursor color in Emacs window\n\
301 --name NAME title for initial Emacs frame\n\
304 --no-blinking-cursor, -nbc disable blinking cursor\n\
305 --reverse-video, -r, -rv switch foreground and background\n\
306 --title, -T TITLE title for initial Emacs frame\n\
307 --vertical-scroll-bars, -vb enable vertical scroll bars\n\
308 --xrm XRESOURCES set additional X resources\n\
309 --parent-id XID set parent window\n\
310 --help display this help and exit\n\
311 --version output version information and exit\n\
315 You can generally also specify long option names with a single -; for\n\
316 example, -batch as well as --batch. You can use any unambiguous\n\
317 abbreviation for a --option.\n\
319 Various environment variables and window system resources also affect\n\
320 the operation of Emacs. See the main documentation.\n\
322 Report bugs to bug-gnu-emacs@gnu.org. First, please see the Bugs\n\
323 section of the Emacs manual or the file BUGS.\n"
327 /* True if handling a fatal error already. */
328 bool fatal_error_in_progress;
330 #ifdef HAVE_NS
331 /* NS autrelease pool, for memory management. */
332 static void *ns_pool;
333 #endif
335 #if !HAVE_SETLOCALE
336 static char *
337 setlocale (int cat, char const *locale)
339 return 0;
341 #endif
344 /* Report a fatal error due to signal SIG, output a backtrace of at
345 most BACKTRACE_LIMIT lines, and exit. */
346 _Noreturn void
347 terminate_due_to_signal (int sig, int backtrace_limit)
349 signal (sig, SIG_DFL);
350 totally_unblock_input ();
352 /* If fatal error occurs in code below, avoid infinite recursion. */
353 if (! fatal_error_in_progress)
355 fatal_error_in_progress = 1;
357 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
358 Fkill_emacs (make_number (sig));
360 shut_down_emacs (sig, Qnil);
361 emacs_backtrace (backtrace_limit);
364 /* Signal the same code; this time it will really be fatal.
365 Since we're in a signal handler, the signal is blocked, so we
366 have to unblock it if we want to really receive it. */
367 #ifndef MSDOS
369 sigset_t unblocked;
370 sigemptyset (&unblocked);
371 sigaddset (&unblocked, sig);
372 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
374 #endif
376 emacs_raise (sig);
378 /* This shouldn't be executed, but it prevents a warning. */
379 exit (1);
382 /* Code for dealing with Lisp access to the Unix command line. */
384 static void
385 init_cmdargs (int argc, char **argv, int skip_args, char *original_pwd)
387 register int i;
388 Lisp_Object name, dir, handler;
389 ptrdiff_t count = SPECPDL_INDEX ();
390 Lisp_Object raw_name;
392 initial_argv = argv;
393 initial_argc = argc;
395 #ifdef WINDOWSNT
396 /* Must use argv[0] converted to UTF-8, as it begets many standard
397 file and directory names. */
399 char argv0[MAX_UTF8_PATH];
401 if (filename_from_ansi (argv[0], argv0) == 0)
402 raw_name = build_unibyte_string (argv0);
403 else
404 raw_name = build_unibyte_string (argv[0]);
406 #else
407 raw_name = build_unibyte_string (argv[0]);
408 #endif
410 /* Add /: to the front of the name
411 if it would otherwise be treated as magic. */
412 handler = Ffind_file_name_handler (raw_name, Qt);
413 if (! NILP (handler))
414 raw_name = concat2 (build_string ("/:"), raw_name);
416 Vinvocation_name = Ffile_name_nondirectory (raw_name);
417 Vinvocation_directory = Ffile_name_directory (raw_name);
419 /* If we got no directory in argv[0], search PATH to find where
420 Emacs actually came from. */
421 if (NILP (Vinvocation_directory))
423 Lisp_Object found;
424 int yes = openp (Vexec_path, Vinvocation_name,
425 Vexec_suffixes, &found, make_number (X_OK), false);
426 if (yes == 1)
428 /* Add /: to the front of the name
429 if it would otherwise be treated as magic. */
430 handler = Ffind_file_name_handler (found, Qt);
431 if (! NILP (handler))
432 found = concat2 (build_string ("/:"), found);
433 Vinvocation_directory = Ffile_name_directory (found);
437 if (!NILP (Vinvocation_directory)
438 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
439 /* Emacs was started with relative path, like ./emacs.
440 Make it absolute. */
442 Lisp_Object odir =
443 original_pwd ? build_unibyte_string (original_pwd) : Qnil;
445 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, odir);
448 Vinstallation_directory = Qnil;
450 if (!NILP (Vinvocation_directory))
452 dir = Vinvocation_directory;
453 #ifdef WINDOWSNT
454 /* If we are running from the build directory, set DIR to the
455 src subdirectory of the Emacs tree, like on Posix
456 platforms. */
457 if (SBYTES (dir) > sizeof ("/i386/") - 1
458 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
459 "/i386/"))
460 dir = Fexpand_file_name (build_string ("../.."), dir);
461 #else /* !WINDOWSNT */
462 #endif
463 name = Fexpand_file_name (Vinvocation_name, dir);
464 while (1)
466 Lisp_Object tem, lib_src_exists;
467 Lisp_Object etc_exists, info_exists;
469 /* See if dir contains subdirs for use by Emacs.
470 Check for the ones that would exist in a build directory,
471 not including lisp and info. */
472 tem = Fexpand_file_name (build_string ("lib-src"), dir);
473 lib_src_exists = Ffile_exists_p (tem);
475 #ifdef MSDOS
476 /* MSDOS installations frequently remove lib-src, but we still
477 must set installation-directory, or else info won't find
478 its files (it uses the value of installation-directory). */
479 tem = Fexpand_file_name (build_string ("info"), dir);
480 info_exists = Ffile_exists_p (tem);
481 #else
482 info_exists = Qnil;
483 #endif
485 if (!NILP (lib_src_exists) || !NILP (info_exists))
487 tem = Fexpand_file_name (build_string ("etc"), dir);
488 etc_exists = Ffile_exists_p (tem);
489 if (!NILP (etc_exists))
491 Vinstallation_directory
492 = Ffile_name_as_directory (dir);
493 break;
497 /* See if dir's parent contains those subdirs. */
498 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
499 lib_src_exists = Ffile_exists_p (tem);
502 #ifdef MSDOS
503 /* See the MSDOS commentary above. */
504 tem = Fexpand_file_name (build_string ("../info"), dir);
505 info_exists = Ffile_exists_p (tem);
506 #else
507 info_exists = Qnil;
508 #endif
510 if (!NILP (lib_src_exists) || !NILP (info_exists))
512 tem = Fexpand_file_name (build_string ("../etc"), dir);
513 etc_exists = Ffile_exists_p (tem);
514 if (!NILP (etc_exists))
516 tem = Fexpand_file_name (build_string (".."), dir);
517 Vinstallation_directory
518 = Ffile_name_as_directory (tem);
519 break;
523 /* If the Emacs executable is actually a link,
524 next try the dir that the link points into. */
525 tem = Ffile_symlink_p (name);
526 if (!NILP (tem))
528 name = Fexpand_file_name (tem, dir);
529 dir = Ffile_name_directory (name);
531 else
532 break;
536 Vcommand_line_args = Qnil;
538 for (i = argc - 1; i >= 0; i--)
540 if (i == 0 || i > skip_args)
541 /* For the moment, we keep arguments as is in unibyte strings.
542 They are decoded in the function command-line after we know
543 locale-coding-system. */
544 Vcommand_line_args
545 = Fcons (build_unibyte_string (argv[i]), Vcommand_line_args);
548 unbind_to (count, Qnil);
551 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
552 doc: /* Return the program name that was used to run Emacs.
553 Any directory names are omitted. */)
554 (void)
556 return Fcopy_sequence (Vinvocation_name);
559 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
560 0, 0, 0,
561 doc: /* Return the directory name in which the Emacs executable was located. */)
562 (void)
564 return Fcopy_sequence (Vinvocation_directory);
568 #ifdef HAVE_TZSET
569 /* A valid but unlikely value for the TZ environment value.
570 It is OK (though a bit slower) if the user actually chooses this value. */
571 static char const dump_tz[] = "UtC0";
572 #endif
574 /* Test whether the next argument in ARGV matches SSTR or a prefix of
575 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
576 (the argument is supposed to have a value) store in *VALPTR either
577 the next argument or the portion of this one after the equal sign.
578 ARGV is read starting at position *SKIPPTR; this index is advanced
579 by the number of arguments used.
581 Too bad we can't just use getopt for all of this, but we don't have
582 enough information to do it right. */
584 static bool
585 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
586 int minlen, char **valptr, int *skipptr)
588 char *p = NULL;
589 ptrdiff_t arglen;
590 char *arg;
592 /* Don't access argv[argc]; give up in advance. */
593 if (argc <= *skipptr + 1)
594 return 0;
596 arg = argv[*skipptr+1];
597 if (arg == NULL)
598 return 0;
599 if (strcmp (arg, sstr) == 0)
601 if (valptr != NULL)
603 *valptr = argv[*skipptr+2];
604 *skipptr += 2;
606 else
607 *skipptr += 1;
608 return 1;
610 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
611 ? p - arg : strlen (arg));
612 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
613 return 0;
614 else if (valptr == NULL)
616 *skipptr += 1;
617 return 1;
619 else if (p != NULL)
621 *valptr = p+1;
622 *skipptr += 1;
623 return 1;
625 else if (argv[*skipptr+2] != NULL)
627 *valptr = argv[*skipptr+2];
628 *skipptr += 2;
629 return 1;
631 else
633 return 0;
637 #ifdef DOUG_LEA_MALLOC
639 /* malloc can be invoked even before main (e.g. by the dynamic
640 linker), so the dumped malloc state must be restored as early as
641 possible using this special hook. */
643 static void
644 malloc_initialize_hook (void)
646 if (initialized)
648 if (!malloc_using_checking)
649 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
650 ignored if the heap to be restored was constructed without
651 malloc checking. Can't use unsetenv, since that calls malloc. */
653 char **p;
655 for (p = environ; p && *p; p++)
656 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
659 *p = p[1];
660 while (*++p);
661 break;
665 malloc_set_state (malloc_state_ptr);
666 #ifndef XMALLOC_OVERRUN_CHECK
667 free (malloc_state_ptr);
668 #endif
670 else
672 if (my_heap_start == 0)
673 my_heap_start = sbrk (0);
674 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
678 void (*__malloc_initialize_hook) (void) EXTERNALLY_VISIBLE = malloc_initialize_hook;
680 #endif /* DOUG_LEA_MALLOC */
682 /* Close standard output and standard error, reporting any write
683 errors as best we can. This is intended for use with atexit. */
684 static void
685 close_output_streams (void)
687 if (close_stream (stdout) != 0)
689 emacs_perror ("Write error to standard output");
690 _exit (EXIT_FAILURE);
693 if (close_stream (stderr) != 0)
694 _exit (EXIT_FAILURE);
697 /* ARGSUSED */
699 main (int argc, char **argv)
701 #if GC_MARK_STACK
702 Lisp_Object dummy;
703 #endif
704 char stack_bottom_variable;
705 bool do_initial_setlocale;
706 bool dumping;
707 int skip_args = 0;
708 #ifdef HAVE_SETRLIMIT
709 struct rlimit rlim;
710 #endif
711 bool no_loadup = 0;
712 char *junk = 0;
713 char *dname_arg = 0;
714 #ifdef DAEMON_MUST_EXEC
715 char dname_arg2[80];
716 #endif
717 char *ch_to_dir = 0;
719 /* If we use --chdir, this records the original directory. */
720 char *original_pwd = 0;
722 #if GC_MARK_STACK
723 stack_base = &dummy;
724 #endif
726 #ifdef G_SLICE_ALWAYS_MALLOC
727 /* This is used by the Cygwin build. It's not needed starting with
728 cygwin-1.7.24, but it doesn't do any harm. */
729 xputenv ("G_SLICE=always-malloc");
730 #endif
732 #ifdef GNU_LINUX
733 if (!initialized)
735 extern char my_endbss[];
736 extern char *my_endbss_static;
738 if (my_heap_start == 0)
739 my_heap_start = sbrk (0);
741 heap_bss_diff = (char *)my_heap_start - max (my_endbss, my_endbss_static);
743 #endif
745 #if defined WINDOWSNT || defined HAVE_NTGUI
746 /* Set global variables used to detect Windows version. Do this as
747 early as possible. (unexw32.c calls this function as well, but
748 the additional call here is harmless.) */
749 cache_system_info ();
750 #ifdef WINDOWSNT
751 /* On Windows 9X, we have to load UNICOWS.DLL as early as possible,
752 to have non-stub implementations of APIs we need to convert file
753 names between UTF-8 and the system's ANSI codepage. */
754 maybe_load_unicows_dll ();
755 #endif
756 #endif
758 #ifdef RUN_TIME_REMAP
759 if (initialized)
760 run_time_remap (argv[0]);
761 #endif
763 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
764 #ifdef DARWIN_OS
765 if (!initialized)
766 unexec_init_emacs_zone ();
767 #endif
769 atexit (close_output_streams);
771 sort_args (argc, argv);
772 argc = 0;
773 while (argv[argc]) argc++;
775 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
777 const char *version, *copyright;
778 if (initialized)
780 Lisp_Object tem, tem2;
781 tem = Fsymbol_value (intern_c_string ("emacs-version"));
782 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
783 if (!STRINGP (tem))
785 fprintf (stderr, "Invalid value of `emacs-version'\n");
786 exit (1);
788 if (!STRINGP (tem2))
790 fprintf (stderr, "Invalid value of `emacs-copyright'\n");
791 exit (1);
793 else
795 version = SSDATA (tem);
796 copyright = SSDATA (tem2);
799 else
801 version = emacs_version;
802 copyright = emacs_copyright;
804 printf ("GNU Emacs %s\n", version);
805 printf ("%s\n", copyright);
806 printf ("GNU Emacs comes with ABSOLUTELY NO WARRANTY.\n");
807 printf ("You may redistribute copies of Emacs\n");
808 printf ("under the terms of the GNU General Public License.\n");
809 printf ("For more information about these matters, ");
810 printf ("see the file named COPYING.\n");
811 exit (0);
814 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
816 #ifdef WINDOWSNT
817 /* argv[] array is kept in its original ANSI codepage encoding,
818 we need to convert to UTF-8, for chdir to work. */
819 char newdir[MAX_UTF8_PATH];
821 filename_from_ansi (ch_to_dir, newdir);
822 ch_to_dir = newdir;
823 #endif
824 original_pwd = get_current_dir_name ();
825 if (chdir (ch_to_dir) != 0)
827 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
828 argv[0], ch_to_dir, strerror (errno));
829 exit (1);
833 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
834 || strcmp (argv[argc - 1], "bootstrap") == 0);
836 #ifdef HAVE_PERSONALITY_LINUX32
837 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
839 /* Set this so we only do this once. */
840 xputenv ("EMACS_HEAP_EXEC=true");
842 /* A flag to turn off address randomization which is introduced
843 in linux kernel shipped with fedora core 4 */
844 #define ADD_NO_RANDOMIZE 0x0040000
845 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
846 #undef ADD_NO_RANDOMIZE
848 execvp (argv[0], argv);
850 /* If the exec fails, try to dump anyway. */
851 emacs_perror (argv[0]);
853 #endif /* HAVE_PERSONALITY_LINUX32 */
855 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK)
856 /* Extend the stack space available.
857 Don't do that if dumping, since some systems (e.g. DJGPP)
858 might define a smaller stack limit at that time. */
859 if (1
860 #ifndef CANNOT_DUMP
861 && (!noninteractive || initialized)
862 #endif
863 && !getrlimit (RLIMIT_STACK, &rlim))
865 long newlim;
866 extern size_t re_max_failures;
867 /* Approximate the amount regex.c needs per unit of re_max_failures. */
868 int ratio = 20 * sizeof (char *);
869 /* Then add 33% to cover the size of the smaller stacks that regex.c
870 successively allocates and discards, on its way to the maximum. */
871 ratio += ratio / 3;
872 /* Add in some extra to cover
873 what we're likely to use for other reasons. */
874 newlim = re_max_failures * ratio + 200000;
875 #ifdef __NetBSD__
876 /* NetBSD (at least NetBSD 1.2G and former) has a bug in its
877 stack allocation routine for new process that the allocation
878 fails if stack limit is not on page boundary. So, round up the
879 new limit to page boundary. */
880 newlim = (newlim + getpagesize () - 1) / getpagesize () * getpagesize ();
881 #endif
882 if (newlim > rlim.rlim_max)
884 newlim = rlim.rlim_max;
885 /* Don't let regex.c overflow the stack we have. */
886 re_max_failures = (newlim - 200000) / ratio;
888 if (rlim.rlim_cur < newlim)
889 rlim.rlim_cur = newlim;
891 setrlimit (RLIMIT_STACK, &rlim);
893 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK */
895 /* Record (approximately) where the stack begins. */
896 stack_bottom = &stack_bottom_variable;
898 clearerr (stdin);
900 #ifndef SYSTEM_MALLOC
901 /* Arrange to get warning messages as memory fills up. */
902 memory_warnings (0, malloc_warning);
904 /* Call malloc at least once, to run malloc_initialize_hook.
905 Also call realloc and free for consistency. */
906 free (realloc (malloc (4), 4));
908 #endif /* not SYSTEM_MALLOC */
910 #if defined (MSDOS) || defined (WINDOWSNT)
911 /* We do all file input/output as binary files. When we need to translate
912 newlines, we do that manually. */
913 _fmode = O_BINARY;
914 #endif /* MSDOS || WINDOWSNT */
916 #ifdef MSDOS
917 if (!isatty (fileno (stdin)))
918 setmode (fileno (stdin), O_BINARY);
919 if (!isatty (fileno (stdout)))
921 fflush (stdout);
922 setmode (fileno (stdout), O_BINARY);
924 #endif /* MSDOS */
926 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
927 The build procedure uses this while dumping, to ensure that the
928 dumped Emacs does not have its system locale tables initialized,
929 as that might cause screwups when the dumped Emacs starts up. */
931 char *lc_all = getenv ("LC_ALL");
932 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
935 /* Set locale now, so that initial error messages are localized properly.
936 fixup_locale must wait until later, since it builds strings. */
937 if (do_initial_setlocale)
938 setlocale (LC_ALL, "");
940 inhibit_window_system = 0;
942 /* Handle the -t switch, which specifies filename to use as terminal. */
943 while (1)
945 char *term;
946 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
948 int result;
949 emacs_close (0);
950 emacs_close (1);
951 result = emacs_open (term, O_RDWR, 0);
952 if (result < 0 || fcntl (0, F_DUPFD_CLOEXEC, 1) < 0)
954 char *errstring = strerror (errno);
955 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
956 exit (1);
958 if (! isatty (0))
960 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
961 exit (1);
963 fprintf (stderr, "Using %s\n", term);
964 #ifdef HAVE_WINDOW_SYSTEM
965 inhibit_window_system = 1; /* -t => -nw */
966 #endif
968 else
969 break;
972 /* Command line option --no-windows is deprecated and thus not mentioned
973 in the manual and usage information. */
974 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
975 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
976 inhibit_window_system = 1;
978 /* Handle the -batch switch, which means don't do interactive display. */
979 noninteractive = 0;
980 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
982 noninteractive = 1;
983 Vundo_outer_limit = Qnil;
985 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
987 noninteractive = 1; /* Set batch mode. */
988 /* Convert --script to -scriptload, un-skip it, and sort again
989 so that it will be handled in proper sequence. */
990 /* FIXME broken for --script=FILE - is that supposed to work? */
991 argv[skip_args - 1] = (char *) "-scriptload";
992 skip_args -= 2;
993 sort_args (argc, argv);
996 /* Handle the --help option, which gives a usage message. */
997 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
999 int i;
1000 printf ("Usage: %s [OPTION-OR-FILENAME]...\n", argv[0]);
1001 for (i = 0; i < sizeof usage_message / sizeof *usage_message; i++)
1002 fputs (usage_message[i], stdout);
1003 exit (0);
1006 /* Make sure IS_DAEMON starts up as false. */
1007 daemon_pipe[1] = 0;
1009 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
1010 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
1012 #ifndef DOS_NT
1013 pid_t f;
1015 /* Start as a daemon: fork a new child process which will run the
1016 rest of the initialization code, then exit.
1018 Detaching a daemon requires the following steps:
1019 - fork
1020 - setsid
1021 - exit the parent
1022 - close the tty file-descriptors
1024 We only want to do the last 2 steps once the daemon is ready to
1025 serve requests, i.e. after loading .emacs (initialization).
1026 OTOH initialization may start subprocesses (e.g. ispell) and these
1027 should be run from the proper process (the one that will end up
1028 running as daemon) and with the proper "session id" in order for
1029 them to keep working after detaching, so fork and setsid need to be
1030 performed before initialization.
1032 We want to avoid exiting before the server socket is ready, so
1033 use a pipe for synchronization. The parent waits for the child
1034 to close its end of the pipe (using `daemon-initialized')
1035 before exiting. */
1036 if (emacs_pipe (daemon_pipe) != 0)
1038 fprintf (stderr, "Cannot pipe!\n");
1039 exit (1);
1042 #ifndef DAEMON_MUST_EXEC
1043 #ifdef USE_GTK
1044 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
1045 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
1046 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
1047 #endif /* USE_GTK */
1048 f = fork ();
1049 #else /* DAEMON_MUST_EXEC */
1050 if (!dname_arg || !strchr (dname_arg, '\n'))
1051 f = fork (); /* in orig */
1052 else
1053 f = 0; /* in exec'd */
1054 #endif /* !DAEMON_MUST_EXEC */
1055 if (f > 0)
1057 int retval;
1058 char buf[1];
1060 /* Close unused writing end of the pipe. */
1061 emacs_close (daemon_pipe[1]);
1063 /* Just wait for the child to close its end of the pipe. */
1066 retval = read (daemon_pipe[0], &buf, 1);
1068 while (retval == -1 && errno == EINTR);
1070 if (retval < 0)
1072 fprintf (stderr, "Error reading status from child\n");
1073 exit (1);
1075 else if (retval == 0)
1077 fprintf (stderr, "Error: server did not start correctly\n");
1078 exit (1);
1081 emacs_close (daemon_pipe[0]);
1082 exit (0);
1084 if (f < 0)
1086 emacs_perror ("fork");
1087 exit (EXIT_CANCELED);
1090 #ifdef DAEMON_MUST_EXEC
1092 /* In orig process, forked as child, OR in exec'd. */
1093 if (!dname_arg || !strchr (dname_arg, '\n'))
1094 { /* In orig, child: now exec w/special daemon name. */
1095 char fdStr[80];
1096 int fdStrlen =
1097 snprintf (fdStr, sizeof fdStr,
1098 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1099 daemon_pipe[1], dname_arg ? dname_arg : "");
1101 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1103 fprintf (stderr, "daemon: child name too long\n");
1104 exit (EXIT_CANNOT_INVOKE);
1107 argv[skip_args] = fdStr;
1109 fcntl (daemon_pipe[0], F_SETFD, 0);
1110 fcntl (daemon_pipe[1], F_SETFD, 0);
1111 execvp (argv[0], argv);
1112 emacs_perror (argv[0]);
1113 exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1116 /* In exec'd: parse special dname into pipe and name info. */
1117 if (!dname_arg || !strchr (dname_arg, '\n')
1118 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1120 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1121 exit (EXIT_CANNOT_INVOKE);
1123 dname_arg2[0] = '\0';
1124 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1125 dname_arg2);
1126 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1127 fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
1129 #endif /* DAEMON_MUST_EXEC */
1131 if (dname_arg)
1132 daemon_name = xstrdup (dname_arg);
1133 /* Close unused reading end of the pipe. */
1134 emacs_close (daemon_pipe[0]);
1136 setsid ();
1137 #else /* DOS_NT */
1138 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1139 exit (1);
1140 #endif /* DOS_NT */
1143 #if defined HAVE_PTHREAD && !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC
1144 # ifndef CANNOT_DUMP
1145 /* Do not make gmalloc thread-safe when creating bootstrap-emacs, as
1146 that causes an infinite recursive loop with FreeBSD. But do make
1147 it thread-safe when creating emacs, otherwise bootstrap-emacs
1148 fails on Cygwin. See Bug#14569. */
1149 if (!noninteractive || initialized)
1150 # endif
1151 malloc_enable_thread ();
1152 #endif
1154 init_signals (dumping);
1156 noninteractive1 = noninteractive;
1158 /* Perform basic initializations (not merely interning symbols). */
1160 if (!initialized)
1162 init_alloc_once ();
1163 init_obarray ();
1164 init_eval_once ();
1165 init_charset_once ();
1166 init_coding_once ();
1167 init_syntax_once (); /* Create standard syntax table. */
1168 init_category_once (); /* Create standard category table. */
1169 init_casetab_once (); /* Must be done before init_buffer_once. */
1170 init_buffer_once (); /* Create buffer table and some buffers. */
1171 init_minibuf_once (); /* Create list of minibuffers. */
1172 /* Must precede init_window_once. */
1174 /* Call syms_of_xfaces before init_window_once because that
1175 function creates Vterminal_frame. Termcap frames now use
1176 faces, and the face implementation uses some symbols as
1177 face names. */
1178 syms_of_xfaces ();
1179 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1180 be better to arrange things not to have this dependency. */
1181 syms_of_keymap ();
1182 /* Call syms_of_keyboard before init_window_once because
1183 keyboard sets up symbols that include some face names that
1184 the X support will want to use. This can happen when
1185 CANNOT_DUMP is defined. */
1186 syms_of_keyboard ();
1188 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1189 syms_of_data ();
1190 syms_of_fns (); /* Before syms_of_charset which uses hashtables. */
1191 syms_of_fileio ();
1192 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1193 syms_of_alloc ();
1194 /* May call Ffuncall and so GC, thus the latter should be initialized. */
1195 init_print_once ();
1196 /* Before syms_of_coding because it initializes Qcharsetp. */
1197 syms_of_charset ();
1198 /* Before init_window_once, because it sets up the
1199 Vcoding_system_hash_table. */
1200 syms_of_coding (); /* This should be after syms_of_fileio. */
1202 init_window_once (); /* Init the window system. */
1203 #ifdef HAVE_WINDOW_SYSTEM
1204 init_fringe_once (); /* Swap bitmaps if necessary. */
1205 #endif /* HAVE_WINDOW_SYSTEM */
1208 init_alloc ();
1210 if (do_initial_setlocale)
1212 fixup_locale ();
1213 Vsystem_messages_locale = Vprevious_system_messages_locale;
1214 Vsystem_time_locale = Vprevious_system_time_locale;
1217 init_eval ();
1218 init_atimer ();
1219 running_asynch_code = 0;
1220 init_random ();
1222 no_loadup
1223 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1225 no_site_lisp
1226 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1228 #ifdef HAVE_NS
1229 ns_pool = ns_alloc_autorelease_pool ();
1230 #ifdef NS_IMPL_GNUSTEP
1231 /* GNUstep stupidly resets our locale settings after we made them. */
1232 fixup_locale ();
1233 #endif
1235 if (!noninteractive)
1237 #ifdef NS_IMPL_COCOA
1238 /* Started from GUI? */
1239 /* FIXME: Do the right thing if getenv returns NULL, or if
1240 chdir fails. */
1241 if (! inhibit_window_system && ! isatty (0) && ! ch_to_dir)
1242 chdir (getenv ("HOME"));
1243 if (skip_args < argc)
1245 if (!strncmp (argv[skip_args], "-psn", 4))
1247 skip_args += 1;
1248 if (! ch_to_dir) chdir (getenv ("HOME"));
1250 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1252 skip_args += 2;
1253 if (! ch_to_dir) chdir (getenv ("HOME"));
1256 #endif /* COCOA */
1258 #endif /* HAVE_NS */
1260 #ifdef HAVE_X_WINDOWS
1261 /* Stupid kludge to catch command-line display spec. We can't
1262 handle this argument entirely in window system dependent code
1263 because we don't even know which window system dependent code
1264 to run until we've recognized this argument. */
1266 char *displayname = 0;
1267 int count_before = skip_args;
1269 /* Skip any number of -d options, but only use the last one. */
1270 while (1)
1272 int count_before_this = skip_args;
1274 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1275 display_arg = 1;
1276 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1277 display_arg = 1;
1278 else
1279 break;
1281 count_before = count_before_this;
1284 /* If we have the form --display=NAME,
1285 convert it into -d name.
1286 This requires inserting a new element into argv. */
1287 if (displayname && count_before < skip_args)
1289 if (skip_args == count_before + 1)
1291 memmove (argv + count_before + 3, argv + count_before + 2,
1292 (argc - (count_before + 2)) * sizeof *argv);
1293 argv[count_before + 2] = displayname;
1294 argc++;
1296 argv[count_before + 1] = (char *) "-d";
1299 if (! no_site_lisp)
1301 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1302 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1303 no_site_lisp = 1;
1306 /* Don't actually discard this arg. */
1307 skip_args = count_before;
1309 #else /* !HAVE_X_WINDOWS */
1310 if (! no_site_lisp)
1312 int count_before = skip_args;
1314 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1315 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1316 no_site_lisp = 1;
1318 skip_args = count_before;
1320 #endif
1322 /* argmatch must not be used after here,
1323 except when building temacs
1324 because the -d argument has not been skipped in skip_args. */
1326 #ifdef MSDOS
1327 /* Call early 'cause init_environment needs it. */
1328 init_dosfns ();
1329 /* Set defaults for several environment variables. */
1330 if (initialized)
1331 init_environment (argc, argv, skip_args);
1332 else
1333 tzset ();
1334 #endif /* MSDOS */
1336 #ifdef HAVE_GFILENOTIFY
1337 globals_of_gfilenotify ();
1338 #endif
1340 #ifdef WINDOWSNT
1341 globals_of_w32 ();
1342 #ifdef HAVE_W32NOTIFY
1343 globals_of_w32notify ();
1344 #endif
1345 /* Initialize environment from registry settings. */
1346 init_environment (argv);
1347 init_ntproc (dumping); /* must precede init_editfns. */
1348 #endif
1350 /* Initialize and GC-protect Vinitial_environment and
1351 Vprocess_environment before set_initial_environment fills them
1352 in. */
1353 if (!initialized)
1354 syms_of_callproc ();
1355 /* egetenv is a pretty low-level facility, which may get called in
1356 many circumstances; it seems flimsy to put off initializing it
1357 until calling init_callproc. Do not do it when dumping. */
1358 if (! dumping)
1359 set_initial_environment ();
1361 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1362 if this is not done. Do it after set_global_environment so that we
1363 don't pollute Vglobal_environment. */
1364 /* Setting LANG here will defeat the startup locale processing... */
1365 #ifdef AIX
1366 xputenv ("LANG=C");
1367 #endif
1369 init_buffer (); /* Init default directory of main buffer. */
1371 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1373 /* Must precede init_lread. */
1374 init_cmdargs (argc, argv, skip_args, original_pwd);
1376 if (initialized)
1378 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1379 Lisp_Object old_log_max;
1380 old_log_max = Vmessage_log_max;
1381 XSETFASTINT (Vmessage_log_max, 0);
1382 message_dolog ("", 0, 1, 0);
1383 Vmessage_log_max = old_log_max;
1386 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1387 init_fileio ();
1388 init_lread ();
1389 #ifdef WINDOWSNT
1390 /* Check to see if Emacs has been installed correctly. */
1391 check_windows_init_file ();
1392 #endif
1394 /* Intern the names of all standard functions and variables;
1395 define standard keys. */
1397 if (!initialized)
1399 /* The basic levels of Lisp must come first. Note that
1400 syms_of_data and some others have already been called. */
1401 syms_of_chartab ();
1402 syms_of_lread ();
1403 syms_of_print ();
1404 syms_of_eval ();
1405 syms_of_floatfns ();
1407 syms_of_buffer ();
1408 syms_of_bytecode ();
1409 syms_of_callint ();
1410 syms_of_casefiddle ();
1411 syms_of_casetab ();
1412 syms_of_category ();
1413 syms_of_ccl ();
1414 syms_of_character ();
1415 syms_of_cmds ();
1416 syms_of_dired ();
1417 syms_of_display ();
1418 syms_of_doc ();
1419 syms_of_editfns ();
1420 syms_of_emacs ();
1421 syms_of_filelock ();
1422 syms_of_indent ();
1423 syms_of_insdel ();
1424 /* syms_of_keymap (); */
1425 syms_of_macros ();
1426 syms_of_marker ();
1427 syms_of_minibuf ();
1428 syms_of_process ();
1429 syms_of_search ();
1430 syms_of_frame ();
1431 syms_of_syntax ();
1432 syms_of_terminal ();
1433 syms_of_term ();
1434 syms_of_undo ();
1435 #ifdef HAVE_SOUND
1436 syms_of_sound ();
1437 #endif
1438 syms_of_textprop ();
1439 syms_of_composite ();
1440 #ifdef WINDOWSNT
1441 syms_of_ntproc ();
1442 #endif /* WINDOWSNT */
1443 #if defined CYGWIN
1444 syms_of_cygw32 ();
1445 #endif
1446 syms_of_window ();
1447 syms_of_xdisp ();
1448 syms_of_font ();
1449 #ifdef HAVE_WINDOW_SYSTEM
1450 syms_of_fringe ();
1451 syms_of_image ();
1452 #endif /* HAVE_WINDOW_SYSTEM */
1453 #ifdef HAVE_X_WINDOWS
1454 syms_of_xterm ();
1455 syms_of_xfns ();
1456 syms_of_xmenu ();
1457 syms_of_fontset ();
1458 syms_of_xsettings ();
1459 #ifdef HAVE_X_SM
1460 syms_of_xsmfns ();
1461 #endif
1462 #ifdef HAVE_X11
1463 syms_of_xselect ();
1464 #endif
1465 #endif /* HAVE_X_WINDOWS */
1467 #ifdef HAVE_LIBXML2
1468 syms_of_xml ();
1469 #endif
1471 #ifdef HAVE_ZLIB
1472 syms_of_decompress ();
1473 #endif
1475 syms_of_menu ();
1477 #ifdef HAVE_NTGUI
1478 syms_of_w32term ();
1479 syms_of_w32fns ();
1480 syms_of_w32menu ();
1481 syms_of_fontset ();
1482 #endif /* HAVE_NTGUI */
1484 #if defined WINDOWSNT || defined HAVE_NTGUI
1485 syms_of_w32select ();
1486 #endif
1488 #ifdef MSDOS
1489 syms_of_xmenu ();
1490 syms_of_dosfns ();
1491 syms_of_msdos ();
1492 syms_of_win16select ();
1493 #endif /* MSDOS */
1495 #ifdef HAVE_NS
1496 syms_of_nsterm ();
1497 syms_of_nsfns ();
1498 syms_of_nsmenu ();
1499 syms_of_nsselect ();
1500 syms_of_fontset ();
1501 #endif /* HAVE_NS */
1503 syms_of_gnutls ();
1505 #ifdef HAVE_GFILENOTIFY
1506 syms_of_gfilenotify ();
1507 #endif /* HAVE_GFILENOTIFY */
1509 #ifdef HAVE_INOTIFY
1510 syms_of_inotify ();
1511 #endif /* HAVE_INOTIFY */
1513 #ifdef HAVE_DBUS
1514 syms_of_dbusbind ();
1515 #endif /* HAVE_DBUS */
1517 #ifdef WINDOWSNT
1518 syms_of_ntterm ();
1519 #ifdef HAVE_W32NOTIFY
1520 syms_of_w32notify ();
1521 #endif /* HAVE_W32NOTIFY */
1522 #endif /* WINDOWSNT */
1524 syms_of_profiler ();
1526 keys_of_casefiddle ();
1527 keys_of_cmds ();
1528 keys_of_buffer ();
1529 keys_of_keyboard ();
1530 keys_of_keymap ();
1531 keys_of_window ();
1533 else
1535 /* Initialization that must be done even if the global variable
1536 initialized is non zero. */
1537 #ifdef HAVE_NTGUI
1538 globals_of_w32font ();
1539 globals_of_w32fns ();
1540 globals_of_w32menu ();
1541 #endif /* HAVE_NTGUI */
1543 #if defined WINDOWSNT || defined HAVE_NTGUI
1544 globals_of_w32select ();
1545 #endif
1548 init_charset ();
1550 init_editfns (); /* init_process_emacs uses Voperating_system_release. */
1551 init_process_emacs (); /* init_display uses add_keyboard_wait_descriptor. */
1552 init_keyboard (); /* This too must precede init_sys_modes. */
1553 if (!noninteractive)
1554 init_display (); /* Determine terminal type. Calls init_sys_modes. */
1555 #if HAVE_W32NOTIFY
1556 else
1557 init_crit (); /* w32notify.c needs this in batch mode. */
1558 #endif /* HAVE_W32NOTIFY */
1559 init_xdisp ();
1560 #ifdef HAVE_WINDOW_SYSTEM
1561 init_fringe ();
1562 #endif /* HAVE_WINDOW_SYSTEM */
1563 init_macros ();
1564 init_window ();
1565 init_font ();
1567 if (!initialized)
1569 char *file;
1570 /* Handle -l loadup, args passed by Makefile. */
1571 if (argmatch (argv, argc, "-l", "--load", 3, &file, &skip_args))
1573 #ifdef WINDOWSNT
1574 char file_utf8[MAX_UTF8_PATH];
1576 if (filename_from_ansi (file, file_utf8) == 0)
1577 file = file_utf8;
1578 #endif
1579 Vtop_level = list2 (intern_c_string ("load"),
1580 build_unibyte_string (file));
1582 /* Unless next switch is -nl, load "loadup.el" first thing. */
1583 if (! no_loadup)
1584 Vtop_level = list2 (intern_c_string ("load"),
1585 build_string ("loadup.el"));
1588 if (initialized)
1590 #ifdef HAVE_TZSET
1592 /* If the execution TZ happens to be the same as the dump TZ,
1593 change it to some other value and then change it back,
1594 to force the underlying implementation to reload the TZ info.
1595 This is needed on implementations that load TZ info from files,
1596 since the TZ file contents may differ between dump and execution. */
1597 char *tz = getenv ("TZ");
1598 if (tz && !strcmp (tz, dump_tz))
1600 ++*tz;
1601 tzset ();
1602 --*tz;
1605 #endif
1608 /* Set up for profiling. This is known to work on FreeBSD,
1609 GNU/Linux and MinGW. It might work on some other systems too.
1610 Give it a try and tell us if it works on your system. To compile
1611 for profiling, use the configure option --enable-profiling. */
1612 #if defined (__FreeBSD__) || defined (GNU_LINUX) || defined (__MINGW32__)
1613 #ifdef PROFILING
1614 if (initialized)
1616 #ifdef __MINGW32__
1617 extern unsigned char etext asm ("etext");
1618 #else
1619 extern char etext;
1620 #endif
1622 atexit (_mcleanup);
1623 monstartup ((uintptr_t) __executable_start, (uintptr_t) &etext);
1625 else
1626 moncontrol (0);
1627 #endif
1628 #endif
1630 initialized = 1;
1632 #ifdef LOCALTIME_CACHE
1633 /* Some versions of localtime have a bug. They cache the value of the time
1634 zone rather than looking it up every time. Since localtime() is
1635 called to bolt the undumping time into the undumped emacs, this
1636 results in localtime ignoring the TZ environment variable.
1637 This flushes the new TZ value into localtime. */
1638 tzset ();
1639 #endif /* defined (LOCALTIME_CACHE) */
1641 /* Enter editor command loop. This never returns. */
1642 Frecursive_edit ();
1643 /* NOTREACHED */
1644 return 0;
1647 /* Sort the args so we can find the most important ones
1648 at the beginning of argv. */
1650 /* First, here's a table of all the standard options. */
1652 struct standard_args
1654 const char *name;
1655 const char *longname;
1656 int priority;
1657 int nargs;
1660 static const struct standard_args standard_args[] =
1662 { "-version", "--version", 150, 0 },
1663 { "-chdir", "--chdir", 130, 1 },
1664 { "-t", "--terminal", 120, 1 },
1665 { "-nw", "--no-window-system", 110, 0 },
1666 { "-nw", "--no-windows", 110, 0 },
1667 { "-batch", "--batch", 100, 0 },
1668 { "-script", "--script", 100, 1 },
1669 { "-daemon", "--daemon", 99, 0 },
1670 { "-help", "--help", 90, 0 },
1671 { "-nl", "--no-loadup", 70, 0 },
1672 { "-nsl", "--no-site-lisp", 65, 0 },
1673 /* -d must come last before the options handled in startup.el. */
1674 { "-d", "--display", 60, 1 },
1675 { "-display", 0, 60, 1 },
1676 /* Now for the options handled in `command-line' (startup.el). */
1677 /* (Note that to imply -nsl, -Q is partially handled here.) */
1678 { "-Q", "--quick", 55, 0 },
1679 { "-quick", 0, 55, 0 },
1680 { "-q", "--no-init-file", 50, 0 },
1681 { "-no-init-file", 0, 50, 0 },
1682 { "-no-site-file", "--no-site-file", 40, 0 },
1683 { "-u", "--user", 30, 1 },
1684 { "-user", 0, 30, 1 },
1685 { "-debug-init", "--debug-init", 20, 0 },
1686 { "-iconic", "--iconic", 15, 0 },
1687 { "-D", "--basic-display", 12, 0},
1688 { "-basic-display", 0, 12, 0},
1689 { "-nbc", "--no-blinking-cursor", 12, 0 },
1690 /* Now for the options handled in `command-line-1' (startup.el). */
1691 { "-nbi", "--no-bitmap-icon", 10, 0 },
1692 { "-bg", "--background-color", 10, 1 },
1693 { "-background", 0, 10, 1 },
1694 { "-fg", "--foreground-color", 10, 1 },
1695 { "-foreground", 0, 10, 1 },
1696 { "-bd", "--border-color", 10, 1 },
1697 { "-bw", "--border-width", 10, 1 },
1698 { "-ib", "--internal-border", 10, 1 },
1699 { "-ms", "--mouse-color", 10, 1 },
1700 { "-cr", "--cursor-color", 10, 1 },
1701 { "-fn", "--font", 10, 1 },
1702 { "-font", 0, 10, 1 },
1703 { "-fs", "--fullscreen", 10, 0 },
1704 { "-fw", "--fullwidth", 10, 0 },
1705 { "-fh", "--fullheight", 10, 0 },
1706 { "-mm", "--maximized", 10, 0 },
1707 { "-g", "--geometry", 10, 1 },
1708 { "-geometry", 0, 10, 1 },
1709 { "-T", "--title", 10, 1 },
1710 { "-title", 0, 10, 1 },
1711 { "-name", "--name", 10, 1 },
1712 { "-xrm", "--xrm", 10, 1 },
1713 { "-parent-id", "--parent-id", 10, 1 },
1714 { "-r", "--reverse-video", 5, 0 },
1715 { "-rv", 0, 5, 0 },
1716 { "-reverse", 0, 5, 0 },
1717 { "-hb", "--horizontal-scroll-bars", 5, 0 },
1718 { "-vb", "--vertical-scroll-bars", 5, 0 },
1719 { "-color", "--color", 5, 0},
1720 { "-no-splash", "--no-splash", 3, 0 },
1721 { "-no-desktop", "--no-desktop", 3, 0 },
1722 #ifdef HAVE_NS
1723 { "-NSAutoLaunch", 0, 5, 1 },
1724 { "-NXAutoLaunch", 0, 5, 1 },
1725 { "-_NSMachLaunch", 0, 85, 1 },
1726 { "-MachLaunch", 0, 85, 1 },
1727 { "-macosx", 0, 85, 0 },
1728 { "-NSHost", 0, 85, 1 },
1729 #endif
1730 /* These have the same priority as ordinary file name args,
1731 so they are not reordered with respect to those. */
1732 { "-L", "--directory", 0, 1 },
1733 { "-directory", 0, 0, 1 },
1734 { "-l", "--load", 0, 1 },
1735 { "-load", 0, 0, 1 },
1736 /* This has no longname, because using --scriptload confuses sort_args,
1737 because then the --script long option seems to match twice; ie
1738 you can't have a long option which is a prefix of another long
1739 option. In any case, this is entirely an internal option. */
1740 { "-scriptload", NULL, 0, 1 },
1741 { "-f", "--funcall", 0, 1 },
1742 { "-funcall", 0, 0, 1 },
1743 { "-eval", "--eval", 0, 1 },
1744 { "-execute", "--execute", 0, 1 },
1745 { "-find-file", "--find-file", 0, 1 },
1746 { "-visit", "--visit", 0, 1 },
1747 { "-file", "--file", 0, 1 },
1748 { "-insert", "--insert", 0, 1 },
1749 #ifdef HAVE_NS
1750 { "-NXOpen", 0, 0, 1 },
1751 { "-NXOpenTemp", 0, 0, 1 },
1752 { "-NSOpen", 0, 0, 1 },
1753 { "-NSOpenTemp", 0, 0, 1 },
1754 { "-GSFilePath", 0, 0, 1 },
1755 #endif
1756 /* This should be processed after ordinary file name args and the like. */
1757 { "-kill", "--kill", -10, 0 },
1760 /* Reorder the elements of ARGV (assumed to have ARGC elements)
1761 so that the highest priority ones come first.
1762 Do not change the order of elements of equal priority.
1763 If an option takes an argument, keep it and its argument together.
1765 If an option that takes no argument appears more
1766 than once, eliminate all but one copy of it. */
1768 static void
1769 sort_args (int argc, char **argv)
1771 char **new = xmalloc (argc * sizeof *new);
1772 /* For each element of argv,
1773 the corresponding element of options is:
1774 0 for an option that takes no arguments,
1775 1 for an option that takes one argument, etc.
1776 -1 for an ordinary non-option argument. */
1777 int *options = xnmalloc (argc, sizeof *options);
1778 int *priority = xnmalloc (argc, sizeof *priority);
1779 int to = 1;
1780 int incoming_used = 1;
1781 int from;
1782 int i;
1784 /* Categorize all the options,
1785 and figure out which argv elts are option arguments. */
1786 for (from = 1; from < argc; from++)
1788 options[from] = -1;
1789 priority[from] = 0;
1790 if (argv[from][0] == '-')
1792 int match;
1794 /* If we have found "--", don't consider
1795 any more arguments as options. */
1796 if (argv[from][1] == '-' && argv[from][2] == 0)
1798 /* Leave the "--", and everything following it, at the end. */
1799 for (; from < argc; from++)
1801 priority[from] = -100;
1802 options[from] = -1;
1804 break;
1807 /* Look for a match with a known old-fashioned option. */
1808 for (i = 0; i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1809 if (!strcmp (argv[from], standard_args[i].name))
1811 options[from] = standard_args[i].nargs;
1812 priority[from] = standard_args[i].priority;
1813 if (from + standard_args[i].nargs >= argc)
1814 fatal ("Option `%s' requires an argument\n", argv[from]);
1815 from += standard_args[i].nargs;
1816 goto done;
1819 /* Look for a match with a known long option.
1820 MATCH is -1 if no match so far, -2 if two or more matches so far,
1821 >= 0 (the table index of the match) if just one match so far. */
1822 if (argv[from][1] == '-')
1824 char const *equals = strchr (argv[from], '=');
1825 ptrdiff_t thislen =
1826 equals ? equals - argv[from] : strlen (argv[from]);
1828 match = -1;
1830 for (i = 0;
1831 i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1832 if (standard_args[i].longname
1833 && !strncmp (argv[from], standard_args[i].longname,
1834 thislen))
1836 if (match == -1)
1837 match = i;
1838 else
1839 match = -2;
1842 /* If we found exactly one match, use that. */
1843 if (match >= 0)
1845 options[from] = standard_args[match].nargs;
1846 priority[from] = standard_args[match].priority;
1847 /* If --OPTION=VALUE syntax is used,
1848 this option uses just one argv element. */
1849 if (equals != 0)
1850 options[from] = 0;
1851 if (from + options[from] >= argc)
1852 fatal ("Option `%s' requires an argument\n", argv[from]);
1853 from += options[from];
1855 /* FIXME When match < 0, shouldn't there be some error,
1856 or at least indication to the user that there was a
1857 problem? */
1859 done: ;
1863 /* Copy the arguments, in order of decreasing priority, to NEW. */
1864 new[0] = argv[0];
1865 while (incoming_used < argc)
1867 int best = -1;
1868 int best_priority = -9999;
1870 /* Find the highest priority remaining option.
1871 If several have equal priority, take the first of them. */
1872 for (from = 1; from < argc; from++)
1874 if (argv[from] != 0 && priority[from] > best_priority)
1876 best_priority = priority[from];
1877 best = from;
1879 /* Skip option arguments--they are tied to the options. */
1880 if (options[from] > 0)
1881 from += options[from];
1884 if (best < 0)
1885 emacs_abort ();
1887 /* Copy the highest priority remaining option, with its args, to NEW.
1888 Unless it is a duplicate of the previous one. */
1889 if (! (options[best] == 0
1890 && ! strcmp (new[to - 1], argv[best])))
1892 new[to++] = argv[best];
1893 for (i = 0; i < options[best]; i++)
1894 new[to++] = argv[best + i + 1];
1897 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1899 /* Clear out this option in ARGV. */
1900 argv[best] = 0;
1901 for (i = 0; i < options[best]; i++)
1902 argv[best + i + 1] = 0;
1905 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1906 while (to < argc)
1907 new[to++] = 0;
1909 memcpy (argv, new, sizeof (char *) * argc);
1911 xfree (options);
1912 xfree (new);
1913 xfree (priority);
1916 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1917 doc: /* Exit the Emacs job and kill it.
1918 If ARG is an integer, return ARG as the exit program code.
1919 If ARG is a string, stuff it as keyboard input.
1921 This function is called upon receipt of the signals SIGTERM
1922 or SIGHUP, and upon SIGINT in batch mode.
1924 The value of `kill-emacs-hook', if not void,
1925 is a list of functions (of no args),
1926 all of which are called before Emacs is actually killed. */)
1927 (Lisp_Object arg)
1929 struct gcpro gcpro1;
1930 int exit_code;
1932 GCPRO1 (arg);
1934 if (feof (stdin))
1935 arg = Qt;
1937 /* Fsignal calls emacs_abort () if it sees that waiting_for_input is
1938 set. */
1939 waiting_for_input = 0;
1940 Frun_hooks (1, &Qkill_emacs_hook);
1941 UNGCPRO;
1943 #ifdef HAVE_X_WINDOWS
1944 /* Transfer any clipboards we own to the clipboard manager. */
1945 x_clipboard_manager_save_all ();
1946 #endif
1948 shut_down_emacs (0, STRINGP (arg) ? arg : Qnil);
1950 #ifdef HAVE_NS
1951 ns_release_autorelease_pool (ns_pool);
1952 #endif
1954 /* If we have an auto-save list file,
1955 kill it because we are exiting Emacs deliberately (not crashing).
1956 Do it after shut_down_emacs, which does an auto-save. */
1957 if (STRINGP (Vauto_save_list_file_name))
1959 Lisp_Object listfile;
1960 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
1961 unlink (SSDATA (listfile));
1964 if (INTEGERP (arg))
1965 exit_code = (XINT (arg) < 0
1966 ? XINT (arg) | INT_MIN
1967 : XINT (arg) & INT_MAX);
1968 else
1969 exit_code = EXIT_SUCCESS;
1970 exit (exit_code);
1974 /* Perform an orderly shutdown of Emacs. Autosave any modified
1975 buffers, kill any child processes, clean up the terminal modes (if
1976 we're in the foreground), and other stuff like that. Don't perform
1977 any redisplay; this may be called when Emacs is shutting down in
1978 the background, or after its X connection has died.
1980 If SIG is a signal number, print a message for it.
1982 This is called by fatal signal handlers, X protocol error handlers,
1983 and Fkill_emacs. */
1985 void
1986 shut_down_emacs (int sig, Lisp_Object stuff)
1988 /* Prevent running of hooks from now on. */
1989 Vrun_hooks = Qnil;
1991 /* Don't update display from now on. */
1992 Vinhibit_redisplay = Qt;
1994 /* If we are controlling the terminal, reset terminal modes. */
1995 #ifndef DOS_NT
1997 pid_t pgrp = getpgrp ();
1998 pid_t tpgrp = tcgetpgrp (0);
1999 if ((tpgrp != -1) && tpgrp == pgrp)
2001 reset_all_sys_modes ();
2002 if (sig && sig != SIGTERM)
2004 static char const format[] = "Fatal error %d: ";
2005 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
2006 int buflen = sprintf (buf, format, sig);
2007 char const *sig_desc = safe_strsignal (sig);
2008 emacs_write (STDERR_FILENO, buf, buflen);
2009 emacs_write (STDERR_FILENO, sig_desc, strlen (sig_desc));
2013 #else
2014 fflush (stdout);
2015 reset_all_sys_modes ();
2016 #endif
2018 stuff_buffered_input (stuff);
2020 inhibit_sentinels = 1;
2021 kill_buffer_processes (Qnil);
2022 Fdo_auto_save (Qt, Qnil);
2024 #ifdef CLASH_DETECTION
2025 unlock_all_files ();
2026 #endif
2028 /* There is a tendency for a SIGIO signal to arrive within exit,
2029 and cause a SIGHUP because the input descriptor is already closed. */
2030 unrequest_sigio ();
2031 ignore_sigio ();
2033 /* Do this only if terminating normally, we want glyph matrices
2034 etc. in a core dump. */
2035 if (sig == 0 || sig == SIGTERM)
2037 check_glyph_memory ();
2038 check_message_stack ();
2041 #ifdef MSDOS
2042 dos_cleanup ();
2043 #endif
2045 #ifdef HAVE_NS
2046 ns_term_shutdown (sig);
2047 #endif
2049 #ifdef HAVE_LIBXML2
2050 xml_cleanup_parser ();
2051 #endif
2053 #ifdef WINDOWSNT
2054 term_ntproc (0);
2055 #endif
2060 #ifndef CANNOT_DUMP
2062 #include "unexec.h"
2064 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
2065 doc: /* Dump current state of Emacs into executable file FILENAME.
2066 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
2067 This is used in the file `loadup.el' when building Emacs.
2069 You must run Emacs in batch mode in order to dump it. */)
2070 (Lisp_Object filename, Lisp_Object symfile)
2072 Lisp_Object tem;
2073 Lisp_Object symbol;
2074 ptrdiff_t count = SPECPDL_INDEX ();
2076 check_pure_size ();
2078 if (! noninteractive)
2079 error ("Dumping Emacs works only in batch mode");
2081 #ifdef GNU_LINUX
2083 /* Warn if the gap between BSS end and heap start is larger than this. */
2084 # define MAX_HEAP_BSS_DIFF (1024*1024)
2086 if (heap_bss_diff > MAX_HEAP_BSS_DIFF)
2088 fprintf (stderr, "**************************************************\n");
2089 fprintf (stderr, "Warning: Your system has a gap between BSS and the\n");
2090 fprintf (stderr, "heap (%"pMu" bytes). This usually means that exec-shield\n",
2091 heap_bss_diff);
2092 fprintf (stderr, "or something similar is in effect. The dump may\n");
2093 fprintf (stderr, "fail because of this. See the section about\n");
2094 fprintf (stderr, "exec-shield in etc/PROBLEMS for more information.\n");
2095 fprintf (stderr, "**************************************************\n");
2097 #endif /* GNU_LINUX */
2099 /* Bind `command-line-processed' to nil before dumping,
2100 so that the dumped Emacs will process its command line
2101 and set up to work with X windows if appropriate. */
2102 symbol = intern ("command-line-processed");
2103 specbind (symbol, Qnil);
2105 CHECK_STRING (filename);
2106 filename = Fexpand_file_name (filename, Qnil);
2107 filename = ENCODE_FILE (filename);
2108 if (!NILP (symfile))
2110 CHECK_STRING (symfile);
2111 if (SCHARS (symfile))
2113 symfile = Fexpand_file_name (symfile, Qnil);
2114 symfile = ENCODE_FILE (symfile);
2118 tem = Vpurify_flag;
2119 Vpurify_flag = Qnil;
2121 #ifdef HAVE_TZSET
2122 set_time_zone_rule (dump_tz);
2123 #ifndef LOCALTIME_CACHE
2124 /* Force a tz reload, since set_time_zone_rule doesn't. */
2125 tzset ();
2126 #endif
2127 #endif
2129 fflush (stdout);
2130 /* Tell malloc where start of impure now is. */
2131 /* Also arrange for warnings when nearly out of space. */
2132 #ifndef SYSTEM_MALLOC
2133 #ifndef WINDOWSNT
2134 /* On Windows, this was done before dumping, and that once suffices.
2135 Meanwhile, my_edata is not valid on Windows. */
2137 extern char my_edata[];
2138 memory_warnings (my_edata, malloc_warning);
2140 #endif /* not WINDOWSNT */
2141 #endif /* not SYSTEM_MALLOC */
2142 #ifdef DOUG_LEA_MALLOC
2143 malloc_state_ptr = malloc_get_state ();
2144 #endif
2146 #ifdef USE_MMAP_FOR_BUFFERS
2147 mmap_set_vars (0);
2148 #endif
2149 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2150 #ifdef USE_MMAP_FOR_BUFFERS
2151 mmap_set_vars (1);
2152 #endif
2153 #ifdef DOUG_LEA_MALLOC
2154 free (malloc_state_ptr);
2155 #endif
2157 #ifdef WINDOWSNT
2158 Vlibrary_cache = Qnil;
2159 #endif
2160 #ifdef HAVE_WINDOW_SYSTEM
2161 reset_image_types ();
2162 #endif
2164 Vpurify_flag = tem;
2166 return unbind_to (count, Qnil);
2169 #endif /* not CANNOT_DUMP */
2171 #if HAVE_SETLOCALE
2172 /* Recover from setlocale (LC_ALL, ""). */
2173 void
2174 fixup_locale (void)
2176 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2177 so that numbers are read and printed properly for Emacs Lisp. */
2178 setlocale (LC_NUMERIC, "C");
2181 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2182 DESIRED_LOCALE. */
2183 static void
2184 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2186 if (! EQ (*plocale, desired_locale))
2188 *plocale = desired_locale;
2189 setlocale (category, (STRINGP (desired_locale)
2190 ? SSDATA (desired_locale)
2191 : ""));
2195 /* Set system time locale to match Vsystem_time_locale, if possible. */
2196 void
2197 synchronize_system_time_locale (void)
2199 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2200 Vsystem_time_locale);
2203 /* Set system messages locale to match Vsystem_messages_locale, if
2204 possible. */
2205 void
2206 synchronize_system_messages_locale (void)
2208 #ifdef LC_MESSAGES
2209 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2210 Vsystem_messages_locale);
2211 #endif
2213 #endif /* HAVE_SETLOCALE */
2216 Lisp_Object
2217 decode_env_path (const char *evarname, const char *defalt, bool empty)
2219 const char *path, *p;
2220 Lisp_Object lpath, element, tem;
2221 /* Default is to use "." for empty path elements.
2222 But if argument EMPTY is true, use nil instead. */
2223 Lisp_Object empty_element = empty ? Qnil : build_string (".");
2224 #ifdef WINDOWSNT
2225 bool defaulted = 0;
2226 static const char *emacs_dir_env = "%emacs_dir%/";
2227 const size_t emacs_dir_len = strlen (emacs_dir_env);
2228 const char *edir = egetenv ("emacs_dir");
2229 char emacs_dir[MAX_UTF8_PATH];
2231 /* egetenv looks in process-environment, which holds the variables
2232 in their original system-locale encoding. We need emacs_dir to
2233 be in UTF-8. */
2234 if (edir)
2235 filename_from_ansi (edir, emacs_dir);
2236 #endif
2238 /* It's okay to use getenv here, because this function is only used
2239 to initialize variables when Emacs starts up, and isn't called
2240 after that. */
2241 if (evarname != 0)
2242 path = getenv (evarname);
2243 else
2244 path = 0;
2245 if (!path)
2247 path = defalt;
2248 #ifdef WINDOWSNT
2249 defaulted = 1;
2250 #endif
2252 #ifdef DOS_NT
2253 /* Ensure values from the environment use the proper directory separator. */
2254 if (path)
2256 char *path_copy;
2258 #ifdef WINDOWSNT
2259 char *path_utf8, *q, *d;
2260 int cnv_result;
2262 /* Convert each element of PATH to UTF-8. */
2263 p = path_copy = alloca (strlen (path) + 1);
2264 strcpy (path_copy, path);
2265 d = path_utf8 = alloca (4 * strlen (path) + 1);
2266 *d = '\0';
2267 do {
2268 q = _mbschr (p, SEPCHAR);
2269 if (q)
2270 *q = '\0';
2271 cnv_result = filename_from_ansi (p, d);
2272 if (q)
2274 *q++ = SEPCHAR;
2275 p = q;
2276 /* If conversion of this PATH elements fails, make sure
2277 destination pointer will stay put, thus effectively
2278 ignoring the offending element. */
2279 if (cnv_result == 0)
2281 d += strlen (d);
2282 *d++ = SEPCHAR;
2285 else if (cnv_result != 0 && d > path_utf8)
2286 d[-1] = '\0'; /* remove last semi-colon and null-terminate PATH */
2287 } while (q);
2288 path_copy = path_utf8;
2289 #else /* MSDOS */
2290 path_copy = alloca (strlen (path) + 1);
2291 strcpy (path_copy, path);
2292 #endif
2293 dostounix_filename (path_copy);
2294 path = path_copy;
2296 #endif
2297 lpath = Qnil;
2298 while (1)
2300 p = strchr (path, SEPCHAR);
2301 if (!p)
2302 p = path + strlen (path);
2303 element = (p - path ? make_unibyte_string (path, p - path)
2304 : empty_element);
2305 if (! NILP (element))
2307 #ifdef WINDOWSNT
2308 /* Relative file names in the default path are interpreted as
2309 being relative to $emacs_dir. */
2310 if (edir && defaulted
2311 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2312 element = Fexpand_file_name (Fsubstring
2313 (element,
2314 make_number (emacs_dir_len),
2315 Qnil),
2316 build_unibyte_string (emacs_dir));
2317 #endif
2319 /* Add /: to the front of the name
2320 if it would otherwise be treated as magic. */
2321 tem = Ffind_file_name_handler (element, Qt);
2323 /* However, if the handler says "I'm safe",
2324 don't bother adding /:. */
2325 if (SYMBOLP (tem))
2327 Lisp_Object prop;
2328 prop = Fget (tem, intern ("safe-magic"));
2329 if (! NILP (prop))
2330 tem = Qnil;
2333 if (! NILP (tem))
2334 element = concat2 (build_string ("/:"), element);
2335 } /* !NILP (element) */
2337 lpath = Fcons (element, lpath);
2338 if (*p)
2339 path = p + 1;
2340 else
2341 break;
2343 return Fnreverse (lpath);
2346 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2347 doc: /* Return non-nil if the current emacs process is a daemon.
2348 If the daemon was given a name argument, return that name. */)
2349 (void)
2351 if (IS_DAEMON)
2352 if (daemon_name)
2353 return build_string (daemon_name);
2354 else
2355 return Qt;
2356 else
2357 return Qnil;
2360 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2361 doc: /* Mark the Emacs daemon as being initialized.
2362 This finishes the daemonization process by doing the other half of detaching
2363 from the parent process and its tty file descriptors. */)
2364 (void)
2366 int nfd;
2367 bool err = 0;
2369 if (!IS_DAEMON)
2370 error ("This function can only be called if emacs is run as a daemon");
2372 if (daemon_pipe[1] < 0)
2373 error ("The daemon has already been initialized");
2375 if (NILP (Vafter_init_time))
2376 error ("This function can only be called after loading the init files");
2378 /* Get rid of stdin, stdout and stderr. */
2379 nfd = emacs_open ("/dev/null", O_RDWR, 0);
2380 err |= nfd < 0;
2381 err |= dup2 (nfd, 0) < 0;
2382 err |= dup2 (nfd, 1) < 0;
2383 err |= dup2 (nfd, 2) < 0;
2384 err |= emacs_close (nfd) != 0;
2386 /* Closing the pipe will notify the parent that it can exit.
2387 FIXME: In case some other process inherited the pipe, closing it here
2388 won't notify the parent because it's still open elsewhere, so we
2389 additionally send a byte, just to make sure the parent really exits.
2390 Instead, we should probably close the pipe in start-process and
2391 call-process to make sure the pipe is never inherited by
2392 subprocesses. */
2393 err |= write (daemon_pipe[1], "\n", 1) < 0;
2394 err |= emacs_close (daemon_pipe[1]) != 0;
2395 /* Set it to an invalid value so we know we've already run this function. */
2396 daemon_pipe[1] = -1;
2398 if (err)
2399 error ("I/O error during daemon initialization");
2400 return Qt;
2403 void
2404 syms_of_emacs (void)
2406 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2407 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2408 DEFSYM (Qkill_emacs, "kill-emacs");
2409 DEFSYM (Qkill_emacs_hook, "kill-emacs-hook");
2411 #ifndef CANNOT_DUMP
2412 defsubr (&Sdump_emacs);
2413 #endif
2415 defsubr (&Skill_emacs);
2417 defsubr (&Sinvocation_name);
2418 defsubr (&Sinvocation_directory);
2419 defsubr (&Sdaemonp);
2420 defsubr (&Sdaemon_initialized);
2422 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2423 doc: /* Args passed by shell to Emacs, as a list of strings.
2424 Many arguments are deleted from the list as they are processed. */);
2426 DEFVAR_LISP ("system-type", Vsystem_type,
2427 doc: /* The value is a symbol indicating the type of operating system you are using.
2428 Special values:
2429 `gnu' compiled for a GNU Hurd system.
2430 `gnu/linux' compiled for a GNU/Linux system.
2431 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2432 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2433 `ms-dos' compiled as an MS-DOS application.
2434 `windows-nt' compiled as a native W32 application.
2435 `cygwin' compiled using the Cygwin library.
2436 Anything else (in Emacs 24.1, the possibilities are: aix, berkeley-unix,
2437 hpux, irix, usg-unix-v) indicates some sort of Unix system. */);
2438 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2439 /* See configure.ac (and config.nt) for the possible SYSTEM_TYPEs. */
2441 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2442 doc: /* Value is string indicating configuration Emacs was built for.
2443 On MS-Windows, the value reflects the OS flavor and version on which
2444 Emacs is running. */);
2445 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2447 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2448 doc: /* String containing the configuration options Emacs was built with. */);
2449 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2451 DEFVAR_BOOL ("noninteractive", noninteractive1,
2452 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2454 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2455 doc: /* Hook run when `kill-emacs' is called.
2456 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2457 in other similar situations), functions placed on this hook should not
2458 expect to be able to interact with the user. To ask for confirmation,
2459 see `kill-emacs-query-functions' instead.
2461 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2462 `noninteractive' was non-nil. */);
2463 Vkill_emacs_hook = Qnil;
2465 DEFVAR_LISP ("path-separator", Vpath_separator,
2466 doc: /* String containing the character that separates directories in
2467 search paths, such as PATH and other similar environment variables. */);
2469 char c = SEPCHAR;
2470 Vpath_separator = make_string (&c, 1);
2473 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2474 doc: /* The program name that was used to run Emacs.
2475 Any directory names are omitted. */);
2477 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2478 doc: /* The directory in which the Emacs executable was found, to run it.
2479 The value is nil if that directory's name is not known. */);
2481 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2482 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2483 In an installed Emacs, this is normally nil. It is non-nil if
2484 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2485 within the variable `invocation-directory' or its parent. For example,
2486 this is the case when running an uninstalled Emacs executable from its
2487 build directory. */);
2488 Vinstallation_directory = Qnil;
2490 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2491 doc: /* System locale for messages. */);
2492 Vsystem_messages_locale = Qnil;
2494 DEFVAR_LISP ("previous-system-messages-locale",
2495 Vprevious_system_messages_locale,
2496 doc: /* Most recently used system locale for messages. */);
2497 Vprevious_system_messages_locale = Qnil;
2499 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2500 doc: /* System locale for time. */);
2501 Vsystem_time_locale = Qnil;
2503 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2504 doc: /* Most recently used system locale for time. */);
2505 Vprevious_system_time_locale = Qnil;
2507 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2508 doc: /* Value of `current-time' before Emacs begins initialization. */);
2509 Vbefore_init_time = Qnil;
2511 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2512 doc: /* Value of `current-time' after loading the init files.
2513 This is nil during initialization. */);
2514 Vafter_init_time = Qnil;
2516 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2517 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2518 inhibit_x_resources = 0;
2520 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2521 doc: /* Short copyright string for this version of Emacs. */);
2522 Vemacs_copyright = build_string (emacs_copyright);
2524 DEFVAR_LISP ("emacs-version", Vemacs_version,
2525 doc: /* Version numbers of this version of Emacs. */);
2526 Vemacs_version = build_string (emacs_version);
2528 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2529 doc: /* Alist of dynamic libraries vs external files implementing them.
2530 Each element is a list (LIBRARY FILE...), where the car is a symbol
2531 representing a supported external library, and the rest are strings giving
2532 alternate filenames for that library.
2534 Emacs tries to load the library from the files in the order they appear on
2535 the list; if none is loaded, the running session of Emacs won't have access
2536 to that library.
2538 Note that image types `pbm' and `xbm' do not need entries in this variable
2539 because they do not depend on external libraries and are always available.
2541 Also note that this is not a generic facility for accessing external
2542 libraries; only those already known by Emacs will be loaded. */);
2543 Vdynamic_library_alist = Qnil;
2544 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2546 #ifdef WINDOWSNT
2547 Vlibrary_cache = Qnil;
2548 staticpro (&Vlibrary_cache);
2549 #endif