* minibuf.texi (Basic Completion): Clarify list form of completion table.
[emacs.git] / src / emacs.c
blobbc54f56b98a2501c77a3859f5850d90488e6ca52
1 /* Fully extensible Emacs, running on Unix, intended for GNU.
3 Copyright (C) 1985-1987, 1993-1995, 1997-1999, 2001-2012
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/>. */
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
26 #include <sys/types.h>
27 #include <sys/file.h>
28 #include <unistd.h>
30 #include <ignore-value.h>
32 #include "lisp.h"
34 #ifdef WINDOWSNT
35 #include <fcntl.h>
36 #include <windows.h> /* just for w32.h */
37 #include "w32.h"
38 #include "w32heap.h" /* for prototype of sbrk */
39 #endif
41 #ifdef HAVE_WINDOW_SYSTEM
42 #include TERM_HEADER
43 #endif /* HAVE_WINDOW_SYSTEM */
45 #ifdef NS_IMPL_GNUSTEP
46 /* At least under Debian, GSConfig is in a subdirectory. --Stef */
47 #include <GNUstepBase/GSConfig.h>
48 #endif
50 #include "commands.h"
51 #include "intervals.h"
52 #include "character.h"
53 #include "buffer.h"
54 #include "window.h"
56 #include "systty.h"
57 #include "atimer.h"
58 #include "blockinput.h"
59 #include "syssignal.h"
60 #include "process.h"
61 #include "frame.h"
62 #include "termhooks.h"
63 #include "keyboard.h"
64 #include "keymap.h"
66 #ifdef HAVE_GNUTLS
67 #include "gnutls.h"
68 #endif
70 #if (defined PROFILING \
71 && (defined __FreeBSD__ || defined GNU_LINUX || defined __MINGW32__))
72 # include <sys/gmon.h>
73 extern void moncontrol (int mode);
74 #endif
76 #ifdef HAVE_SETLOCALE
77 #include <locale.h>
78 #endif
80 #ifdef HAVE_SETRLIMIT
81 #include <sys/time.h>
82 #include <sys/resource.h>
83 #endif
85 #ifdef HAVE_PERSONALITY_LINUX32
86 #include <sys/personality.h>
87 #endif
89 #ifndef O_RDWR
90 #define O_RDWR 2
91 #endif
93 static const char emacs_version[] = VERSION;
94 static const char emacs_copyright[] = COPYRIGHT;
96 /* Empty lisp strings. To avoid having to build any others. */
97 Lisp_Object empty_unibyte_string, empty_multibyte_string;
99 #ifdef WINDOWSNT
100 /* Cache for externally loaded libraries. */
101 Lisp_Object Vlibrary_cache;
102 #endif
104 /* Set after Emacs has started up the first time.
105 Prevents reinitialization of the Lisp world and keymaps
106 on subsequent starts. */
107 bool initialized;
109 #ifdef DARWIN_OS
110 extern void unexec_init_emacs_zone (void);
111 #endif
113 #ifdef DOUG_LEA_MALLOC
114 /* Preserves a pointer to the memory allocated that copies that
115 static data inside glibc's malloc. */
116 static void *malloc_state_ptr;
117 /* From glibc, a routine that returns a copy of the malloc internal state. */
118 extern void *malloc_get_state (void);
119 /* From glibc, a routine that overwrites the malloc internal state. */
120 extern int malloc_set_state (void*);
121 /* True if the MALLOC_CHECK_ environment variable was set while
122 dumping. Used to work around a bug in glibc's malloc. */
123 static bool malloc_using_checking;
124 #endif
126 Lisp_Object Qfile_name_handler_alist;
128 Lisp_Object Qrisky_local_variable;
130 Lisp_Object Qkill_emacs;
132 /* If true, Emacs should not attempt to use a window-specific code,
133 but instead should use the virtual terminal under which it was started. */
134 bool inhibit_window_system;
136 /* If true, a filter or a sentinel is running. Tested to save the match
137 data on the first attempt to change it inside asynchronous code. */
138 bool running_asynch_code;
140 #if defined (HAVE_X_WINDOWS) || defined (HAVE_NS)
141 /* If true, -d was specified, meaning we're using some window system. */
142 bool display_arg;
143 #endif
145 /* An address near the bottom of the stack.
146 Tells GC how to save a copy of the stack. */
147 char *stack_bottom;
149 #if defined (DOUG_LEA_MALLOC) || defined (GNU_LINUX)
150 /* The address where the heap starts (from the first sbrk (0) call). */
151 static void *my_heap_start;
152 #endif
154 #ifdef GNU_LINUX
155 /* The gap between BSS end and heap start as far as we can tell. */
156 static uprintmax_t heap_bss_diff;
157 #endif
159 /* True means running Emacs without interactive terminal. */
160 bool noninteractive;
162 /* True means remove site-lisp directories from load-path. */
163 bool no_site_lisp;
165 /* Name for the server started by the daemon.*/
166 static char *daemon_name;
168 /* Pipe used to send exit notification to the daemon parent at
169 startup. */
170 int daemon_pipe[2];
172 /* Save argv and argc. */
173 char **initial_argv;
174 int initial_argc;
176 static void sort_args (int argc, char **argv);
177 static void syms_of_emacs (void);
179 /* MSVC needs each string be shorter than 2048 bytes, so the usage
180 strings below are split to not overflow this limit. */
181 #define USAGE1 "\
182 Usage: %s [OPTION-OR-FILENAME]...\n\
184 Run Emacs, the extensible, customizable, self-documenting real-time\n\
185 display editor. The recommended way to start Emacs for normal editing\n\
186 is with no options at all.\n\
188 Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n\
189 read the main documentation for these command-line arguments.\n\
191 Initialization options:\n\
193 --batch do not do interactive display; implies -q\n\
194 --chdir DIR change to directory DIR\n\
195 --daemon start a server in the background\n\
196 --debug-init enable Emacs Lisp debugger for init file\n\
197 --display, -d DISPLAY use X server DISPLAY\n\
198 --no-desktop do not load a saved desktop\n\
199 --no-init-file, -q load neither ~/.emacs nor default.el\n\
200 --no-shared-memory, -nl do not use shared memory\n\
201 --no-site-file do not load site-start.el\n\
202 --no-site-lisp, -nsl do not add site-lisp directories to load-path\n\
203 --no-splash do not display a splash screen on startup\n\
204 --no-window-system, -nw do not communicate with X, ignoring $DISPLAY\n\
205 --quick, -Q equivalent to:\n\
206 -q --no-site-file --no-site-lisp --no-splash\n\
207 --script FILE run FILE as an Emacs Lisp script\n\
208 --terminal, -t DEVICE use DEVICE for terminal I/O\n\
209 --user, -u USER load ~USER/.emacs instead of your own\n\
210 \n%s"
212 #define USAGE2 "\
213 Action options:\n\
215 FILE visit FILE using find-file\n\
216 +LINE go to line LINE in next FILE\n\
217 +LINE:COLUMN go to line LINE, column COLUMN, in next FILE\n\
218 --directory, -L DIR add DIR to variable load-path\n\
219 --eval EXPR evaluate Emacs Lisp expression EXPR\n\
220 --execute EXPR evaluate Emacs Lisp expression EXPR\n\
221 --file FILE visit FILE using find-file\n\
222 --find-file FILE visit FILE using find-file\n\
223 --funcall, -f FUNC call Emacs Lisp function FUNC with no arguments\n\
224 --insert FILE insert contents of FILE into current buffer\n\
225 --kill exit without asking for confirmation\n\
226 --load, -l FILE load Emacs Lisp FILE using the load function\n\
227 --visit FILE visit FILE using find-file\n\
230 #define USAGE3 "\
231 Display options:\n\
233 --background-color, -bg COLOR window background color\n\
234 --basic-display, -D disable many display features;\n\
235 used for debugging Emacs\n\
236 --border-color, -bd COLOR main border color\n\
237 --border-width, -bw WIDTH width of main border\n\
238 --color, --color=MODE override color mode for character terminals;\n\
239 MODE defaults to `auto', and\n\
240 can also be `never', `always',\n\
241 or a mode name like `ansi8'\n\
242 --cursor-color, -cr COLOR color of the Emacs cursor indicating point\n\
243 --font, -fn FONT default font; must be fixed-width\n\
244 --foreground-color, -fg COLOR window foreground color\n\
245 --fullheight, -fh make the first frame high as the screen\n\
246 --fullscreen, -fs make the first frame fullscreen\n\
247 --fullwidth, -fw make the first frame wide as the screen\n\
248 --maximized, -mm make the first frame maximized\n\
249 --geometry, -g GEOMETRY window geometry\n\
250 --no-bitmap-icon, -nbi do not use picture of gnu for Emacs icon\n\
251 --iconic start Emacs in iconified state\n\
252 --internal-border, -ib WIDTH width between text and main border\n\
253 --line-spacing, -lsp PIXELS additional space to put between lines\n\
254 --mouse-color, -ms COLOR mouse cursor color in Emacs window\n\
255 --name NAME title for initial Emacs frame\n\
256 --no-blinking-cursor, -nbc disable blinking cursor\n\
257 --reverse-video, -r, -rv switch foreground and background\n\
258 --title, -T TITLE title for initial Emacs frame\n\
259 --vertical-scroll-bars, -vb enable vertical scroll bars\n\
260 --xrm XRESOURCES set additional X resources\n\
261 --parent-id XID set parent window\n\
262 --help display this help and exit\n\
263 --version output version information and exit\n\
266 #define USAGE4 "\
267 You can generally also specify long option names with a single -; for\n\
268 example, -batch as well as --batch. You can use any unambiguous\n\
269 abbreviation for a --option.\n\
271 Various environment variables and window system resources also affect\n\
272 Emacs' operation. See the main documentation.\n\
274 Report bugs to bug-gnu-emacs@gnu.org. First, please see the Bugs\n\
275 section of the Emacs manual or the file BUGS.\n"
278 /* True if handling a fatal error already. */
279 bool fatal_error_in_progress;
281 #ifdef HAVE_NS
282 /* NS autrelease pool, for memory management. */
283 static void *ns_pool;
284 #endif
288 /* Report a fatal error due to signal SIG, output a backtrace of at
289 most BACKTRACE_LIMIT lines, and exit. */
290 _Noreturn void
291 terminate_due_to_signal (int sig, int backtrace_limit)
293 signal (sig, SIG_DFL);
294 totally_unblock_input ();
296 /* If fatal error occurs in code below, avoid infinite recursion. */
297 if (! fatal_error_in_progress)
299 fatal_error_in_progress = 1;
301 if (sig == SIGTERM || sig == SIGHUP || sig == SIGINT)
302 Fkill_emacs (make_number (sig));
304 shut_down_emacs (sig, Qnil);
305 emacs_backtrace (backtrace_limit);
308 /* Signal the same code; this time it will really be fatal.
309 Since we're in a signal handler, the signal is blocked, so we
310 have to unblock it if we want to really receive it. */
311 #ifndef MSDOS
313 sigset_t unblocked;
314 sigemptyset (&unblocked);
315 sigaddset (&unblocked, sig);
316 pthread_sigmask (SIG_UNBLOCK, &unblocked, 0);
318 #endif
320 emacs_raise (sig);
322 /* This shouldn't be executed, but it prevents a warning. */
323 exit (1);
326 #ifdef SIGDANGER
328 /* Handler for SIGDANGER. */
329 static void
330 handle_danger_signal (int sig)
332 malloc_warning ("Operating system warns that virtual memory is running low.\n");
334 /* It might be unsafe to call do_auto_save now. */
335 force_auto_save_soon ();
338 static void
339 deliver_danger_signal (int sig)
341 deliver_process_signal (sig, handle_danger_signal);
343 #endif
345 /* Code for dealing with Lisp access to the Unix command line. */
347 static void
348 init_cmdargs (int argc, char **argv, int skip_args)
350 register int i;
351 Lisp_Object name, dir, handler;
352 ptrdiff_t count = SPECPDL_INDEX ();
353 Lisp_Object raw_name;
355 initial_argv = argv;
356 initial_argc = argc;
358 raw_name = build_string (argv[0]);
360 /* Add /: to the front of the name
361 if it would otherwise be treated as magic. */
362 handler = Ffind_file_name_handler (raw_name, Qt);
363 if (! NILP (handler))
364 raw_name = concat2 (build_string ("/:"), raw_name);
366 Vinvocation_name = Ffile_name_nondirectory (raw_name);
367 Vinvocation_directory = Ffile_name_directory (raw_name);
369 /* If we got no directory in argv[0], search PATH to find where
370 Emacs actually came from. */
371 if (NILP (Vinvocation_directory))
373 Lisp_Object found;
374 int yes = openp (Vexec_path, Vinvocation_name,
375 Vexec_suffixes, &found, make_number (X_OK));
376 if (yes == 1)
378 /* Add /: to the front of the name
379 if it would otherwise be treated as magic. */
380 handler = Ffind_file_name_handler (found, Qt);
381 if (! NILP (handler))
382 found = concat2 (build_string ("/:"), found);
383 Vinvocation_directory = Ffile_name_directory (found);
387 if (!NILP (Vinvocation_directory)
388 && NILP (Ffile_name_absolute_p (Vinvocation_directory)))
389 /* Emacs was started with relative path, like ./emacs.
390 Make it absolute. */
391 Vinvocation_directory = Fexpand_file_name (Vinvocation_directory, Qnil);
393 Vinstallation_directory = Qnil;
395 if (!NILP (Vinvocation_directory))
397 dir = Vinvocation_directory;
398 #ifdef WINDOWSNT
399 /* If we are running from the build directory, set DIR to the
400 src subdirectory of the Emacs tree, like on Posix
401 platforms. */
402 if (SBYTES (dir) > sizeof ("/i386/") - 1
403 && 0 == strcmp (SSDATA (dir) + SBYTES (dir) - sizeof ("/i386/") + 1,
404 "/i386/"))
405 dir = Fexpand_file_name (build_string ("../.."), dir);
406 #else /* !WINDOWSNT */
407 #endif
408 name = Fexpand_file_name (Vinvocation_name, dir);
409 while (1)
411 Lisp_Object tem, lib_src_exists;
412 Lisp_Object etc_exists, info_exists;
414 /* See if dir contains subdirs for use by Emacs.
415 Check for the ones that would exist in a build directory,
416 not including lisp and info. */
417 tem = Fexpand_file_name (build_string ("lib-src"), dir);
418 lib_src_exists = Ffile_exists_p (tem);
420 #ifdef MSDOS
421 /* MSDOS installations frequently remove lib-src, but we still
422 must set installation-directory, or else info won't find
423 its files (it uses the value of installation-directory). */
424 tem = Fexpand_file_name (build_string ("info"), dir);
425 info_exists = Ffile_exists_p (tem);
426 #else
427 info_exists = Qnil;
428 #endif
430 if (!NILP (lib_src_exists) || !NILP (info_exists))
432 tem = Fexpand_file_name (build_string ("etc"), dir);
433 etc_exists = Ffile_exists_p (tem);
434 if (!NILP (etc_exists))
436 Vinstallation_directory
437 = Ffile_name_as_directory (dir);
438 break;
442 /* See if dir's parent contains those subdirs. */
443 tem = Fexpand_file_name (build_string ("../lib-src"), dir);
444 lib_src_exists = Ffile_exists_p (tem);
447 #ifdef MSDOS
448 /* See the MSDOS commentary above. */
449 tem = Fexpand_file_name (build_string ("../info"), dir);
450 info_exists = Ffile_exists_p (tem);
451 #else
452 info_exists = Qnil;
453 #endif
455 if (!NILP (lib_src_exists) || !NILP (info_exists))
457 tem = Fexpand_file_name (build_string ("../etc"), dir);
458 etc_exists = Ffile_exists_p (tem);
459 if (!NILP (etc_exists))
461 tem = Fexpand_file_name (build_string (".."), dir);
462 Vinstallation_directory
463 = Ffile_name_as_directory (tem);
464 break;
468 /* If the Emacs executable is actually a link,
469 next try the dir that the link points into. */
470 tem = Ffile_symlink_p (name);
471 if (!NILP (tem))
473 name = Fexpand_file_name (tem, dir);
474 dir = Ffile_name_directory (name);
476 else
477 break;
481 Vcommand_line_args = Qnil;
483 for (i = argc - 1; i >= 0; i--)
485 if (i == 0 || i > skip_args)
486 /* For the moment, we keep arguments as is in unibyte strings.
487 They are decoded in the function command-line after we know
488 locale-coding-system. */
489 Vcommand_line_args
490 = Fcons (make_unibyte_string (argv[i], strlen (argv[i])),
491 Vcommand_line_args);
494 unbind_to (count, Qnil);
497 DEFUN ("invocation-name", Finvocation_name, Sinvocation_name, 0, 0, 0,
498 doc: /* Return the program name that was used to run Emacs.
499 Any directory names are omitted. */)
500 (void)
502 return Fcopy_sequence (Vinvocation_name);
505 DEFUN ("invocation-directory", Finvocation_directory, Sinvocation_directory,
506 0, 0, 0,
507 doc: /* Return the directory name in which the Emacs executable was located. */)
508 (void)
510 return Fcopy_sequence (Vinvocation_directory);
514 #ifdef HAVE_TZSET
515 /* A valid but unlikely value for the TZ environment value.
516 It is OK (though a bit slower) if the user actually chooses this value. */
517 static char dump_tz[] = "UtC0";
518 #endif
520 #ifndef ORDINARY_LINK
521 /* We don't include crtbegin.o and crtend.o in the link,
522 so these functions and variables might be missed.
523 Provide dummy definitions to avoid error.
524 (We don't have any real constructors or destructors.) */
525 #ifdef __GNUC__
527 /* Define a dummy function F. Declare F too, to pacify gcc
528 -Wmissing-prototypes. */
529 #define DEFINE_DUMMY_FUNCTION(f) \
530 void f (void) ATTRIBUTE_CONST EXTERNALLY_VISIBLE; void f (void) {}
532 #ifndef GCC_CTORS_IN_LIBC
533 DEFINE_DUMMY_FUNCTION (__do_global_ctors)
534 DEFINE_DUMMY_FUNCTION (__do_global_ctors_aux)
535 DEFINE_DUMMY_FUNCTION (__do_global_dtors)
536 /* GNU/Linux has a bug in its library; avoid an error. */
537 #ifndef GNU_LINUX
538 char * __CTOR_LIST__[2] EXTERNALLY_VISIBLE = { (char *) (-1), 0 };
539 #endif
540 char * __DTOR_LIST__[2] EXTERNALLY_VISIBLE = { (char *) (-1), 0 };
541 #endif /* GCC_CTORS_IN_LIBC */
542 DEFINE_DUMMY_FUNCTION (__main)
543 #endif /* __GNUC__ */
544 #endif /* ORDINARY_LINK */
546 /* Test whether the next argument in ARGV matches SSTR or a prefix of
547 LSTR (at least MINLEN characters). If so, then if VALPTR is non-null
548 (the argument is supposed to have a value) store in *VALPTR either
549 the next argument or the portion of this one after the equal sign.
550 ARGV is read starting at position *SKIPPTR; this index is advanced
551 by the number of arguments used.
553 Too bad we can't just use getopt for all of this, but we don't have
554 enough information to do it right. */
556 static bool
557 argmatch (char **argv, int argc, const char *sstr, const char *lstr,
558 int minlen, char **valptr, int *skipptr)
560 char *p = NULL;
561 ptrdiff_t arglen;
562 char *arg;
564 /* Don't access argv[argc]; give up in advance. */
565 if (argc <= *skipptr + 1)
566 return 0;
568 arg = argv[*skipptr+1];
569 if (arg == NULL)
570 return 0;
571 if (strcmp (arg, sstr) == 0)
573 if (valptr != NULL)
575 *valptr = argv[*skipptr+2];
576 *skipptr += 2;
578 else
579 *skipptr += 1;
580 return 1;
582 arglen = (valptr != NULL && (p = strchr (arg, '=')) != NULL
583 ? p - arg : strlen (arg));
584 if (lstr == 0 || arglen < minlen || strncmp (arg, lstr, arglen) != 0)
585 return 0;
586 else if (valptr == NULL)
588 *skipptr += 1;
589 return 1;
591 else if (p != NULL)
593 *valptr = p+1;
594 *skipptr += 1;
595 return 1;
597 else if (argv[*skipptr+2] != NULL)
599 *valptr = argv[*skipptr+2];
600 *skipptr += 2;
601 return 1;
603 else
605 return 0;
609 #ifdef DOUG_LEA_MALLOC
611 /* malloc can be invoked even before main (e.g. by the dynamic
612 linker), so the dumped malloc state must be restored as early as
613 possible using this special hook. */
615 static void
616 malloc_initialize_hook (void)
618 if (initialized)
620 if (!malloc_using_checking)
621 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
622 ignored if the heap to be restored was constructed without
623 malloc checking. Can't use unsetenv, since that calls malloc. */
625 char **p;
627 for (p = environ; p && *p; p++)
628 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
631 *p = p[1];
632 while (*++p);
633 break;
637 malloc_set_state (malloc_state_ptr);
638 #ifndef XMALLOC_OVERRUN_CHECK
639 free (malloc_state_ptr);
640 #endif
642 else
644 if (my_heap_start == 0)
645 my_heap_start = sbrk (0);
646 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
650 void (*__malloc_initialize_hook) (void) EXTERNALLY_VISIBLE = malloc_initialize_hook;
652 #endif /* DOUG_LEA_MALLOC */
655 /* ARGSUSED */
657 main (int argc, char **argv)
659 #if GC_MARK_STACK
660 Lisp_Object dummy;
661 #endif
662 char stack_bottom_variable;
663 bool do_initial_setlocale;
664 bool dumping;
665 int skip_args = 0;
666 #ifdef HAVE_SETRLIMIT
667 struct rlimit rlim;
668 #endif
669 bool no_loadup = 0;
670 char *junk = 0;
671 char *dname_arg = 0;
672 #ifdef NS_IMPL_COCOA
673 char dname_arg2[80];
674 #endif
675 char *ch_to_dir;
677 #if GC_MARK_STACK
678 stack_base = &dummy;
679 #endif
681 #if defined (USE_GTK) && defined (G_SLICE_ALWAYS_MALLOC)
682 /* This is used by the Cygwin build. */
683 setenv ("G_SLICE", "always-malloc", 1);
684 #endif
686 #ifdef GNU_LINUX
687 if (!initialized)
689 extern char my_endbss[];
690 extern char *my_endbss_static;
692 if (my_heap_start == 0)
693 my_heap_start = sbrk (0);
695 heap_bss_diff = (char *)my_heap_start - max (my_endbss, my_endbss_static);
697 #endif
699 #ifdef RUN_TIME_REMAP
700 if (initialized)
701 run_time_remap (argv[0]);
702 #endif
704 /* If using unexmacosx.c (set by s/darwin.h), we must do this. */
705 #ifdef DARWIN_OS
706 if (!initialized)
707 unexec_init_emacs_zone ();
708 #endif
710 sort_args (argc, argv);
711 argc = 0;
712 while (argv[argc]) argc++;
714 if (argmatch (argv, argc, "-version", "--version", 3, NULL, &skip_args))
716 const char *version, *copyright;
717 if (initialized)
719 Lisp_Object tem, tem2;
720 tem = Fsymbol_value (intern_c_string ("emacs-version"));
721 tem2 = Fsymbol_value (intern_c_string ("emacs-copyright"));
722 if (!STRINGP (tem))
724 fprintf (stderr, "Invalid value of `emacs-version'\n");
725 exit (1);
727 if (!STRINGP (tem2))
729 fprintf (stderr, "Invalid value of `emacs-copyright'\n");
730 exit (1);
732 else
734 version = SSDATA (tem);
735 copyright = SSDATA (tem2);
738 else
740 version = emacs_version;
741 copyright = emacs_copyright;
743 printf ("GNU Emacs %s\n", version);
744 printf ("%s\n", copyright);
745 printf ("GNU Emacs comes with ABSOLUTELY NO WARRANTY.\n");
746 printf ("You may redistribute copies of Emacs\n");
747 printf ("under the terms of the GNU General Public License.\n");
748 printf ("For more information about these matters, ");
749 printf ("see the file named COPYING.\n");
750 exit (0);
753 if (argmatch (argv, argc, "-chdir", "--chdir", 4, &ch_to_dir, &skip_args))
754 if (chdir (ch_to_dir) == -1)
756 fprintf (stderr, "%s: Can't chdir to %s: %s\n",
757 argv[0], ch_to_dir, strerror (errno));
758 exit (1);
761 dumping = !initialized && (strcmp (argv[argc - 1], "dump") == 0
762 || strcmp (argv[argc - 1], "bootstrap") == 0);
764 #ifdef HAVE_PERSONALITY_LINUX32
765 if (dumping && ! getenv ("EMACS_HEAP_EXEC"))
767 static char heapexec[] = "EMACS_HEAP_EXEC=true";
768 /* Set this so we only do this once. */
769 putenv (heapexec);
771 /* A flag to turn off address randomization which is introduced
772 in linux kernel shipped with fedora core 4 */
773 #define ADD_NO_RANDOMIZE 0x0040000
774 personality (PER_LINUX32 | ADD_NO_RANDOMIZE);
775 #undef ADD_NO_RANDOMIZE
777 execvp (argv[0], argv);
779 /* If the exec fails, try to dump anyway. */
780 perror ("execvp");
782 #endif /* HAVE_PERSONALITY_LINUX32 */
784 #if defined (HAVE_SETRLIMIT) && defined (RLIMIT_STACK)
785 /* Extend the stack space available.
786 Don't do that if dumping, since some systems (e.g. DJGPP)
787 might define a smaller stack limit at that time. */
788 if (1
789 #ifndef CANNOT_DUMP
790 && (!noninteractive || initialized)
791 #endif
792 && !getrlimit (RLIMIT_STACK, &rlim))
794 long newlim;
795 extern size_t re_max_failures;
796 /* Approximate the amount regex.c needs per unit of re_max_failures. */
797 int ratio = 20 * sizeof (char *);
798 /* Then add 33% to cover the size of the smaller stacks that regex.c
799 successively allocates and discards, on its way to the maximum. */
800 ratio += ratio / 3;
801 /* Add in some extra to cover
802 what we're likely to use for other reasons. */
803 newlim = re_max_failures * ratio + 200000;
804 #ifdef __NetBSD__
805 /* NetBSD (at least NetBSD 1.2G and former) has a bug in its
806 stack allocation routine for new process that the allocation
807 fails if stack limit is not on page boundary. So, round up the
808 new limit to page boundary. */
809 newlim = (newlim + getpagesize () - 1) / getpagesize () * getpagesize ();
810 #endif
811 if (newlim > rlim.rlim_max)
813 newlim = rlim.rlim_max;
814 /* Don't let regex.c overflow the stack we have. */
815 re_max_failures = (newlim - 200000) / ratio;
817 if (rlim.rlim_cur < newlim)
818 rlim.rlim_cur = newlim;
820 setrlimit (RLIMIT_STACK, &rlim);
822 #endif /* HAVE_SETRLIMIT and RLIMIT_STACK */
824 /* Record (approximately) where the stack begins. */
825 stack_bottom = &stack_bottom_variable;
827 clearerr (stdin);
829 #ifndef SYSTEM_MALLOC
830 /* Arrange to get warning messages as memory fills up. */
831 memory_warnings (0, malloc_warning);
833 /* Call malloc at least once, to run malloc_initialize_hook.
834 Also call realloc and free for consistency. */
835 free (realloc (malloc (4), 4));
837 #endif /* not SYSTEM_MALLOC */
839 #if defined (MSDOS) || defined (WINDOWSNT)
840 /* We do all file input/output as binary files. When we need to translate
841 newlines, we do that manually. */
842 _fmode = O_BINARY;
843 #endif /* MSDOS || WINDOWSNT */
845 #ifdef MSDOS
846 if (!isatty (fileno (stdin)))
847 setmode (fileno (stdin), O_BINARY);
848 if (!isatty (fileno (stdout)))
850 fflush (stdout);
851 setmode (fileno (stdout), O_BINARY);
853 #endif /* MSDOS */
855 /* Skip initial setlocale if LC_ALL is "C", as it's not needed in that case.
856 The build procedure uses this while dumping, to ensure that the
857 dumped Emacs does not have its system locale tables initialized,
858 as that might cause screwups when the dumped Emacs starts up. */
860 char *lc_all = getenv ("LC_ALL");
861 do_initial_setlocale = ! lc_all || strcmp (lc_all, "C");
864 /* Set locale now, so that initial error messages are localized properly.
865 fixup_locale must wait until later, since it builds strings. */
866 if (do_initial_setlocale)
867 setlocale (LC_ALL, "");
869 inhibit_window_system = 0;
871 /* Handle the -t switch, which specifies filename to use as terminal. */
872 while (1)
874 char *term;
875 if (argmatch (argv, argc, "-t", "--terminal", 4, &term, &skip_args))
877 int result;
878 emacs_close (0);
879 emacs_close (1);
880 result = emacs_open (term, O_RDWR, 0);
881 if (result < 0 || dup (0) < 0)
883 char *errstring = strerror (errno);
884 fprintf (stderr, "%s: %s: %s\n", argv[0], term, errstring);
885 exit (1);
887 if (! isatty (0))
889 fprintf (stderr, "%s: %s: not a tty\n", argv[0], term);
890 exit (1);
892 fprintf (stderr, "Using %s\n", term);
893 #ifdef HAVE_WINDOW_SYSTEM
894 inhibit_window_system = 1; /* -t => -nw */
895 #endif
897 else
898 break;
901 /* Command line option --no-windows is deprecated and thus not mentioned
902 in the manual and usage information. */
903 if (argmatch (argv, argc, "-nw", "--no-window-system", 6, NULL, &skip_args)
904 || argmatch (argv, argc, "-nw", "--no-windows", 6, NULL, &skip_args))
905 inhibit_window_system = 1;
907 /* Handle the -batch switch, which means don't do interactive display. */
908 noninteractive = 0;
909 if (argmatch (argv, argc, "-batch", "--batch", 5, NULL, &skip_args))
911 noninteractive = 1;
912 Vundo_outer_limit = Qnil;
914 if (argmatch (argv, argc, "-script", "--script", 3, &junk, &skip_args))
916 noninteractive = 1; /* Set batch mode. */
917 /* Convert --script to -scriptload, un-skip it, and sort again
918 so that it will be handled in proper sequence. */
919 /* FIXME broken for --script=FILE - is that supposed to work? */
920 argv[skip_args - 1] = (char *) "-scriptload";
921 skip_args -= 2;
922 sort_args (argc, argv);
925 /* Handle the --help option, which gives a usage message. */
926 if (argmatch (argv, argc, "-help", "--help", 3, NULL, &skip_args))
928 printf (USAGE1, argv[0], USAGE2);
929 printf (USAGE3);
930 printf (USAGE4);
931 exit (0);
934 if (argmatch (argv, argc, "-daemon", "--daemon", 5, NULL, &skip_args)
935 || argmatch (argv, argc, "-daemon", "--daemon", 5, &dname_arg, &skip_args))
937 #ifndef DOS_NT
938 pid_t f;
940 /* Start as a daemon: fork a new child process which will run the
941 rest of the initialization code, then exit.
943 Detaching a daemon requires the following steps:
944 - fork
945 - setsid
946 - exit the parent
947 - close the tty file-descriptors
949 We only want to do the last 2 steps once the daemon is ready to
950 serve requests, i.e. after loading .emacs (initialization).
951 OTOH initialization may start subprocesses (e.g. ispell) and these
952 should be run from the proper process (the one that will end up
953 running as daemon) and with the proper "session id" in order for
954 them to keep working after detaching, so fork and setsid need to be
955 performed before initialization.
957 We want to avoid exiting before the server socket is ready, so
958 use a pipe for synchronization. The parent waits for the child
959 to close its end of the pipe (using `daemon-initialized')
960 before exiting. */
961 if (pipe (daemon_pipe) == -1)
963 fprintf (stderr, "Cannot pipe!\n");
964 exit (1);
967 #ifndef NS_IMPL_COCOA
968 #ifdef USE_GTK
969 fprintf (stderr, "\nWarning: due to a long standing Gtk+ bug\nhttp://bugzilla.gnome.org/show_bug.cgi?id=85715\n\
970 Emacs might crash when run in daemon mode and the X11 connection is unexpectedly lost.\n\
971 Using an Emacs configured with --with-x-toolkit=lucid does not have this problem.\n");
972 #endif
973 f = fork ();
974 #else /* NS_IMPL_COCOA */
975 /* Under Cocoa we must do fork+exec as CoreFoundation lib fails in
976 forked process: http://developer.apple.com/ReleaseNotes/
977 CoreFoundation/CoreFoundation.html)
978 We mark being in the exec'd process by a daemon name argument of
979 form "--daemon=\nFD0,FD1\nNAME" where FD are the pipe file descriptors,
980 NAME is the original daemon name, if any. */
981 if (!dname_arg || !strchr (dname_arg, '\n'))
982 f = fork (); /* in orig */
983 else
984 f = 0; /* in exec'd */
985 #endif /* NS_IMPL_COCOA */
986 if (f > 0)
988 int retval;
989 char buf[1];
991 /* Close unused writing end of the pipe. */
992 close (daemon_pipe[1]);
994 /* Just wait for the child to close its end of the pipe. */
997 retval = read (daemon_pipe[0], &buf, 1);
999 while (retval == -1 && errno == EINTR);
1001 if (retval < 0)
1003 fprintf (stderr, "Error reading status from child\n");
1004 exit (1);
1006 else if (retval == 0)
1008 fprintf (stderr, "Error: server did not start correctly\n");
1009 exit (1);
1012 close (daemon_pipe[0]);
1013 exit (0);
1015 if (f < 0)
1017 fprintf (stderr, "Cannot fork!\n");
1018 exit (1);
1021 #ifdef NS_IMPL_COCOA
1023 /* In orig process, forked as child, OR in exec'd. */
1024 if (!dname_arg || !strchr (dname_arg, '\n'))
1025 { /* In orig, child: now exec w/special daemon name. */
1026 char fdStr[80];
1027 int fdStrlen =
1028 snprintf (fdStr, sizeof fdStr,
1029 "--daemon=\n%d,%d\n%s", daemon_pipe[0],
1030 daemon_pipe[1], dname_arg ? dname_arg : "");
1032 if (! (0 <= fdStrlen && fdStrlen < sizeof fdStr))
1034 fprintf (stderr, "daemon: child name too long\n");
1035 exit (1);
1038 argv[skip_args] = fdStr;
1040 execv (argv[0], argv);
1041 fprintf (stderr, "emacs daemon: exec failed: %d\n", errno);
1042 exit (1);
1045 /* In exec'd: parse special dname into pipe and name info. */
1046 if (!dname_arg || !strchr (dname_arg, '\n')
1047 || strlen (dname_arg) < 1 || strlen (dname_arg) > 70)
1049 fprintf (stderr, "emacs daemon: daemon name absent or too long\n");
1050 exit (1);
1052 dname_arg2[0] = '\0';
1053 sscanf (dname_arg, "\n%d,%d\n%s", &(daemon_pipe[0]), &(daemon_pipe[1]),
1054 dname_arg2);
1055 dname_arg = *dname_arg2 ? dname_arg2 : NULL;
1057 #endif /* NS_IMPL_COCOA */
1059 if (dname_arg)
1060 daemon_name = xstrdup (dname_arg);
1061 /* Close unused reading end of the pipe. */
1062 close (daemon_pipe[0]);
1063 /* Make sure that the used end of the pipe is closed on exec, so
1064 that it is not accessible to programs started from .emacs. */
1065 fcntl (daemon_pipe[1], F_SETFD, FD_CLOEXEC);
1067 #ifdef HAVE_SETSID
1068 setsid ();
1069 #endif
1070 #else /* DOS_NT */
1071 fprintf (stderr, "This platform does not support the -daemon flag.\n");
1072 exit (1);
1073 #endif /* DOS_NT */
1076 if (! noninteractive)
1078 #if defined (USG5) && defined (INTERRUPT_INPUT)
1079 setpgrp ();
1080 #endif
1081 #if defined (HAVE_PTHREAD) && !defined (SYSTEM_MALLOC) && !defined (DOUG_LEA_MALLOC)
1083 extern void malloc_enable_thread (void);
1085 malloc_enable_thread ();
1087 #endif
1090 init_signals (dumping);
1092 noninteractive1 = noninteractive;
1094 /* Perform basic initializations (not merely interning symbols). */
1096 if (!initialized)
1098 init_alloc_once ();
1099 init_obarray ();
1100 init_eval_once ();
1101 init_charset_once ();
1102 init_coding_once ();
1103 init_syntax_once (); /* Create standard syntax table. */
1104 init_category_once (); /* Create standard category table. */
1105 /* Must be done before init_buffer. */
1106 init_casetab_once ();
1107 init_buffer_once (); /* Create buffer table and some buffers. */
1108 init_minibuf_once (); /* Create list of minibuffers. */
1109 /* Must precede init_window_once. */
1111 /* Call syms_of_xfaces before init_window_once because that
1112 function creates Vterminal_frame. Termcap frames now use
1113 faces, and the face implementation uses some symbols as
1114 face names. */
1115 syms_of_xfaces ();
1116 /* XXX syms_of_keyboard uses some symbols in keymap.c. It would
1117 be better to arrange things not to have this dependency. */
1118 syms_of_keymap ();
1119 /* Call syms_of_keyboard before init_window_once because
1120 keyboard sets up symbols that include some face names that
1121 the X support will want to use. This can happen when
1122 CANNOT_DUMP is defined. */
1123 syms_of_keyboard ();
1125 /* Called before syms_of_fileio, because it sets up Qerror_condition. */
1126 syms_of_data ();
1127 syms_of_fileio ();
1128 /* Before syms_of_coding to initialize Vgc_cons_threshold. */
1129 syms_of_alloc ();
1130 /* Before syms_of_coding because it initializes Qcharsetp. */
1131 syms_of_charset ();
1132 /* Before init_window_once, because it sets up the
1133 Vcoding_system_hash_table. */
1134 syms_of_coding (); /* This should be after syms_of_fileio. */
1136 init_window_once (); /* Init the window system. */
1137 #ifdef HAVE_WINDOW_SYSTEM
1138 init_fringe_once (); /* Swap bitmaps if necessary. */
1139 #endif /* HAVE_WINDOW_SYSTEM */
1142 init_alloc ();
1144 if (do_initial_setlocale)
1146 fixup_locale ();
1147 Vsystem_messages_locale = Vprevious_system_messages_locale;
1148 Vsystem_time_locale = Vprevious_system_time_locale;
1151 init_eval ();
1152 init_atimer ();
1153 running_asynch_code = 0;
1154 init_random ();
1156 no_loadup
1157 = argmatch (argv, argc, "-nl", "--no-loadup", 6, NULL, &skip_args);
1159 no_site_lisp
1160 = argmatch (argv, argc, "-nsl", "--no-site-lisp", 11, NULL, &skip_args);
1162 #ifdef HAVE_NS
1163 ns_pool = ns_alloc_autorelease_pool ();
1164 if (!noninteractive)
1166 #ifdef NS_IMPL_COCOA
1167 if (skip_args < argc)
1169 /* FIXME: Do the right thing if getenv returns NULL, or if
1170 chdir fails. */
1171 if (!strncmp (argv[skip_args], "-psn", 4))
1173 skip_args += 1;
1174 chdir (getenv ("HOME"));
1176 else if (skip_args+1 < argc && !strncmp (argv[skip_args+1], "-psn", 4))
1178 skip_args += 2;
1179 chdir (getenv ("HOME"));
1182 #endif /* COCOA */
1184 #endif /* HAVE_NS */
1186 #ifdef HAVE_X_WINDOWS
1187 /* Stupid kludge to catch command-line display spec. We can't
1188 handle this argument entirely in window system dependent code
1189 because we don't even know which window system dependent code
1190 to run until we've recognized this argument. */
1192 char *displayname = 0;
1193 int count_before = skip_args;
1195 /* Skip any number of -d options, but only use the last one. */
1196 while (1)
1198 int count_before_this = skip_args;
1200 if (argmatch (argv, argc, "-d", "--display", 3, &displayname, &skip_args))
1201 display_arg = 1;
1202 else if (argmatch (argv, argc, "-display", 0, 3, &displayname, &skip_args))
1203 display_arg = 1;
1204 else
1205 break;
1207 count_before = count_before_this;
1210 /* If we have the form --display=NAME,
1211 convert it into -d name.
1212 This requires inserting a new element into argv. */
1213 if (displayname && count_before < skip_args)
1215 if (skip_args == count_before + 1)
1217 memmove (argv + count_before + 3, argv + count_before + 2,
1218 (argc - (count_before + 2)) * sizeof *argv);
1219 argv[count_before + 2] = displayname;
1220 argc++;
1222 argv[count_before + 1] = (char *) "-d";
1225 if (! no_site_lisp)
1227 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1228 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1229 no_site_lisp = 1;
1232 /* Don't actually discard this arg. */
1233 skip_args = count_before;
1235 #else /* !HAVE_X_WINDOWS */
1236 if (! no_site_lisp)
1238 int count_before = skip_args;
1240 if (argmatch (argv, argc, "-Q", "--quick", 3, NULL, &skip_args)
1241 || argmatch (argv, argc, "-quick", 0, 2, NULL, &skip_args))
1242 no_site_lisp = 1;
1244 skip_args = count_before;
1246 #endif
1248 /* argmatch must not be used after here,
1249 except when building temacs
1250 because the -d argument has not been skipped in skip_args. */
1252 #ifdef MSDOS
1253 /* Call early 'cause init_environment needs it. */
1254 init_dosfns ();
1255 /* Set defaults for several environment variables. */
1256 if (initialized)
1257 init_environment (argc, argv, skip_args);
1258 else
1259 tzset ();
1260 #endif /* MSDOS */
1262 #ifdef WINDOWSNT
1263 globals_of_w32 ();
1264 /* Initialize environment from registry settings. */
1265 init_environment (argv);
1266 init_ntproc (dumping); /* must precede init_editfns. */
1267 #endif
1269 /* Initialize and GC-protect Vinitial_environment and
1270 Vprocess_environment before set_initial_environment fills them
1271 in. */
1272 if (!initialized)
1273 syms_of_callproc ();
1274 /* egetenv is a pretty low-level facility, which may get called in
1275 many circumstances; it seems flimsy to put off initializing it
1276 until calling init_callproc. Do not do it when dumping. */
1277 if (! dumping)
1278 set_initial_environment ();
1280 /* AIX crashes are reported in system versions 3.2.3 and 3.2.4
1281 if this is not done. Do it after set_global_environment so that we
1282 don't pollute Vglobal_environment. */
1283 /* Setting LANG here will defeat the startup locale processing... */
1284 #ifdef AIX
1285 putenv ("LANG=C");
1286 #endif
1288 init_buffer (); /* Init default directory of main buffer. */
1290 init_callproc_1 (); /* Must precede init_cmdargs and init_sys_modes. */
1291 init_cmdargs (argc, argv, skip_args); /* Must precede init_lread. */
1293 if (initialized)
1295 /* Erase any pre-dump messages in the message log, to avoid confusion. */
1296 Lisp_Object old_log_max;
1297 old_log_max = Vmessage_log_max;
1298 XSETFASTINT (Vmessage_log_max, 0);
1299 message_dolog ("", 0, 1, 0);
1300 Vmessage_log_max = old_log_max;
1303 init_callproc (); /* Must follow init_cmdargs but not init_sys_modes. */
1304 init_lread ();
1305 #ifdef WINDOWSNT
1306 /* Check to see if Emacs has been installed correctly. */
1307 check_windows_init_file ();
1308 #endif
1310 /* Intern the names of all standard functions and variables;
1311 define standard keys. */
1313 if (!initialized)
1315 /* The basic levels of Lisp must come first. Note that
1316 syms_of_data and some others have already been called. */
1317 syms_of_chartab ();
1318 syms_of_lread ();
1319 syms_of_print ();
1320 syms_of_eval ();
1321 syms_of_fns ();
1322 syms_of_floatfns ();
1324 syms_of_buffer ();
1325 syms_of_bytecode ();
1326 syms_of_callint ();
1327 syms_of_casefiddle ();
1328 syms_of_casetab ();
1329 syms_of_category ();
1330 syms_of_ccl ();
1331 syms_of_character ();
1332 syms_of_cmds ();
1333 syms_of_dired ();
1334 syms_of_display ();
1335 syms_of_doc ();
1336 syms_of_editfns ();
1337 syms_of_emacs ();
1338 syms_of_filelock ();
1339 syms_of_indent ();
1340 syms_of_insdel ();
1341 /* syms_of_keymap (); */
1342 syms_of_macros ();
1343 syms_of_marker ();
1344 syms_of_minibuf ();
1345 syms_of_process ();
1346 syms_of_search ();
1347 syms_of_frame ();
1348 syms_of_syntax ();
1349 syms_of_terminal ();
1350 syms_of_term ();
1351 syms_of_undo ();
1352 #ifdef HAVE_SOUND
1353 syms_of_sound ();
1354 #endif
1355 syms_of_textprop ();
1356 syms_of_composite ();
1357 #ifdef WINDOWSNT
1358 syms_of_ntproc ();
1359 #endif /* WINDOWSNT */
1360 syms_of_window ();
1361 syms_of_xdisp ();
1362 syms_of_font ();
1363 #ifdef HAVE_WINDOW_SYSTEM
1364 syms_of_fringe ();
1365 syms_of_image ();
1366 #endif /* HAVE_WINDOW_SYSTEM */
1367 #ifdef HAVE_X_WINDOWS
1368 syms_of_xterm ();
1369 syms_of_xfns ();
1370 syms_of_xmenu ();
1371 syms_of_fontset ();
1372 syms_of_xsettings ();
1373 #ifdef HAVE_X_SM
1374 syms_of_xsmfns ();
1375 #endif
1376 #ifdef HAVE_X11
1377 syms_of_xselect ();
1378 #endif
1379 #endif /* HAVE_X_WINDOWS */
1381 #ifdef HAVE_LIBXML2
1382 syms_of_xml ();
1383 #endif
1385 syms_of_menu ();
1387 #ifdef HAVE_NTGUI
1388 syms_of_w32term ();
1389 syms_of_w32fns ();
1390 syms_of_w32select ();
1391 syms_of_w32menu ();
1392 syms_of_fontset ();
1393 #endif /* HAVE_NTGUI */
1395 #ifdef MSDOS
1396 syms_of_xmenu ();
1397 syms_of_dosfns ();
1398 syms_of_msdos ();
1399 syms_of_win16select ();
1400 #endif /* MSDOS */
1402 #ifdef HAVE_NS
1403 syms_of_nsterm ();
1404 syms_of_nsfns ();
1405 syms_of_nsmenu ();
1406 syms_of_nsselect ();
1407 syms_of_fontset ();
1408 #endif /* HAVE_NS */
1410 #ifdef HAVE_GNUTLS
1411 syms_of_gnutls ();
1412 #endif
1414 #ifdef HAVE_DBUS
1415 syms_of_dbusbind ();
1416 #endif /* HAVE_DBUS */
1418 #ifdef WINDOWSNT
1419 syms_of_ntterm ();
1420 #endif /* WINDOWSNT */
1422 syms_of_profiler ();
1424 keys_of_casefiddle ();
1425 keys_of_cmds ();
1426 keys_of_buffer ();
1427 keys_of_keyboard ();
1428 keys_of_keymap ();
1429 keys_of_window ();
1431 else
1433 /* Initialization that must be done even if the global variable
1434 initialized is non zero. */
1435 #ifdef HAVE_NTGUI
1436 globals_of_w32font ();
1437 globals_of_w32fns ();
1438 globals_of_w32menu ();
1439 globals_of_w32select ();
1440 #endif /* HAVE_NTGUI */
1443 init_charset ();
1445 init_editfns (); /* init_process_emacs uses Voperating_system_release. */
1446 init_process_emacs (); /* init_display uses add_keyboard_wait_descriptor. */
1447 init_keyboard (); /* This too must precede init_sys_modes. */
1448 if (!noninteractive)
1449 init_display (); /* Determine terminal type. Calls init_sys_modes. */
1450 init_xdisp ();
1451 #ifdef HAVE_WINDOW_SYSTEM
1452 init_fringe ();
1453 #endif /* HAVE_WINDOW_SYSTEM */
1454 init_macros ();
1455 init_window ();
1456 init_font ();
1458 if (!initialized)
1460 char *file;
1461 /* Handle -l loadup, args passed by Makefile. */
1462 if (argmatch (argv, argc, "-l", "--load", 3, &file, &skip_args))
1463 Vtop_level = Fcons (intern_c_string ("load"),
1464 Fcons (build_string (file), Qnil));
1465 /* Unless next switch is -nl, load "loadup.el" first thing. */
1466 if (! no_loadup)
1467 Vtop_level = Fcons (intern_c_string ("load"),
1468 Fcons (build_string ("loadup.el"), Qnil));
1471 if (initialized)
1473 #ifdef HAVE_TZSET
1475 /* If the execution TZ happens to be the same as the dump TZ,
1476 change it to some other value and then change it back,
1477 to force the underlying implementation to reload the TZ info.
1478 This is needed on implementations that load TZ info from files,
1479 since the TZ file contents may differ between dump and execution. */
1480 char *tz = getenv ("TZ");
1481 if (tz && !strcmp (tz, dump_tz))
1483 ++*tz;
1484 tzset ();
1485 --*tz;
1488 #endif
1491 /* Set up for profiling. This is known to work on FreeBSD,
1492 GNU/Linux and MinGW. It might work on some other systems too.
1493 Give it a try and tell us if it works on your system. To compile
1494 for profiling, use the configure option --enable-profiling. */
1495 #if defined (__FreeBSD__) || defined (GNU_LINUX) || defined (__MINGW32__)
1496 #ifdef PROFILING
1497 if (initialized)
1499 #ifdef __MINGW32__
1500 extern unsigned char etext asm ("etext");
1501 #else
1502 extern char etext;
1503 #endif
1505 atexit (_mcleanup);
1506 monstartup ((uintptr_t) __executable_start, (uintptr_t) &etext);
1508 else
1509 moncontrol (0);
1510 #endif
1511 #endif
1513 initialized = 1;
1515 #ifdef LOCALTIME_CACHE
1516 /* Some versions of localtime have a bug. They cache the value of the time
1517 zone rather than looking it up every time. Since localtime() is
1518 called to bolt the undumping time into the undumped emacs, this
1519 results in localtime ignoring the TZ environment variable.
1520 This flushes the new TZ value into localtime. */
1521 tzset ();
1522 #endif /* defined (LOCALTIME_CACHE) */
1524 /* Enter editor command loop. This never returns. */
1525 Frecursive_edit ();
1526 /* NOTREACHED */
1527 return 0;
1530 /* Sort the args so we can find the most important ones
1531 at the beginning of argv. */
1533 /* First, here's a table of all the standard options. */
1535 struct standard_args
1537 const char *name;
1538 const char *longname;
1539 int priority;
1540 int nargs;
1543 static const struct standard_args standard_args[] =
1545 { "-version", "--version", 150, 0 },
1546 { "-chdir", "--chdir", 130, 1 },
1547 { "-t", "--terminal", 120, 1 },
1548 { "-nw", "--no-window-system", 110, 0 },
1549 { "-nw", "--no-windows", 110, 0 },
1550 { "-batch", "--batch", 100, 0 },
1551 { "-script", "--script", 100, 1 },
1552 { "-daemon", "--daemon", 99, 0 },
1553 { "-help", "--help", 90, 0 },
1554 { "-nl", "--no-loadup", 70, 0 },
1555 { "-nsl", "--no-site-lisp", 65, 0 },
1556 /* -d must come last before the options handled in startup.el. */
1557 { "-d", "--display", 60, 1 },
1558 { "-display", 0, 60, 1 },
1559 /* Now for the options handled in `command-line' (startup.el). */
1560 /* (Note that to imply -nsl, -Q is partially handled here.) */
1561 { "-Q", "--quick", 55, 0 },
1562 { "-quick", 0, 55, 0 },
1563 { "-q", "--no-init-file", 50, 0 },
1564 { "-no-init-file", 0, 50, 0 },
1565 { "-no-site-file", "--no-site-file", 40, 0 },
1566 { "-u", "--user", 30, 1 },
1567 { "-user", 0, 30, 1 },
1568 { "-debug-init", "--debug-init", 20, 0 },
1569 { "-iconic", "--iconic", 15, 0 },
1570 { "-D", "--basic-display", 12, 0},
1571 { "-basic-display", 0, 12, 0},
1572 { "-nbc", "--no-blinking-cursor", 12, 0 },
1573 /* Now for the options handled in `command-line-1' (startup.el). */
1574 { "-nbi", "--no-bitmap-icon", 10, 0 },
1575 { "-bg", "--background-color", 10, 1 },
1576 { "-background", 0, 10, 1 },
1577 { "-fg", "--foreground-color", 10, 1 },
1578 { "-foreground", 0, 10, 1 },
1579 { "-bd", "--border-color", 10, 1 },
1580 { "-bw", "--border-width", 10, 1 },
1581 { "-ib", "--internal-border", 10, 1 },
1582 { "-ms", "--mouse-color", 10, 1 },
1583 { "-cr", "--cursor-color", 10, 1 },
1584 { "-fn", "--font", 10, 1 },
1585 { "-font", 0, 10, 1 },
1586 { "-fs", "--fullscreen", 10, 0 },
1587 { "-fw", "--fullwidth", 10, 0 },
1588 { "-fh", "--fullheight", 10, 0 },
1589 { "-mm", "--maximized", 10, 0 },
1590 { "-g", "--geometry", 10, 1 },
1591 { "-geometry", 0, 10, 1 },
1592 { "-T", "--title", 10, 1 },
1593 { "-title", 0, 10, 1 },
1594 { "-name", "--name", 10, 1 },
1595 { "-xrm", "--xrm", 10, 1 },
1596 { "-parent-id", "--parent-id", 10, 1 },
1597 { "-r", "--reverse-video", 5, 0 },
1598 { "-rv", 0, 5, 0 },
1599 { "-reverse", 0, 5, 0 },
1600 { "-hb", "--horizontal-scroll-bars", 5, 0 },
1601 { "-vb", "--vertical-scroll-bars", 5, 0 },
1602 { "-color", "--color", 5, 0},
1603 { "-no-splash", "--no-splash", 3, 0 },
1604 { "-no-desktop", "--no-desktop", 3, 0 },
1605 #ifdef HAVE_NS
1606 { "-NSAutoLaunch", 0, 5, 1 },
1607 { "-NXAutoLaunch", 0, 5, 1 },
1608 { "-disable-font-backend", "--disable-font-backend", 65, 0 },
1609 { "-_NSMachLaunch", 0, 85, 1 },
1610 { "-MachLaunch", 0, 85, 1 },
1611 { "-macosx", 0, 85, 0 },
1612 { "-NSHost", 0, 85, 1 },
1613 #endif
1614 /* These have the same priority as ordinary file name args,
1615 so they are not reordered with respect to those. */
1616 { "-L", "--directory", 0, 1 },
1617 { "-directory", 0, 0, 1 },
1618 { "-l", "--load", 0, 1 },
1619 { "-load", 0, 0, 1 },
1620 /* This has no longname, because using --scriptload confuses sort_args,
1621 because then the --script long option seems to match twice; ie
1622 you can't have a long option which is a prefix of another long
1623 option. In any case, this is entirely an internal option. */
1624 { "-scriptload", NULL, 0, 1 },
1625 { "-f", "--funcall", 0, 1 },
1626 { "-funcall", 0, 0, 1 },
1627 { "-eval", "--eval", 0, 1 },
1628 { "-execute", "--execute", 0, 1 },
1629 { "-find-file", "--find-file", 0, 1 },
1630 { "-visit", "--visit", 0, 1 },
1631 { "-file", "--file", 0, 1 },
1632 { "-insert", "--insert", 0, 1 },
1633 #ifdef HAVE_NS
1634 { "-NXOpen", 0, 0, 1 },
1635 { "-NXOpenTemp", 0, 0, 1 },
1636 { "-NSOpen", 0, 0, 1 },
1637 { "-NSOpenTemp", 0, 0, 1 },
1638 { "-GSFilePath", 0, 0, 1 },
1639 #endif
1640 /* This should be processed after ordinary file name args and the like. */
1641 { "-kill", "--kill", -10, 0 },
1644 /* Reorder the elements of ARGV (assumed to have ARGC elements)
1645 so that the highest priority ones come first.
1646 Do not change the order of elements of equal priority.
1647 If an option takes an argument, keep it and its argument together.
1649 If an option that takes no argument appears more
1650 than once, eliminate all but one copy of it. */
1652 static void
1653 sort_args (int argc, char **argv)
1655 char **new = xmalloc (argc * sizeof *new);
1656 /* For each element of argv,
1657 the corresponding element of options is:
1658 0 for an option that takes no arguments,
1659 1 for an option that takes one argument, etc.
1660 -1 for an ordinary non-option argument. */
1661 int *options = xnmalloc (argc, sizeof *options);
1662 int *priority = xnmalloc (argc, sizeof *priority);
1663 int to = 1;
1664 int incoming_used = 1;
1665 int from;
1666 int i;
1668 /* Categorize all the options,
1669 and figure out which argv elts are option arguments. */
1670 for (from = 1; from < argc; from++)
1672 options[from] = -1;
1673 priority[from] = 0;
1674 if (argv[from][0] == '-')
1676 int match;
1678 /* If we have found "--", don't consider
1679 any more arguments as options. */
1680 if (argv[from][1] == '-' && argv[from][2] == 0)
1682 /* Leave the "--", and everything following it, at the end. */
1683 for (; from < argc; from++)
1685 priority[from] = -100;
1686 options[from] = -1;
1688 break;
1691 /* Look for a match with a known old-fashioned option. */
1692 for (i = 0; i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1693 if (!strcmp (argv[from], standard_args[i].name))
1695 options[from] = standard_args[i].nargs;
1696 priority[from] = standard_args[i].priority;
1697 if (from + standard_args[i].nargs >= argc)
1698 fatal ("Option `%s' requires an argument\n", argv[from]);
1699 from += standard_args[i].nargs;
1700 goto done;
1703 /* Look for a match with a known long option.
1704 MATCH is -1 if no match so far, -2 if two or more matches so far,
1705 >= 0 (the table index of the match) if just one match so far. */
1706 if (argv[from][1] == '-')
1708 char const *equals = strchr (argv[from], '=');
1709 ptrdiff_t thislen =
1710 equals ? equals - argv[from] : strlen (argv[from]);
1712 match = -1;
1714 for (i = 0;
1715 i < sizeof (standard_args) / sizeof (standard_args[0]); i++)
1716 if (standard_args[i].longname
1717 && !strncmp (argv[from], standard_args[i].longname,
1718 thislen))
1720 if (match == -1)
1721 match = i;
1722 else
1723 match = -2;
1726 /* If we found exactly one match, use that. */
1727 if (match >= 0)
1729 options[from] = standard_args[match].nargs;
1730 priority[from] = standard_args[match].priority;
1731 /* If --OPTION=VALUE syntax is used,
1732 this option uses just one argv element. */
1733 if (equals != 0)
1734 options[from] = 0;
1735 if (from + options[from] >= argc)
1736 fatal ("Option `%s' requires an argument\n", argv[from]);
1737 from += options[from];
1739 /* FIXME When match < 0, shouldn't there be some error,
1740 or at least indication to the user that there was a
1741 problem? */
1743 done: ;
1747 /* Copy the arguments, in order of decreasing priority, to NEW. */
1748 new[0] = argv[0];
1749 while (incoming_used < argc)
1751 int best = -1;
1752 int best_priority = -9999;
1754 /* Find the highest priority remaining option.
1755 If several have equal priority, take the first of them. */
1756 for (from = 1; from < argc; from++)
1758 if (argv[from] != 0 && priority[from] > best_priority)
1760 best_priority = priority[from];
1761 best = from;
1763 /* Skip option arguments--they are tied to the options. */
1764 if (options[from] > 0)
1765 from += options[from];
1768 if (best < 0)
1769 emacs_abort ();
1771 /* Copy the highest priority remaining option, with its args, to NEW.
1772 Unless it is a duplicate of the previous one. */
1773 if (! (options[best] == 0
1774 && ! strcmp (new[to - 1], argv[best])))
1776 new[to++] = argv[best];
1777 for (i = 0; i < options[best]; i++)
1778 new[to++] = argv[best + i + 1];
1781 incoming_used += 1 + (options[best] > 0 ? options[best] : 0);
1783 /* Clear out this option in ARGV. */
1784 argv[best] = 0;
1785 for (i = 0; i < options[best]; i++)
1786 argv[best + i + 1] = 0;
1789 /* If duplicate options were deleted, fill up extra space with null ptrs. */
1790 while (to < argc)
1791 new[to++] = 0;
1793 memcpy (argv, new, sizeof (char *) * argc);
1795 xfree (options);
1796 xfree (new);
1797 xfree (priority);
1800 DEFUN ("kill-emacs", Fkill_emacs, Skill_emacs, 0, 1, "P",
1801 doc: /* Exit the Emacs job and kill it.
1802 If ARG is an integer, return ARG as the exit program code.
1803 If ARG is a string, stuff it as keyboard input.
1805 This function is called upon receipt of the signals SIGTERM
1806 or SIGHUP, and upon SIGINT in batch mode.
1808 The value of `kill-emacs-hook', if not void,
1809 is a list of functions (of no args),
1810 all of which are called before Emacs is actually killed. */)
1811 (Lisp_Object arg)
1813 struct gcpro gcpro1;
1814 Lisp_Object hook;
1815 int exit_code;
1817 GCPRO1 (arg);
1819 if (feof (stdin))
1820 arg = Qt;
1822 hook = intern ("kill-emacs-hook");
1823 Frun_hooks (1, &hook);
1825 UNGCPRO;
1827 #ifdef HAVE_X_WINDOWS
1828 /* Transfer any clipboards we own to the clipboard manager. */
1829 x_clipboard_manager_save_all ();
1830 #endif
1832 shut_down_emacs (0, STRINGP (arg) ? arg : Qnil);
1834 #ifdef HAVE_NS
1835 ns_release_autorelease_pool (ns_pool);
1836 #endif
1838 /* If we have an auto-save list file,
1839 kill it because we are exiting Emacs deliberately (not crashing).
1840 Do it after shut_down_emacs, which does an auto-save. */
1841 if (STRINGP (Vauto_save_list_file_name))
1842 unlink (SSDATA (Vauto_save_list_file_name));
1844 if (INTEGERP (arg))
1845 exit_code = (XINT (arg) < 0
1846 ? XINT (arg) | INT_MIN
1847 : XINT (arg) & INT_MAX);
1848 else if (noninteractive && (fflush (stdout) || ferror (stdout)))
1849 exit_code = EXIT_FAILURE;
1850 else
1851 exit_code = EXIT_SUCCESS;
1852 exit (exit_code);
1856 /* Perform an orderly shutdown of Emacs. Autosave any modified
1857 buffers, kill any child processes, clean up the terminal modes (if
1858 we're in the foreground), and other stuff like that. Don't perform
1859 any redisplay; this may be called when Emacs is shutting down in
1860 the background, or after its X connection has died.
1862 If SIG is a signal number, print a message for it.
1864 This is called by fatal signal handlers, X protocol error handlers,
1865 and Fkill_emacs. */
1867 void
1868 shut_down_emacs (int sig, Lisp_Object stuff)
1870 /* Prevent running of hooks from now on. */
1871 Vrun_hooks = Qnil;
1873 /* Don't update display from now on. */
1874 Vinhibit_redisplay = Qt;
1876 /* If we are controlling the terminal, reset terminal modes. */
1877 #ifndef DOS_NT
1879 int pgrp = EMACS_GETPGRP (0);
1880 int tpgrp = tcgetpgrp (0);
1881 if ((tpgrp != -1) && tpgrp == pgrp)
1883 reset_all_sys_modes ();
1884 if (sig && sig != SIGTERM)
1886 static char const format[] = "Fatal error %d: ";
1887 char buf[sizeof format - 2 + INT_STRLEN_BOUND (int)];
1888 int buflen = sprintf (buf, format, sig);
1889 char const *sig_desc = safe_strsignal (sig);
1890 ignore_value (write (STDERR_FILENO, buf, buflen));
1891 ignore_value (write (STDERR_FILENO, sig_desc, strlen (sig_desc)));
1895 #else
1896 fflush (stdout);
1897 reset_all_sys_modes ();
1898 #endif
1900 stuff_buffered_input (stuff);
1902 inhibit_sentinels = 1;
1903 kill_buffer_processes (Qnil);
1904 Fdo_auto_save (Qt, Qnil);
1906 #ifdef CLASH_DETECTION
1907 unlock_all_files ();
1908 #endif
1910 /* There is a tendency for a SIGIO signal to arrive within exit,
1911 and cause a SIGHUP because the input descriptor is already closed. */
1912 unrequest_sigio ();
1913 ignore_sigio ();
1915 /* Do this only if terminating normally, we want glyph matrices
1916 etc. in a core dump. */
1917 if (sig == 0 || sig == SIGTERM)
1919 check_glyph_memory ();
1920 check_message_stack ();
1923 #ifdef MSDOS
1924 dos_cleanup ();
1925 #endif
1927 #ifdef HAVE_NS
1928 ns_term_shutdown (sig);
1929 #endif
1931 #ifdef HAVE_LIBXML2
1932 xml_cleanup_parser ();
1933 #endif
1935 #ifdef WINDOWSNT
1936 term_ntproc (0);
1937 #endif
1942 #ifndef CANNOT_DUMP
1944 #include "unexec.h"
1946 DEFUN ("dump-emacs", Fdump_emacs, Sdump_emacs, 2, 2, 0,
1947 doc: /* Dump current state of Emacs into executable file FILENAME.
1948 Take symbols from SYMFILE (presumably the file you executed to run Emacs).
1949 This is used in the file `loadup.el' when building Emacs.
1951 You must run Emacs in batch mode in order to dump it. */)
1952 (Lisp_Object filename, Lisp_Object symfile)
1954 Lisp_Object tem;
1955 Lisp_Object symbol;
1956 ptrdiff_t count = SPECPDL_INDEX ();
1958 check_pure_size ();
1960 if (! noninteractive)
1961 error ("Dumping Emacs works only in batch mode");
1963 #ifdef GNU_LINUX
1965 /* Warn if the gap between BSS end and heap start is larger than this. */
1966 # define MAX_HEAP_BSS_DIFF (1024*1024)
1968 if (heap_bss_diff > MAX_HEAP_BSS_DIFF)
1970 fprintf (stderr, "**************************************************\n");
1971 fprintf (stderr, "Warning: Your system has a gap between BSS and the\n");
1972 fprintf (stderr, "heap (%"pMu" bytes). This usually means that exec-shield\n",
1973 heap_bss_diff);
1974 fprintf (stderr, "or something similar is in effect. The dump may\n");
1975 fprintf (stderr, "fail because of this. See the section about\n");
1976 fprintf (stderr, "exec-shield in etc/PROBLEMS for more information.\n");
1977 fprintf (stderr, "**************************************************\n");
1979 #endif /* GNU_LINUX */
1981 /* Bind `command-line-processed' to nil before dumping,
1982 so that the dumped Emacs will process its command line
1983 and set up to work with X windows if appropriate. */
1984 symbol = intern ("command-line-processed");
1985 specbind (symbol, Qnil);
1987 CHECK_STRING (filename);
1988 filename = Fexpand_file_name (filename, Qnil);
1989 if (!NILP (symfile))
1991 CHECK_STRING (symfile);
1992 if (SCHARS (symfile))
1993 symfile = Fexpand_file_name (symfile, Qnil);
1996 tem = Vpurify_flag;
1997 Vpurify_flag = Qnil;
1999 #ifdef HAVE_TZSET
2000 set_time_zone_rule (dump_tz);
2001 #ifndef LOCALTIME_CACHE
2002 /* Force a tz reload, since set_time_zone_rule doesn't. */
2003 tzset ();
2004 #endif
2005 #endif
2007 fflush (stdout);
2008 /* Tell malloc where start of impure now is. */
2009 /* Also arrange for warnings when nearly out of space. */
2010 #ifndef SYSTEM_MALLOC
2011 #ifndef WINDOWSNT
2012 /* On Windows, this was done before dumping, and that once suffices.
2013 Meanwhile, my_edata is not valid on Windows. */
2015 extern char my_edata[];
2016 memory_warnings (my_edata, malloc_warning);
2018 #endif /* not WINDOWSNT */
2019 #endif /* not SYSTEM_MALLOC */
2020 #ifdef DOUG_LEA_MALLOC
2021 malloc_state_ptr = malloc_get_state ();
2022 #endif
2024 #ifdef USE_MMAP_FOR_BUFFERS
2025 mmap_set_vars (0);
2026 #endif
2027 unexec (SSDATA (filename), !NILP (symfile) ? SSDATA (symfile) : 0);
2028 #ifdef USE_MMAP_FOR_BUFFERS
2029 mmap_set_vars (1);
2030 #endif
2031 #ifdef DOUG_LEA_MALLOC
2032 free (malloc_state_ptr);
2033 #endif
2035 #ifdef WINDOWSNT
2036 Vlibrary_cache = Qnil;
2037 #endif
2038 #ifdef HAVE_WINDOW_SYSTEM
2039 reset_image_types ();
2040 #endif
2042 Vpurify_flag = tem;
2044 return unbind_to (count, Qnil);
2047 #endif /* not CANNOT_DUMP */
2049 #if HAVE_SETLOCALE
2050 /* Recover from setlocale (LC_ALL, ""). */
2051 void
2052 fixup_locale (void)
2054 /* The Emacs Lisp reader needs LC_NUMERIC to be "C",
2055 so that numbers are read and printed properly for Emacs Lisp. */
2056 setlocale (LC_NUMERIC, "C");
2059 /* Set system locale CATEGORY, with previous locale *PLOCALE, to
2060 DESIRED_LOCALE. */
2061 static void
2062 synchronize_locale (int category, Lisp_Object *plocale, Lisp_Object desired_locale)
2064 if (! EQ (*plocale, desired_locale))
2066 *plocale = desired_locale;
2067 setlocale (category, (STRINGP (desired_locale)
2068 ? SSDATA (desired_locale)
2069 : ""));
2073 /* Set system time locale to match Vsystem_time_locale, if possible. */
2074 void
2075 synchronize_system_time_locale (void)
2077 synchronize_locale (LC_TIME, &Vprevious_system_time_locale,
2078 Vsystem_time_locale);
2081 /* Set system messages locale to match Vsystem_messages_locale, if
2082 possible. */
2083 void
2084 synchronize_system_messages_locale (void)
2086 #ifdef LC_MESSAGES
2087 synchronize_locale (LC_MESSAGES, &Vprevious_system_messages_locale,
2088 Vsystem_messages_locale);
2089 #endif
2091 #endif /* HAVE_SETLOCALE */
2094 Lisp_Object
2095 decode_env_path (const char *evarname, const char *defalt)
2097 const char *path, *p;
2098 Lisp_Object lpath, element, tem;
2099 #ifdef WINDOWSNT
2100 bool defaulted = 0;
2101 const char *emacs_dir = egetenv ("emacs_dir");
2102 static const char *emacs_dir_env = "%emacs_dir%/";
2103 const size_t emacs_dir_len = strlen (emacs_dir_env);
2104 #endif
2106 /* It's okay to use getenv here, because this function is only used
2107 to initialize variables when Emacs starts up, and isn't called
2108 after that. */
2109 if (evarname != 0)
2110 path = getenv (evarname);
2111 else
2112 path = 0;
2113 if (!path)
2115 path = defalt;
2116 #ifdef WINDOWSNT
2117 defaulted = 1;
2118 #endif
2120 #ifdef DOS_NT
2121 /* Ensure values from the environment use the proper directory separator. */
2122 if (path)
2124 char *path_copy = alloca (strlen (path) + 1);
2125 strcpy (path_copy, path);
2126 dostounix_filename (path_copy);
2127 path = path_copy;
2129 #endif
2130 lpath = Qnil;
2131 while (1)
2133 p = strchr (path, SEPCHAR);
2134 if (!p)
2135 p = path + strlen (path);
2136 element = (p - path ? make_string (path, p - path)
2137 : build_string ("."));
2138 #ifdef WINDOWSNT
2139 /* Relative file names in the default path are interpreted as
2140 being relative to $emacs_dir. */
2141 if (emacs_dir && defaulted
2142 && strncmp (path, emacs_dir_env, emacs_dir_len) == 0)
2143 element = Fexpand_file_name (Fsubstring (element,
2144 make_number (emacs_dir_len),
2145 Qnil),
2146 build_string (emacs_dir));
2147 #endif
2149 /* Add /: to the front of the name
2150 if it would otherwise be treated as magic. */
2151 tem = Ffind_file_name_handler (element, Qt);
2153 /* However, if the handler says "I'm safe",
2154 don't bother adding /:. */
2155 if (SYMBOLP (tem))
2157 Lisp_Object prop;
2158 prop = Fget (tem, intern ("safe-magic"));
2159 if (! NILP (prop))
2160 tem = Qnil;
2163 if (! NILP (tem))
2164 element = concat2 (build_string ("/:"), element);
2166 lpath = Fcons (element, lpath);
2167 if (*p)
2168 path = p + 1;
2169 else
2170 break;
2172 return Fnreverse (lpath);
2175 DEFUN ("daemonp", Fdaemonp, Sdaemonp, 0, 0, 0,
2176 doc: /* Return non-nil if the current emacs process is a daemon.
2177 If the daemon was given a name argument, return that name. */)
2178 (void)
2180 if (IS_DAEMON)
2181 if (daemon_name)
2182 return build_string (daemon_name);
2183 else
2184 return Qt;
2185 else
2186 return Qnil;
2189 DEFUN ("daemon-initialized", Fdaemon_initialized, Sdaemon_initialized, 0, 0, 0,
2190 doc: /* Mark the Emacs daemon as being initialized.
2191 This finishes the daemonization process by doing the other half of detaching
2192 from the parent process and its tty file descriptors. */)
2193 (void)
2195 int nfd;
2196 bool err = 0;
2198 if (!IS_DAEMON)
2199 error ("This function can only be called if emacs is run as a daemon");
2201 if (daemon_pipe[1] < 0)
2202 error ("The daemon has already been initialized");
2204 if (NILP (Vafter_init_time))
2205 error ("This function can only be called after loading the init files");
2207 /* Get rid of stdin, stdout and stderr. */
2208 nfd = open ("/dev/null", O_RDWR);
2209 err |= nfd < 0;
2210 err |= dup2 (nfd, 0) < 0;
2211 err |= dup2 (nfd, 1) < 0;
2212 err |= dup2 (nfd, 2) < 0;
2213 err |= close (nfd) != 0;
2215 /* Closing the pipe will notify the parent that it can exit.
2216 FIXME: In case some other process inherited the pipe, closing it here
2217 won't notify the parent because it's still open elsewhere, so we
2218 additionally send a byte, just to make sure the parent really exits.
2219 Instead, we should probably close the pipe in start-process and
2220 call-process to make sure the pipe is never inherited by
2221 subprocesses. */
2222 err |= write (daemon_pipe[1], "\n", 1) < 0;
2223 err |= close (daemon_pipe[1]) != 0;
2224 /* Set it to an invalid value so we know we've already run this function. */
2225 daemon_pipe[1] = -1;
2227 if (err)
2228 error ("I/O error during daemon initialization");
2229 return Qt;
2232 void
2233 syms_of_emacs (void)
2235 DEFSYM (Qfile_name_handler_alist, "file-name-handler-alist");
2236 DEFSYM (Qrisky_local_variable, "risky-local-variable");
2237 DEFSYM (Qkill_emacs, "kill-emacs");
2239 #ifndef CANNOT_DUMP
2240 defsubr (&Sdump_emacs);
2241 #endif
2243 defsubr (&Skill_emacs);
2245 defsubr (&Sinvocation_name);
2246 defsubr (&Sinvocation_directory);
2247 defsubr (&Sdaemonp);
2248 defsubr (&Sdaemon_initialized);
2250 DEFVAR_LISP ("command-line-args", Vcommand_line_args,
2251 doc: /* Args passed by shell to Emacs, as a list of strings.
2252 Many arguments are deleted from the list as they are processed. */);
2254 DEFVAR_LISP ("system-type", Vsystem_type,
2255 doc: /* The value is a symbol indicating the type of operating system you are using.
2256 Special values:
2257 `gnu' compiled for a GNU Hurd system.
2258 `gnu/linux' compiled for a GNU/Linux system.
2259 `gnu/kfreebsd' compiled for a GNU system with a FreeBSD kernel.
2260 `darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...).
2261 `ms-dos' compiled as an MS-DOS application.
2262 `windows-nt' compiled as a native W32 application.
2263 `cygwin' compiled using the Cygwin library.
2264 Anything else (in Emacs 24.1, the possibilities are: aix, berkeley-unix,
2265 hpux, irix, usg-unix-v) indicates some sort of Unix system. */);
2266 Vsystem_type = intern_c_string (SYSTEM_TYPE);
2267 /* See configure.ac (and config.nt) for the possible SYSTEM_TYPEs. */
2269 DEFVAR_LISP ("system-configuration", Vsystem_configuration,
2270 doc: /* Value is string indicating configuration Emacs was built for.
2271 On MS-Windows, the value reflects the OS flavor and version on which
2272 Emacs is running. */);
2273 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2275 DEFVAR_LISP ("system-configuration-options", Vsystem_configuration_options,
2276 doc: /* String containing the configuration options Emacs was built with. */);
2277 Vsystem_configuration_options = build_string (EMACS_CONFIG_OPTIONS);
2279 DEFVAR_BOOL ("noninteractive", noninteractive1,
2280 doc: /* Non-nil means Emacs is running without interactive terminal. */);
2282 DEFVAR_LISP ("kill-emacs-hook", Vkill_emacs_hook,
2283 doc: /* Hook run when `kill-emacs' is called.
2284 Since `kill-emacs' may be invoked when the terminal is disconnected (or
2285 in other similar situations), functions placed on this hook should not
2286 expect to be able to interact with the user. To ask for confirmation,
2287 see `kill-emacs-query-functions' instead.
2289 Before Emacs 24.1, the hook was not run in batch mode, i.e., if
2290 `noninteractive' was non-nil. */);
2291 Vkill_emacs_hook = Qnil;
2293 DEFVAR_LISP ("path-separator", Vpath_separator,
2294 doc: /* String containing the character that separates directories in
2295 search paths, such as PATH and other similar environment variables. */);
2297 char c = SEPCHAR;
2298 Vpath_separator = make_string (&c, 1);
2301 DEFVAR_LISP ("invocation-name", Vinvocation_name,
2302 doc: /* The program name that was used to run Emacs.
2303 Any directory names are omitted. */);
2305 DEFVAR_LISP ("invocation-directory", Vinvocation_directory,
2306 doc: /* The directory in which the Emacs executable was found, to run it.
2307 The value is nil if that directory's name is not known. */);
2309 DEFVAR_LISP ("installation-directory", Vinstallation_directory,
2310 doc: /* A directory within which to look for the `lib-src' and `etc' directories.
2311 In an installed Emacs, this is normally nil. It is non-nil if
2312 both `lib-src' (on MS-DOS, `info') and `etc' directories are found
2313 within the variable `invocation-directory' or its parent. For example,
2314 this is the case when running an uninstalled Emacs executable from its
2315 build directory. */);
2316 Vinstallation_directory = Qnil;
2318 DEFVAR_LISP ("system-messages-locale", Vsystem_messages_locale,
2319 doc: /* System locale for messages. */);
2320 Vsystem_messages_locale = Qnil;
2322 DEFVAR_LISP ("previous-system-messages-locale",
2323 Vprevious_system_messages_locale,
2324 doc: /* Most recently used system locale for messages. */);
2325 Vprevious_system_messages_locale = Qnil;
2327 DEFVAR_LISP ("system-time-locale", Vsystem_time_locale,
2328 doc: /* System locale for time. */);
2329 Vsystem_time_locale = Qnil;
2331 DEFVAR_LISP ("previous-system-time-locale", Vprevious_system_time_locale,
2332 doc: /* Most recently used system locale for time. */);
2333 Vprevious_system_time_locale = Qnil;
2335 DEFVAR_LISP ("before-init-time", Vbefore_init_time,
2336 doc: /* Value of `current-time' before Emacs begins initialization. */);
2337 Vbefore_init_time = Qnil;
2339 DEFVAR_LISP ("after-init-time", Vafter_init_time,
2340 doc: /* Value of `current-time' after loading the init files.
2341 This is nil during initialization. */);
2342 Vafter_init_time = Qnil;
2344 DEFVAR_BOOL ("inhibit-x-resources", inhibit_x_resources,
2345 doc: /* If non-nil, X resources, Windows Registry settings, and NS defaults are not used. */);
2346 inhibit_x_resources = 0;
2348 DEFVAR_LISP ("emacs-copyright", Vemacs_copyright,
2349 doc: /* Short copyright string for this version of Emacs. */);
2350 Vemacs_copyright = build_string (emacs_copyright);
2352 DEFVAR_LISP ("emacs-version", Vemacs_version,
2353 doc: /* Version numbers of this version of Emacs. */);
2354 Vemacs_version = build_string (emacs_version);
2356 DEFVAR_LISP ("dynamic-library-alist", Vdynamic_library_alist,
2357 doc: /* Alist of dynamic libraries vs external files implementing them.
2358 Each element is a list (LIBRARY FILE...), where the car is a symbol
2359 representing a supported external library, and the rest are strings giving
2360 alternate filenames for that library.
2362 Emacs tries to load the library from the files in the order they appear on
2363 the list; if none is loaded, the running session of Emacs won't have access
2364 to that library.
2366 Note that image types `pbm' and `xbm' do not need entries in this variable
2367 because they do not depend on external libraries and are always available.
2369 Also note that this is not a generic facility for accessing external
2370 libraries; only those already known by Emacs will be loaded. */);
2371 Vdynamic_library_alist = Qnil;
2372 Fput (intern_c_string ("dynamic-library-alist"), Qrisky_local_variable, Qt);
2374 #ifdef WINDOWSNT
2375 Vlibrary_cache = Qnil;
2376 staticpro (&Vlibrary_cache);
2377 #endif
2379 /* Make sure IS_DAEMON starts up as false. */
2380 daemon_pipe[1] = 0;