Remove unused variable EMACS_HEAPSIZE from src/Makefile.in.
[emacs.git] / src / emacs.c
blob9b05d68b91421b7b5e1100d05974f500398715e9
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 register int i;
400 Lisp_Object name, dir, handler;
401 ptrdiff_t count = SPECPDL_INDEX ();
402 Lisp_Object raw_name;
404 initial_argv = argv;
405 initial_argc = argc;
407 #ifdef WINDOWSNT
408 /* Must use argv[0] converted to UTF-8, as it begets many standard
409 file and directory names. */
411 char argv0[MAX_UTF8_PATH];
413 if (filename_from_ansi (argv[0], argv0) == 0)
414 raw_name = build_unibyte_string (argv0);
415 else
416 raw_name = build_unibyte_string (argv[0]);
418 #else
419 raw_name = build_unibyte_string (argv[0]);
420 #endif
422 /* Add /: to the front of the name
423 if it would otherwise be treated as magic. */
424 handler = Ffind_file_name_handler (raw_name, Qt);
425 if (! NILP (handler))
426 raw_name = concat2 (build_string ("/:"), raw_name);
428 Vinvocation_name = Ffile_name_nondirectory (raw_name);
429 Vinvocation_directory = Ffile_name_directory (raw_name);
431 /* If we got no directory in argv[0], search PATH to find where
432 Emacs actually came from. */
433 if (NILP (Vinvocation_directory))
435 Lisp_Object found;
436 int yes = openp (Vexec_path, Vinvocation_name,
437 Vexec_suffixes, &found, make_number (X_OK), false);
438 if (yes == 1)
440 /* Add /: to the front of the name
441 if it would otherwise be treated as magic. */
442 handler = Ffind_file_name_handler (found, Qt);
443 if (! NILP (handler))
444 found = concat2 (build_string ("/:"), found);
445 Vinvocation_directory = Ffile_name_directory (found);
449 if (!NILP (Vinvocation_directory)
450 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
451 /* Emacs was started with relative path, like ./emacs.
452 Make it absolute. */
454 Lisp_Object odir =
455 original_pwd ? build_unibyte_string (original_pwd) : Qnil;
457 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, odir);
460 Vinstallation_directory = Qnil;
462 if (!NILP (Vinvocation_directory))
464 dir = Vinvocation_directory;
465 #ifdef WINDOWSNT
466 /* If we are running from the build directory, set DIR to the
467 src subdirectory of the Emacs tree, like on Posix
468 platforms. */
469 if (SBYTES (dir) > sizeof ("/i386/") - 1
470 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
471 "/i386/"))
472 dir = Fexpand_file_name (build_string ("../.."), dir);
473 #else /* !WINDOWSNT */
474 #endif
475 name = Fexpand_file_name (Vinvocation_name, dir);
476 while (1)
478 Lisp_Object tem, lib_src_exists;
479 Lisp_Object etc_exists, info_exists;
481 /* See if dir contains subdirs for use by Emacs.
482 Check for the ones that would exist in a build directory,
483 not including lisp and info. */
484 tem = Fexpand_file_name (build_string ("lib-src"), dir);
485 lib_src_exists = Ffile_exists_p (tem);
487 #ifdef MSDOS
488 /* MSDOS installations frequently remove lib-src, but we still
489 must set installation-directory, or else info won't find
490 its files (it uses the value of installation-directory). */
491 tem = Fexpand_file_name (build_string ("info"), dir);
492 info_exists = Ffile_exists_p (tem);
493 #else
494 info_exists = Qnil;
495 #endif
497 if (!NILP (lib_src_exists) || !NILP (info_exists))
499 tem = Fexpand_file_name (build_string ("etc"), dir);
500 etc_exists = Ffile_exists_p (tem);
501 if (!NILP (etc_exists))
503 Vinstallation_directory
504 = Ffile_name_as_directory (dir);
505 break;
509 /* See if dir's parent contains those subdirs. */
510 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
511 lib_src_exists = Ffile_exists_p (tem);
514 #ifdef MSDOS
515 /* See the MSDOS commentary above. */
516 tem = Fexpand_file_name (build_string ("../info"), dir);
517 info_exists = Ffile_exists_p (tem);
518 #else
519 info_exists = Qnil;
520 #endif
522 if (!NILP (lib_src_exists) || !NILP (info_exists))
524 tem = Fexpand_file_name (build_string ("../etc"), dir);
525 etc_exists = Ffile_exists_p (tem);
526 if (!NILP (etc_exists))
528 tem = Fexpand_file_name (build_string (".."), dir);
529 Vinstallation_directory
530 = Ffile_name_as_directory (tem);
531 break;
535 /* If the Emacs executable is actually a link,
536 next try the dir that the link points into. */
537 tem = Ffile_symlink_p (name);
538 if (!NILP (tem))
540 name = Fexpand_file_name (tem, dir);
541 dir = Ffile_name_directory (name);
543 else
544 break;
548 Vcommand_line_args = Qnil;
550 for (i = argc - 1; i >= 0; i--)
552 if (i == 0 || i > skip_args)
553 /* For the moment, we keep arguments as is in unibyte strings.
554 They are decoded in the function command-line after we know
555 locale-coding-system. */
556 Vcommand_line_args
557 = Fcons (build_unibyte_string (argv[i]), Vcommand_line_args);
560 unbind_to (count, Qnil);
563 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
564 doc: /* Return the program name that was used to run Emacs.
565 Any directory names are omitted. */)
566 (void)
568 return Fcopy_sequence (Vinvocation_name);
571 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
572 0, 0, 0,
573 doc: /* Return the directory name in which the Emacs executable was located. */)
574 (void)
576 return Fcopy_sequence (Vinvocation_directory);
580 #ifdef HAVE_TZSET
581 /* A valid but unlikely value for the TZ environment value.
582 It is OK (though a bit slower) if the user actually chooses this value. */
583 static char const dump_tz[] = "UtC0";
584 #endif
586 /* Test whether the next argument in ARGV matches SSTR or a prefix of
587 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
588 (the argument is supposed to have a value) store in *VALPTR either
589 the next argument or the portion of this one after the equal sign.
590 ARGV is read starting at position *SKIPPTR; this index is advanced
591 by the number of arguments used.
593 Too bad we can't just use getopt for all of this, but we don't have
594 enough information to do it right. */
596 static bool
597 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
598 int minlen, char **valptr, int *skipptr)
600 char *p = NULL;
601 ptrdiff_t arglen;
602 char *arg;
604 /* Don't access argv[argc]; give up in advance. */
605 if (argc <= *skipptr + 1)
606 return 0;
608 arg = argv[*skipptr+1];
609 if (arg == NULL)
610 return 0;
611 if (strcmp (arg, sstr) == 0)
613 if (valptr != NULL)
615 *valptr = argv[*skipptr+2];
616 *skipptr += 2;
618 else
619 *skipptr += 1;
620 return 1;
622 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
623 ? p - arg : strlen (arg));
624 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
625 return 0;
626 else if (valptr == NULL)
628 *skipptr += 1;
629 return 1;
631 else if (p != NULL)
633 *valptr = p+1;
634 *skipptr += 1;
635 return 1;
637 else if (argv[*skipptr+2] != NULL)
639 *valptr = argv[*skipptr+2];
640 *skipptr += 2;
641 return 1;
643 else
645 return 0;
649 #ifdef DOUG_LEA_MALLOC
651 /* malloc can be invoked even before main (e.g. by the dynamic
652 linker), so the dumped malloc state must be restored as early as
653 possible using this special hook. */
655 static void
656 malloc_initialize_hook (void)
658 if (initialized)
660 if (!malloc_using_checking)
661 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
662 ignored if the heap to be restored was constructed without
663 malloc checking. Can't use unsetenv, since that calls malloc. */
665 char **p;
667 for (p = environ; p && *p; p++)
668 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
671 *p = p[1];
672 while (*++p);
673 break;
677 malloc_set_state (malloc_state_ptr);
678 #ifndef XMALLOC_OVERRUN_CHECK
679 free (malloc_state_ptr);
680 #endif
682 else
684 if (my_heap_start == 0)
685 my_heap_start = sbrk (0);
686 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
690 void (*__malloc_initialize_hook) (void) EXTERNALLY_VISIBLE = malloc_initialize_hook;
692 #endif /* DOUG_LEA_MALLOC */
694 /* Close standard output and standard error, reporting any write
695 errors as best we can. This is intended for use with atexit. */
696 static void
697 close_output_streams (void)
699 if (close_stream (stdout) != 0)
701 emacs_perror ("Write error to standard output");
702 _exit (EXIT_FAILURE);
705 if (close_stream (stderr) != 0)
706 _exit (EXIT_FAILURE);
709 /* ARGSUSED */
711 main (int argc, char **argv)
713 #if GC_MARK_STACK
714 Lisp_Object dummy;
715 #endif
716 char stack_bottom_variable;
717 bool do_initial_setlocale;
718 bool dumping;
719 int skip_args = 0;
720 #ifdef HAVE_SETRLIMIT
721 struct rlimit rlim;
722 #endif
723 bool no_loadup = 0;
724 char *junk = 0;
725 char *dname_arg = 0;
726 #ifdef DAEMON_MUST_EXEC
727 char dname_arg2[80];
728 #endif
729 char *ch_to_dir;
731 /* If we use --chdir, this records the original directory. */
732 char *original_pwd = 0;
734 #if GC_MARK_STACK
735 stack_base = &dummy;
736 #endif
738 #ifndef CANNOT_DUMP
739 might_dump = !initialized;
740 #endif
742 #ifdef GNU_LINUX
743 if (!initialized)
745 if (my_heap_start == 0)
746 my_heap_start = sbrk (0);
748 heap_bss_diff = (char *)my_heap_start - max (my_endbss, my_endbss_static);
750 #endif
752 #if defined WINDOWSNT || defined HAVE_NTGUI
753 /* Set global variables used to detect Windows version. Do this as
754 early as possible. (unexw32.c calls this function as well, but
755 the additional call here is harmless.) */
756 cache_system_info ();
757 #ifdef WINDOWSNT
758 /* On Windows 9X, we have to load UNICOWS.DLL as early as possible,
759 to have non-stub implementations of APIs we need to convert file
760 names between UTF-8 and the system's ANSI codepage. */
761 maybe_load_unicows_dll ();
762 #endif
763 #endif
765 #ifdef RUN_TIME_REMAP
766 if (initialized)
767 run_time_remap (argv[0]);
768 #endif
770 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
771 #ifdef DARWIN_OS
772 if (!initialized)
773 unexec_init_emacs_zone ();
774 #endif
776 atexit (close_output_streams);
778 sort_args (argc, argv);
779 argc = 0;
780 while (argv[argc]) argc++;
782 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
784 const char *version, *copyright;
785 if (initialized)
787 Lisp_Object tem, tem2;
788 tem = Fsymbol_value (intern_c_string ("emacs-version"));
789 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
790 if (!STRINGP (tem))
792 fprintf (stderr, "Invalid value of `emacs-version'\n");
793 exit (1);
795 if (!STRINGP (tem2))
797 fprintf (stderr, "Invalid value of `emacs-copyright'\n");
798 exit (1);
800 else
802 version = SSDATA (tem);
803 copyright = SSDATA (tem2);
806 else
808 version = emacs_version;
809 copyright = emacs_copyright;
811 printf ("GNU Emacs %s\n", version);
812 printf ("%s\n", copyright);
813 printf ("GNU Emacs comes with ABSOLUTELY NO WARRANTY.\n");
814 printf ("You may redistribute copies of Emacs\n");
815 printf ("under the terms of the GNU General Public License.\n");
816 printf ("For more information about these matters, ");
817 printf ("see the file named COPYING.\n");
818 exit (0);
821 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
823 #ifdef WINDOWSNT
824 /* argv[] array is kept in its original ANSI codepage encoding,
825 we need to convert to UTF-8, for chdir to work. */
826 char newdir[MAX_UTF8_PATH];
828 filename_from_ansi (ch_to_dir, newdir);
829 ch_to_dir = newdir;
830 #endif
831 original_pwd = get_current_dir_name ();
832 if (chdir (ch_to_dir) != 0)
834 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
835 argv[0], ch_to_dir, strerror (errno));
836 exit (1);
840 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
841 || strcmp (argv[argc - 1], "bootstrap") == 0);
843 #ifdef HAVE_PERSONALITY_LINUX32
844 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
846 /* Set this so we only do this once. */
847 xputenv ("EMACS_HEAP_EXEC=true");
849 /* A flag to turn off address randomization which is introduced
850 in linux kernel shipped with fedora core 4 */
851 #define ADD_NO_RANDOMIZE 0x0040000
852 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
853 #undef ADD_NO_RANDOMIZE
855 execvp (argv[0], argv);
857 /* If the exec fails, try to dump anyway. */
858 emacs_perror (argv[0]);
860 #endif /* HAVE_PERSONALITY_LINUX32 */
862 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK)
863 /* Extend the stack space available.
864 Don't do that if dumping, since some systems (e.g. DJGPP)
865 might define a smaller stack limit at that time. */
866 if (1
867 #ifndef CANNOT_DUMP
868 && (!noninteractive || initialized)
869 #endif
870 && !getrlimit (RLIMIT_STACK, &rlim))
872 long newlim;
873 /* Approximate the amount regex.c needs per unit of re_max_failures. */
874 int ratio = 20 * sizeof (char *);
875 /* Then add 33% to cover the size of the smaller stacks that regex.c
876 successively allocates and discards, on its way to the maximum. */
877 ratio += ratio / 3;
878 /* Add in some extra to cover
879 what we're likely to use for other reasons. */
880 newlim = re_max_failures * ratio + 200000;
881 #ifdef __NetBSD__
882 /* NetBSD (at least NetBSD 1.2G and former) has a bug in its
883 stack allocation routine for new process that the allocation
884 fails if stack limit is not on page boundary. So, round up the
885 new limit to page boundary. */
886 newlim = (newlim + getpagesize () - 1) / getpagesize () * getpagesize ();
887 #endif
888 if (newlim > rlim.rlim_max)
890 newlim = rlim.rlim_max;
891 /* Don't let regex.c overflow the stack we have. */
892 re_max_failures = (newlim - 200000) / ratio;
894 if (rlim.rlim_cur < newlim)
895 rlim.rlim_cur = newlim;
897 setrlimit (RLIMIT_STACK, &rlim);
899 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK */
901 /* Record (approximately) where the stack begins. */
902 stack_bottom = &stack_bottom_variable;
904 clearerr (stdin);
906 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
907 /* Arrange to get warning messages as memory fills up. */
908 memory_warnings (0, malloc_warning);
910 /* Call malloc at least once, to run malloc_initialize_hook.
911 Also call realloc and free for consistency. */
912 free (realloc (malloc (4), 4));
914 #endif /* not SYSTEM_MALLOC and not HYBRID_MALLOC */
916 #ifdef MSDOS
917 SET_BINARY (fileno (stdin));
918 fflush (stdout);
919 SET_BINARY (fileno (stdout));
920 #endif /* MSDOS */
922 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
923 The build procedure uses this while dumping, to ensure that the
924 dumped Emacs does not have its system locale tables initialized,
925 as that might cause screwups when the dumped Emacs starts up. */
927 char *lc_all = getenv ("LC_ALL");
928 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
931 /* Set locale now, so that initial error messages are localized properly.
932 fixup_locale must wait until later, since it builds strings. */
933 if (do_initial_setlocale)
934 setlocale (LC_ALL, "");
936 inhibit_window_system = 0;
938 /* Handle the -t switch, which specifies filename to use as terminal. */
939 while (1)
941 char *term;
942 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
944 int result;
945 emacs_close (0);
946 emacs_close (1);
947 result = emacs_open (term, O_RDWR, 0);
948 if (result < 0 || fcntl (0, F_DUPFD_CLOEXEC, 1) < 0)
950 char *errstring = strerror (errno);
951 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
952 exit (1);
954 if (! isatty (0))
956 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
957 exit (1);
959 fprintf (stderr, "Using %s\n", term);
960 #ifdef HAVE_WINDOW_SYSTEM
961 inhibit_window_system = 1; /* -t => -nw */
962 #endif
964 else
965 break;
968 /* Command line option --no-windows is deprecated and thus not mentioned
969 in the manual and usage information. */
970 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
971 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
972 inhibit_window_system = 1;
974 /* Handle the -batch switch, which means don't do interactive display. */
975 noninteractive = 0;
976 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
978 noninteractive = 1;
979 Vundo_outer_limit = Qnil;
981 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
983 noninteractive = 1; /* Set batch mode. */
984 /* Convert --script to -scriptload, un-skip it, and sort again
985 so that it will be handled in proper sequence. */
986 /* FIXME broken for --script=FILE - is that supposed to work? */
987 argv[skip_args - 1] = (char *) "-scriptload";
988 skip_args -= 2;
989 sort_args (argc, argv);
992 /* Handle the --help option, which gives a usage message. */
993 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
995 int i;
996 printf ("Usage: %s [OPTION-OR-FILENAME]...\n", argv[0]);
997 for (i = 0; i < ARRAYELTS (usage_message); i++)
998 fputs (usage_message[i], stdout);
999 exit (0);
1002 /* Make sure IS_DAEMON starts up as false. */
1003 daemon_pipe[1] = 0;
1005 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
1006 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
1008 #ifndef DOS_NT
1009 pid_t f;
1011 /* Start as a daemon: fork a new child process which will run the
1012 rest of the initialization code, then exit.
1014 Detaching a daemon requires the following steps:
1015 - fork
1016 - setsid
1017 - exit the parent
1018 - close the tty file-descriptors
1020 We only want to do the last 2 steps once the daemon is ready to
1021 serve requests, i.e. after loading .emacs (initialization).
1022 OTOH initialization may start subprocesses (e.g. ispell) and these
1023 should be run from the proper process (the one that will end up
1024 running as daemon) and with the proper "session id" in order for
1025 them to keep working after detaching, so fork and setsid need to be
1026 performed before initialization.
1028 We want to avoid exiting before the server socket is ready, so
1029 use a pipe for synchronization. The parent waits for the child
1030 to close its end of the pipe (using `daemon-initialized')
1031 before exiting. */
1032 if (emacs_pipe (daemon_pipe) != 0)
1034 fprintf (stderr, "Cannot pipe!\n");
1035 exit (1);
1038 #ifndef DAEMON_MUST_EXEC
1039 #ifdef USE_GTK
1040 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
1041 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
1042 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
1043 #endif /* USE_GTK */
1044 f = fork ();
1045 #else /* DAEMON_MUST_EXEC */
1046 if (!dname_arg || !strchr (dname_arg, '\n'))
1047 f = fork (); /* in orig */
1048 else
1049 f = 0; /* in exec'd */
1050 #endif /* !DAEMON_MUST_EXEC */
1051 if (f > 0)
1053 int retval;
1054 char buf[1];
1056 /* Close unused writing end of the pipe. */
1057 emacs_close (daemon_pipe[1]);
1059 /* Just wait for the child to close its end of the pipe. */
1062 retval = read (daemon_pipe[0], &buf, 1);
1064 while (retval == -1 && errno == EINTR);
1066 if (retval < 0)
1068 fprintf (stderr, "Error reading status from child\n");
1069 exit (1);
1071 else if (retval == 0)
1073 fprintf (stderr, "Error: server did not start correctly\n");
1074 exit (1);
1077 emacs_close (daemon_pipe[0]);
1078 exit (0);
1080 if (f < 0)
1082 emacs_perror ("fork");
1083 exit (EXIT_CANCELED);
1086 #ifdef DAEMON_MUST_EXEC
1088 /* In orig process, forked as child, OR in exec'd. */
1089 if (!dname_arg || !strchr (dname_arg, '\n'))
1090 { /* In orig, child: now exec w/special daemon name. */
1091 char fdStr[80];
1092 int fdStrlen =
1093 snprintf (fdStr, sizeof fdStr,
1094 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1095 daemon_pipe[1], dname_arg ? dname_arg : "");
1097 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1099 fprintf (stderr, "daemon: child name too long\n");
1100 exit (EXIT_CANNOT_INVOKE);
1103 argv[skip_args] = fdStr;
1105 fcntl (daemon_pipe[0], F_SETFD, 0);
1106 fcntl (daemon_pipe[1], F_SETFD, 0);
1107 execvp (argv[0], argv);
1108 emacs_perror (argv[0]);
1109 exit (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
1112 /* In exec'd: parse special dname into pipe and name info. */
1113 if (!dname_arg || !strchr (dname_arg, '\n')
1114 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1116 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1117 exit (EXIT_CANNOT_INVOKE);
1119 dname_arg2[0] = '\0';
1120 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1121 dname_arg2);
1122 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1123 fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
1125 #endif /* DAEMON_MUST_EXEC */
1127 if (dname_arg)
1128 daemon_name = xstrdup (dname_arg);
1129 /* Close unused reading end of the pipe. */
1130 emacs_close (daemon_pipe[0]);
1132 setsid ();
1133 #else /* DOS_NT */
1134 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1135 exit (1);
1136 #endif /* DOS_NT */
1139 #if defined HAVE_PTHREAD && !defined SYSTEM_MALLOC \
1140 && !defined DOUG_LEA_MALLOC && !defined HYBRID_MALLOC
1141 # ifndef CANNOT_DUMP
1142 /* Do not make gmalloc thread-safe when creating bootstrap-emacs, as
1143 that causes an infinite recursive loop with FreeBSD. See
1144 Bug#14569. The part of this bug involving Cygwin is no longer
1145 relevant, now that Cygwin defines HYBRID_MALLOC. */
1146 if (!noninteractive || initialized)
1147 # endif
1148 malloc_enable_thread ();
1149 #endif
1151 init_signals (dumping);
1153 noninteractive1 = noninteractive;
1155 /* Perform basic initializations (not merely interning symbols). */
1157 if (!initialized)
1159 init_alloc_once ();
1160 init_obarray ();
1161 init_eval_once ();
1162 init_charset_once ();
1163 init_coding_once ();
1164 init_syntax_once (); /* Create standard syntax table. */
1165 init_category_once (); /* Create standard category table. */
1166 init_casetab_once (); /* Must be done before init_buffer_once. */
1167 init_buffer_once (); /* Create buffer table and some buffers. */
1168 init_minibuf_once (); /* Create list of minibuffers. */
1169 /* Must precede init_window_once. */
1171 /* Call syms_of_xfaces before init_window_once because that
1172 function creates Vterminal_frame. Termcap frames now use
1173 faces, and the face implementation uses some symbols as
1174 face names. */
1175 syms_of_xfaces ();
1176 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1177 be better to arrange things not to have this dependency. */
1178 syms_of_keymap ();
1179 /* Call syms_of_keyboard before init_window_once because
1180 keyboard sets up symbols that include some face names that
1181 the X support will want to use. This can happen when
1182 CANNOT_DUMP is defined. */
1183 syms_of_keyboard ();
1185 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1186 syms_of_data ();
1187 syms_of_fns (); /* Before syms_of_charset which uses hashtables. */
1188 syms_of_fileio ();
1189 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1190 syms_of_alloc ();
1191 /* May call Ffuncall and so GC, thus the latter should be initialized. */
1192 init_print_once ();
1193 /* Before syms_of_coding because it initializes Qcharsetp. */
1194 syms_of_charset ();
1195 /* Before init_window_once, because it sets up the
1196 Vcoding_system_hash_table. */
1197 syms_of_coding (); /* This should be after syms_of_fileio. */
1199 init_window_once (); /* Init the window system. */
1200 #ifdef HAVE_WINDOW_SYSTEM
1201 init_fringe_once (); /* Swap bitmaps if necessary. */
1202 #endif /* HAVE_WINDOW_SYSTEM */
1205 init_alloc ();
1207 if (do_initial_setlocale)
1209 fixup_locale ();
1210 Vsystem_messages_locale = Vprevious_system_messages_locale;
1211 Vsystem_time_locale = Vprevious_system_time_locale;
1214 init_eval ();
1215 init_atimer ();
1216 running_asynch_code = 0;
1217 init_random ();
1219 no_loadup
1220 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1222 no_site_lisp
1223 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1225 #ifdef HAVE_NS
1226 ns_pool = ns_alloc_autorelease_pool ();
1227 #ifdef NS_IMPL_GNUSTEP
1228 /* GNUstep stupidly resets our locale settings after we made them. */
1229 fixup_locale ();
1230 #endif
1232 if (!noninteractive)
1234 #ifdef NS_IMPL_COCOA
1235 /* Started from GUI? */
1236 /* FIXME: Do the right thing if getenv returns NULL, or if
1237 chdir fails. */
1238 if (! inhibit_window_system && ! isatty (0))
1239 chdir (getenv ("HOME"));
1240 if (skip_args < argc)
1242 if (!strncmp (argv[skip_args], "-psn", 4))
1244 skip_args += 1;
1245 chdir (getenv ("HOME"));
1247 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1249 skip_args += 2;
1250 chdir (getenv ("HOME"));
1253 #endif /* COCOA */
1255 #endif /* HAVE_NS */
1257 #ifdef HAVE_X_WINDOWS
1258 /* Stupid kludge to catch command-line display spec. We can't
1259 handle this argument entirely in window system dependent code
1260 because we don't even know which window system dependent code
1261 to run until we've recognized this argument. */
1263 char *displayname = 0;
1264 int count_before = skip_args;
1266 /* Skip any number of -d options, but only use the last one. */
1267 while (1)
1269 int count_before_this = skip_args;
1271 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1272 display_arg = 1;
1273 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1274 display_arg = 1;
1275 else
1276 break;
1278 count_before = count_before_this;
1281 /* If we have the form --display=NAME,
1282 convert it into -d name.
1283 This requires inserting a new element into argv. */
1284 if (displayname && count_before < skip_args)
1286 if (skip_args == count_before + 1)
1288 memmove (argv + count_before + 3, argv + count_before + 2,
1289 (argc - (count_before + 2)) * sizeof *argv);
1290 argv[count_before + 2] = displayname;
1291 argc++;
1293 argv[count_before + 1] = (char *) "-d";
1296 if (! no_site_lisp)
1298 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1299 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1300 no_site_lisp = 1;
1303 /* Don't actually discard this arg. */
1304 skip_args = count_before;
1306 #else /* !HAVE_X_WINDOWS */
1307 if (! no_site_lisp)
1309 int count_before = skip_args;
1311 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1312 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1313 no_site_lisp = 1;
1315 skip_args = count_before;
1317 #endif
1319 /* argmatch must not be used after here,
1320 except when building temacs
1321 because the -d argument has not been skipped in skip_args. */
1323 #ifdef MSDOS
1324 /* Call early 'cause init_environment needs it. */
1325 init_dosfns ();
1326 /* Set defaults for several environment variables. */
1327 if (initialized)
1328 init_environment (argc, argv, skip_args);
1329 else
1330 tzset ();
1331 #endif /* MSDOS */
1333 #ifdef HAVE_GFILENOTIFY
1334 globals_of_gfilenotify ();
1335 #endif
1337 #ifdef WINDOWSNT
1338 globals_of_w32 ();
1339 #ifdef HAVE_W32NOTIFY
1340 globals_of_w32notify ();
1341 #endif
1342 /* Initialize environment from registry settings. */
1343 init_environment (argv);
1344 init_ntproc (dumping); /* must precede init_editfns. */
1345 #endif
1347 /* Initialize and GC-protect Vinitial_environment and
1348 Vprocess_environment before set_initial_environment fills them
1349 in. */
1350 if (!initialized)
1351 syms_of_callproc ();
1352 /* egetenv is a pretty low-level facility, which may get called in
1353 many circumstances; it seems flimsy to put off initializing it
1354 until calling init_callproc. Do not do it when dumping. */
1355 if (! dumping)
1356 set_initial_environment ();
1358 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1359 if this is not done. Do it after set_global_environment so that we
1360 don't pollute Vglobal_environment. */
1361 /* Setting LANG here will defeat the startup locale processing... */
1362 #ifdef AIX
1363 xputenv ("LANG=C");
1364 #endif
1366 /* Init buffer storage and default directory of main buffer. */
1367 init_buffer (initialized);
1369 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1371 /* Must precede init_lread. */
1372 init_cmdargs (argc, argv, skip_args, original_pwd);
1374 if (initialized)
1376 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1377 Lisp_Object old_log_max;
1378 old_log_max = Vmessage_log_max;
1379 XSETFASTINT (Vmessage_log_max, 0);
1380 message_dolog ("", 0, 1, 0);
1381 Vmessage_log_max = old_log_max;
1384 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1385 init_fileio ();
1386 init_lread ();
1387 #ifdef WINDOWSNT
1388 /* Check to see if Emacs has been installed correctly. */
1389 check_windows_init_file ();
1390 #endif
1392 /* Intern the names of all standard functions and variables;
1393 define standard keys. */
1395 if (!initialized)
1397 /* The basic levels of Lisp must come first. Note that
1398 syms_of_data and some others have already been called. */
1399 syms_of_chartab ();
1400 syms_of_lread ();
1401 syms_of_print ();
1402 syms_of_eval ();
1403 syms_of_floatfns ();
1405 syms_of_buffer ();
1406 syms_of_bytecode ();
1407 syms_of_callint ();
1408 syms_of_casefiddle ();
1409 syms_of_casetab ();
1410 syms_of_category ();
1411 syms_of_ccl ();
1412 syms_of_character ();
1413 syms_of_cmds ();
1414 syms_of_dired ();
1415 syms_of_display ();
1416 syms_of_doc ();
1417 syms_of_editfns ();
1418 syms_of_emacs ();
1419 syms_of_filelock ();
1420 syms_of_indent ();
1421 syms_of_insdel ();
1422 /* syms_of_keymap (); */
1423 syms_of_macros ();
1424 syms_of_marker ();
1425 syms_of_minibuf ();
1426 syms_of_process ();
1427 syms_of_search ();
1428 syms_of_frame ();
1429 syms_of_syntax ();
1430 syms_of_terminal ();
1431 syms_of_term ();
1432 syms_of_undo ();
1433 #ifdef HAVE_SOUND
1434 syms_of_sound ();
1435 #endif
1436 syms_of_textprop ();
1437 syms_of_composite ();
1438 #ifdef WINDOWSNT
1439 syms_of_ntproc ();
1440 #endif /* WINDOWSNT */
1441 #if defined CYGWIN
1442 syms_of_cygw32 ();
1443 #endif
1444 syms_of_window ();
1445 syms_of_xdisp ();
1446 syms_of_font ();
1447 #ifdef HAVE_WINDOW_SYSTEM
1448 syms_of_fringe ();
1449 syms_of_image ();
1450 #endif /* HAVE_WINDOW_SYSTEM */
1451 #ifdef HAVE_X_WINDOWS
1452 syms_of_xterm ();
1453 syms_of_xfns ();
1454 syms_of_xmenu ();
1455 syms_of_fontset ();
1456 syms_of_xsettings ();
1457 #ifdef HAVE_X_SM
1458 syms_of_xsmfns ();
1459 #endif
1460 #ifdef HAVE_X11
1461 syms_of_xselect ();
1462 #endif
1463 #endif /* HAVE_X_WINDOWS */
1465 #ifdef HAVE_LIBXML2
1466 syms_of_xml ();
1467 #endif
1469 #ifdef HAVE_ZLIB
1470 syms_of_decompress ();
1471 #endif
1473 syms_of_menu ();
1475 #ifdef HAVE_NTGUI
1476 syms_of_w32term ();
1477 syms_of_w32fns ();
1478 syms_of_w32menu ();
1479 syms_of_fontset ();
1480 #endif /* HAVE_NTGUI */
1482 #if defined WINDOWSNT || defined HAVE_NTGUI
1483 syms_of_w32select ();
1484 #endif
1486 #ifdef MSDOS
1487 syms_of_xmenu ();
1488 syms_of_dosfns ();
1489 syms_of_msdos ();
1490 syms_of_win16select ();
1491 #endif /* MSDOS */
1493 #ifdef HAVE_NS
1494 syms_of_nsterm ();
1495 syms_of_nsfns ();
1496 syms_of_nsmenu ();
1497 syms_of_nsselect ();
1498 syms_of_fontset ();
1499 #endif /* HAVE_NS */
1501 #ifdef HAVE_GNUTLS
1502 syms_of_gnutls ();
1503 #endif
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 < ARRAYELTS (standard_args); 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; i < ARRAYELTS (standard_args); i++)
1831 if (standard_args[i].longname
1832 && !strncmp (argv[from], standard_args[i].longname,
1833 thislen))
1835 if (match == -1)
1836 match = i;
1837 else
1838 match = -2;
1841 /* If we found exactly one match, use that. */
1842 if (match >= 0)
1844 options[from] = standard_args[match].nargs;
1845 priority[from] = standard_args[match].priority;
1846 /* If --OPTION=VALUE syntax is used,
1847 this option uses just one argv element. */
1848 if (equals != 0)
1849 options[from] = 0;
1850 if (from + options[from] >= argc)
1851 fatal ("Option `%s' requires an argument\n", argv[from]);
1852 from += options[from];
1854 /* FIXME When match < 0, shouldn't there be some error,
1855 or at least indication to the user that there was a
1856 problem? */
1858 done: ;
1862 /* Copy the arguments, in order of decreasing priority, to NEW. */
1863 new[0] = argv[0];
1864 while (incoming_used < argc)
1866 int best = -1;
1867 int best_priority = -9999;
1869 /* Find the highest priority remaining option.
1870 If several have equal priority, take the first of them. */
1871 for (from = 1; from < argc; from++)
1873 if (argv[from] != 0 && priority[from] > best_priority)
1875 best_priority = priority[from];
1876 best = from;
1878 /* Skip option arguments--they are tied to the options. */
1879 if (options[from] > 0)
1880 from += options[from];
1883 if (best < 0)
1884 emacs_abort ();
1886 /* Copy the highest priority remaining option, with its args, to NEW.
1887 Unless it is a duplicate of the previous one. */
1888 if (! (options[best] == 0
1889 && ! strcmp (new[to - 1], argv[best])))
1891 new[to++] = argv[best];
1892 for (i = 0; i < options[best]; i++)
1893 new[to++] = argv[best + i + 1];
1896 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1898 /* Clear out this option in ARGV. */
1899 argv[best] = 0;
1900 for (i = 0; i < options[best]; i++)
1901 argv[best + i + 1] = 0;
1904 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1905 while (to < argc)
1906 new[to++] = 0;
1908 memcpy (argv, new, sizeof (char *) * argc);
1910 xfree (options);
1911 xfree (new);
1912 xfree (priority);
1915 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1916 doc: /* Exit the Emacs job and kill it.
1917 If ARG is an integer, return ARG as the exit program code.
1918 If ARG is a string, stuff it as keyboard input.
1920 This function is called upon receipt of the signals SIGTERM
1921 or SIGHUP, and upon SIGINT in batch mode.
1923 The value of `kill-emacs-hook', if not void,
1924 is a list of functions (of no args),
1925 all of which are called before Emacs is actually killed. */)
1926 (Lisp_Object arg)
1928 struct gcpro gcpro1;
1929 int exit_code;
1931 GCPRO1 (arg);
1933 if (feof (stdin))
1934 arg = Qt;
1936 /* Fsignal calls emacs_abort () if it sees that waiting_for_input is
1937 set. */
1938 waiting_for_input = 0;
1939 Frun_hooks (1, &Qkill_emacs_hook);
1940 UNGCPRO;
1942 #ifdef HAVE_X_WINDOWS
1943 /* Transfer any clipboards we own to the clipboard manager. */
1944 x_clipboard_manager_save_all ();
1945 #endif
1947 shut_down_emacs (0, STRINGP (arg) ? arg : Qnil);
1949 #ifdef HAVE_NS
1950 ns_release_autorelease_pool (ns_pool);
1951 #endif
1953 /* If we have an auto-save list file,
1954 kill it because we are exiting Emacs deliberately (not crashing).
1955 Do it after shut_down_emacs, which does an auto-save. */
1956 if (STRINGP (Vauto_save_list_file_name))
1958 Lisp_Object listfile;
1959 listfile = Fexpand_file_name (Vauto_save_list_file_name, Qnil);
1960 unlink (SSDATA (listfile));
1963 if (INTEGERP (arg))
1964 exit_code = (XINT (arg) < 0
1965 ? XINT (arg) | INT_MIN
1966 : XINT (arg) & INT_MAX);
1967 else
1968 exit_code = EXIT_SUCCESS;
1969 exit (exit_code);
1973 /* Perform an orderly shutdown of Emacs. Autosave any modified
1974 buffers, kill any child processes, clean up the terminal modes (if
1975 we're in the foreground), and other stuff like that. Don't perform
1976 any redisplay; this may be called when Emacs is shutting down in
1977 the background, or after its X connection has died.
1979 If SIG is a signal number, print a message for it.
1981 This is called by fatal signal handlers, X protocol error handlers,
1982 and Fkill_emacs. */
1984 void
1985 shut_down_emacs (int sig, Lisp_Object stuff)
1987 /* Prevent running of hooks from now on. */
1988 Vrun_hooks = Qnil;
1990 /* Don't update display from now on. */
1991 Vinhibit_redisplay = Qt;
1993 /* If we are controlling the terminal, reset terminal modes. */
1994 #ifndef DOS_NT
1996 pid_t pgrp = getpgrp ();
1997 pid_t tpgrp = tcgetpgrp (0);
1998 if ((tpgrp != -1) && tpgrp == pgrp)
2000 reset_all_sys_modes ();
2001 if (sig && sig != SIGTERM)
2003 static char const format[] = "Fatal error %d: ";
2004 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
2005 int buflen = sprintf (buf, format, sig);
2006 char const *sig_desc = safe_strsignal (sig);
2007 emacs_write (STDERR_FILENO, buf, buflen);
2008 emacs_write (STDERR_FILENO, sig_desc, strlen (sig_desc));
2012 #else
2013 fflush (stdout);
2014 reset_all_sys_modes ();
2015 #endif
2017 stuff_buffered_input (stuff);
2019 inhibit_sentinels = 1;
2020 kill_buffer_processes (Qnil);
2021 Fdo_auto_save (Qt, Qnil);
2023 unlock_all_files ();
2025 /* There is a tendency for a SIGIO signal to arrive within exit,
2026 and cause a SIGHUP because the input descriptor is already closed. */
2027 unrequest_sigio ();
2028 ignore_sigio ();
2030 /* Do this only if terminating normally, we want glyph matrices
2031 etc. in a core dump. */
2032 if (sig == 0 || sig == SIGTERM)
2034 check_glyph_memory ();
2035 check_message_stack ();
2038 #ifdef MSDOS
2039 dos_cleanup ();
2040 #endif
2042 #ifdef HAVE_NS
2043 ns_term_shutdown (sig);
2044 #endif
2046 #ifdef HAVE_LIBXML2
2047 xml_cleanup_parser ();
2048 #endif
2050 #ifdef WINDOWSNT
2051 term_ntproc (0);
2052 #endif
2057 #ifndef CANNOT_DUMP
2059 #include "unexec.h"
2061 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
2062 doc: /* Dump current state of Emacs into executable file FILENAME.
2063 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
2064 This is used in the file `loadup.el' when building Emacs.
2066 You must run Emacs in batch mode in order to dump it. */)
2067 (Lisp_Object filename, Lisp_Object symfile)
2069 Lisp_Object tem;
2070 Lisp_Object symbol;
2071 ptrdiff_t count = SPECPDL_INDEX ();
2073 check_pure_size ();
2075 if (! noninteractive)
2076 error ("Dumping Emacs works only in batch mode");
2078 if (!might_dump)
2079 error ("Emacs can be dumped only once");
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 #if !defined SYSTEM_MALLOC && !defined HYBRID_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. */
2136 memory_warnings (my_edata, malloc_warning);
2137 #endif /* not WINDOWSNT */
2138 #endif /* not SYSTEM_MALLOC and not HYBRID_MALLOC */
2139 #ifdef DOUG_LEA_MALLOC
2140 malloc_state_ptr = malloc_get_state ();
2141 #endif
2143 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2145 #ifdef DOUG_LEA_MALLOC
2146 free (malloc_state_ptr);
2147 #endif
2149 #ifdef WINDOWSNT
2150 Vlibrary_cache = Qnil;
2151 #endif
2152 #ifdef HAVE_WINDOW_SYSTEM
2153 reset_image_types ();
2154 #endif
2156 Vpurify_flag = tem;
2158 return unbind_to (count, Qnil);
2161 #endif /* not CANNOT_DUMP */
2163 #if HAVE_SETLOCALE
2164 /* Recover from setlocale (LC_ALL, ""). */
2165 void
2166 fixup_locale (void)
2168 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2169 so that numbers are read and printed properly for Emacs Lisp. */
2170 setlocale (LC_NUMERIC, "C");
2173 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2174 DESIRED_LOCALE. */
2175 static void
2176 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2178 if (! EQ (*plocale, desired_locale))
2180 *plocale = desired_locale;
2181 setlocale (category, (STRINGP (desired_locale)
2182 ? SSDATA (desired_locale)
2183 : ""));
2187 /* Set system time locale to match Vsystem_time_locale, if possible. */
2188 void
2189 synchronize_system_time_locale (void)
2191 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2192 Vsystem_time_locale);
2195 /* Set system messages locale to match Vsystem_messages_locale, if
2196 possible. */
2197 void
2198 synchronize_system_messages_locale (void)
2200 #ifdef LC_MESSAGES
2201 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2202 Vsystem_messages_locale);
2203 #endif
2205 #endif /* HAVE_SETLOCALE */
2208 Lisp_Object
2209 decode_env_path (const char *evarname, const char *defalt, bool empty)
2211 const char *path, *p;
2212 Lisp_Object lpath, element, tem;
2213 /* Default is to use "." for empty path elements.
2214 But if argument EMPTY is true, use nil instead. */
2215 Lisp_Object empty_element = empty ? Qnil : build_string (".");
2216 #ifdef WINDOWSNT
2217 bool defaulted = 0;
2218 static const char *emacs_dir_env = "%emacs_dir%/";
2219 const size_t emacs_dir_len = strlen (emacs_dir_env);
2220 const char *edir = egetenv ("emacs_dir");
2221 char emacs_dir[MAX_UTF8_PATH];
2223 /* egetenv looks in process-environment, which holds the variables
2224 in their original system-locale encoding. We need emacs_dir to
2225 be in UTF-8. */
2226 if (edir)
2227 filename_from_ansi (edir, emacs_dir);
2228 #endif
2230 /* It's okay to use getenv here, because this function is only used
2231 to initialize variables when Emacs starts up, and isn't called
2232 after that. */
2233 if (evarname != 0)
2234 path = getenv (evarname);
2235 else
2236 path = 0;
2237 if (!path)
2239 path = defalt;
2240 #ifdef WINDOWSNT
2241 defaulted = 1;
2242 #endif
2244 #ifdef DOS_NT
2245 /* Ensure values from the environment use the proper directory separator. */
2246 if (path)
2248 char *path_copy;
2250 #ifdef WINDOWSNT
2251 char *path_utf8, *q, *d;
2252 int cnv_result;
2254 /* Convert each element of PATH to UTF-8. */
2255 p = path_copy = alloca (strlen (path) + 1);
2256 strcpy (path_copy, path);
2257 d = path_utf8 = alloca (4 * strlen (path) + 1);
2258 *d = '\0';
2259 do {
2260 q = _mbschr (p, SEPCHAR);
2261 if (q)
2262 *q = '\0';
2263 cnv_result = filename_from_ansi (p, d);
2264 if (q)
2266 *q++ = SEPCHAR;
2267 p = q;
2268 /* If conversion of this PATH elements fails, make sure
2269 destination pointer will stay put, thus effectively
2270 ignoring the offending element. */
2271 if (cnv_result == 0)
2273 d += strlen (d);
2274 *d++ = SEPCHAR;
2277 else if (cnv_result != 0 && d > path_utf8)
2278 d[-1] = '\0'; /* remove last semi-colon and null-terminate PATH */
2279 } while (q);
2280 path_copy = path_utf8;
2281 #else /* MSDOS */
2282 path_copy = alloca (strlen (path) + 1);
2283 strcpy (path_copy, path);
2284 #endif
2285 dostounix_filename (path_copy);
2286 path = path_copy;
2288 #endif
2289 lpath = Qnil;
2290 while (1)
2292 p = strchr (path, SEPCHAR);
2293 if (!p)
2294 p = path + strlen (path);
2295 element = (p - path ? make_unibyte_string (path, p - path)
2296 : empty_element);
2297 if (! NILP (element))
2299 #ifdef WINDOWSNT
2300 /* Relative file names in the default path are interpreted as
2301 being relative to $emacs_dir. */
2302 if (edir && defaulted
2303 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2304 element = Fexpand_file_name (Fsubstring
2305 (element,
2306 make_number (emacs_dir_len),
2307 Qnil),
2308 build_unibyte_string (emacs_dir));
2309 #endif
2311 /* Add /: to the front of the name
2312 if it would otherwise be treated as magic. */
2313 tem = Ffind_file_name_handler (element, Qt);
2315 /* However, if the handler says "I'm safe",
2316 don't bother adding /:. */
2317 if (SYMBOLP (tem))
2319 Lisp_Object prop;
2320 prop = Fget (tem, intern ("safe-magic"));
2321 if (! NILP (prop))
2322 tem = Qnil;
2325 if (! NILP (tem))
2326 element = concat2 (build_string ("/:"), element);
2327 } /* !NILP (element) */
2329 lpath = Fcons (element, lpath);
2330 if (*p)
2331 path = p + 1;
2332 else
2333 break;
2335 return Fnreverse (lpath);
2338 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2339 doc: /* Return non-nil if the current emacs process is a daemon.
2340 If the daemon was given a name argument, return that name. */)
2341 (void)
2343 if (IS_DAEMON)
2344 if (daemon_name)
2345 return build_string (daemon_name);
2346 else
2347 return Qt;
2348 else
2349 return Qnil;
2352 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2353 doc: /* Mark the Emacs daemon as being initialized.
2354 This finishes the daemonization process by doing the other half of detaching
2355 from the parent process and its tty file descriptors. */)
2356 (void)
2358 int nfd;
2359 bool err = 0;
2361 if (!IS_DAEMON)
2362 error ("This function can only be called if emacs is run as a daemon");
2364 if (daemon_pipe[1] < 0)
2365 error ("The daemon has already been initialized");
2367 if (NILP (Vafter_init_time))
2368 error ("This function can only be called after loading the init files");
2370 /* Get rid of stdin, stdout and stderr. */
2371 nfd = emacs_open ("/dev/null", O_RDWR, 0);
2372 err |= nfd < 0;
2373 err |= dup2 (nfd, 0) < 0;
2374 err |= dup2 (nfd, 1) < 0;
2375 err |= dup2 (nfd, 2) < 0;
2376 err |= emacs_close (nfd) != 0;
2378 /* Closing the pipe will notify the parent that it can exit.
2379 FIXME: In case some other process inherited the pipe, closing it here
2380 won't notify the parent because it's still open elsewhere, so we
2381 additionally send a byte, just to make sure the parent really exits.
2382 Instead, we should probably close the pipe in start-process and
2383 call-process to make sure the pipe is never inherited by
2384 subprocesses. */
2385 err |= write (daemon_pipe[1], "\n", 1) < 0;
2386 err |= emacs_close (daemon_pipe[1]) != 0;
2387 /* Set it to an invalid value so we know we've already run this function. */
2388 daemon_pipe[1] = -1;
2390 if (err)
2391 error ("I/O error during daemon initialization");
2392 return Qt;
2395 void
2396 syms_of_emacs (void)
2398 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2399 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2400 DEFSYM (Qkill_emacs, "kill-emacs");
2401 DEFSYM (Qkill_emacs_hook, "kill-emacs-hook");
2403 #ifndef CANNOT_DUMP
2404 defsubr (&Sdump_emacs);
2405 #endif
2407 defsubr (&Skill_emacs);
2409 defsubr (&Sinvocation_name);
2410 defsubr (&Sinvocation_directory);
2411 defsubr (&Sdaemonp);
2412 defsubr (&Sdaemon_initialized);
2414 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2415 doc: /* Args passed by shell to Emacs, as a list of strings.
2416 Many arguments are deleted from the list as they are processed. */);
2418 DEFVAR_LISP ("system-type", Vsystem_type,
2419 doc: /* The value is a symbol indicating the type of operating system you are using.
2420 Special values:
2421 `gnu' compiled for a GNU Hurd system.
2422 `gnu/linux' compiled for a GNU/Linux system.
2423 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2424 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2425 `ms-dos' compiled as an MS-DOS application.
2426 `windows-nt' compiled as a native W32 application.
2427 `cygwin' compiled using the Cygwin library.
2428 Anything else (in Emacs 24.1, the possibilities are: aix, berkeley-unix,
2429 hpux, irix, usg-unix-v) indicates some sort of Unix system. */);
2430 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2431 /* See configure.ac (and config.nt) for the possible SYSTEM_TYPEs. */
2433 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2434 doc: /* Value is string indicating configuration Emacs was built for.
2435 On MS-Windows, the value reflects the OS flavor and version on which
2436 Emacs is running. */);
2437 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2439 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2440 doc: /* String containing the configuration options Emacs was built with. */);
2441 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2443 DEFVAR_LISP ("system-configuration-features", Vsystem_configuration_features,
2444 doc: /* String listing some of the main features this Emacs was compiled with.
2445 An element of the form \"FOO\" generally means that HAVE_FOO was
2446 defined during the build. */);
2447 Vsystem_configuration_features = build_string (EMACS_CONFIG_FEATURES);
2449 DEFVAR_BOOL ("noninteractive", noninteractive1,
2450 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2452 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2453 doc: /* Hook run when `kill-emacs' is called.
2454 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2455 in other similar situations), functions placed on this hook should not
2456 expect to be able to interact with the user. To ask for confirmation,
2457 see `kill-emacs-query-functions' instead.
2459 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2460 `noninteractive' was non-nil. */);
2461 Vkill_emacs_hook = Qnil;
2463 DEFVAR_LISP ("path-separator", Vpath_separator,
2464 doc: /* String containing the character that separates directories in
2465 search paths, such as PATH and other similar environment variables. */);
2467 char c = SEPCHAR;
2468 Vpath_separator = make_string (&c, 1);
2471 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2472 doc: /* The program name that was used to run Emacs.
2473 Any directory names are omitted. */);
2475 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2476 doc: /* The directory in which the Emacs executable was found, to run it.
2477 The value is nil if that directory's name is not known. */);
2479 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2480 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2481 In an installed Emacs, this is normally nil. It is non-nil if
2482 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2483 within the variable `invocation-directory' or its parent. For example,
2484 this is the case when running an uninstalled Emacs executable from its
2485 build directory. */);
2486 Vinstallation_directory = Qnil;
2488 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2489 doc: /* System locale for messages. */);
2490 Vsystem_messages_locale = Qnil;
2492 DEFVAR_LISP ("previous-system-messages-locale",
2493 Vprevious_system_messages_locale,
2494 doc: /* Most recently used system locale for messages. */);
2495 Vprevious_system_messages_locale = Qnil;
2497 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2498 doc: /* System locale for time. */);
2499 Vsystem_time_locale = Qnil;
2501 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2502 doc: /* Most recently used system locale for time. */);
2503 Vprevious_system_time_locale = Qnil;
2505 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2506 doc: /* Value of `current-time' before Emacs begins initialization. */);
2507 Vbefore_init_time = Qnil;
2509 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2510 doc: /* Value of `current-time' after loading the init files.
2511 This is nil during initialization. */);
2512 Vafter_init_time = Qnil;
2514 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2515 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2516 inhibit_x_resources = 0;
2518 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2519 doc: /* Short copyright string for this version of Emacs. */);
2520 Vemacs_copyright = build_string (emacs_copyright);
2522 DEFVAR_LISP ("emacs-version", Vemacs_version,
2523 doc: /* Version numbers of this version of Emacs. */);
2524 Vemacs_version = build_string (emacs_version);
2526 DEFVAR_LISP ("report-emacs-bug-address", Vreport_emacs_bug_address,
2527 doc: /* Address of mailing list for GNU Emacs bugs. */);
2528 Vreport_emacs_bug_address = build_string (emacs_bugreport);
2530 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2531 doc: /* Alist of dynamic libraries vs external files implementing them.
2532 Each element is a list (LIBRARY FILE...), where the car is a symbol
2533 representing a supported external library, and the rest are strings giving
2534 alternate filenames for that library.
2536 Emacs tries to load the library from the files in the order they appear on
2537 the list; if none is loaded, the running session of Emacs won't have access
2538 to that library.
2540 Note that image types `pbm' and `xbm' do not need entries in this variable
2541 because they do not depend on external libraries and are always available.
2543 Also note that this is not a generic facility for accessing external
2544 libraries; only those already known by Emacs will be loaded. */);
2545 Vdynamic_library_alist = Qnil;
2546 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2548 #ifdef WINDOWSNT
2549 Vlibrary_cache = Qnil;
2550 staticpro (&Vlibrary_cache);
2551 #endif