f2bc2d31a810bdeaaae7d5d76442e4bf21b6e6b2
[chise/xemacs-chise.git.1] / lisp / startup.el
1 ;;; startup.el --- process XEmacs shell arguments
2
3 ;; Copyright (C) 1985-1986, 1990, 1992-1997 Free Software Foundation, Inc.
4 ;; Copyright (c) 1993, 1994 Sun Microsystems, Inc.
5 ;; Copyright (C) 1995 Board of Trustees, University of Illinois
6
7 ;; Maintainer: XEmacs Development Team
8 ;; Keywords: internal, dumped
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Synched up with: FSF 19.34.
28
29 ;;; Commentary:
30
31 ;; This file is dumped with XEmacs.
32
33 ;; -batch, -t, and -nw are processed by main() in emacs.c and are
34 ;; never seen by lisp code.
35
36 ;; -version and -help are special-cased as well: they imply -batch,
37 ;; but are left on the list for lisp code to process.
38
39 ;;; Code:
40 \f
41 (setq top-level '(normal-top-level))
42
43 (defvar command-line-processed nil "t once command line has been processed")
44
45 (defconst startup-message-timeout 12000) ; More or less disable the timeout
46 (defconst splash-frame-timeout 7) ; interval between splash frame elements
47
48 (defconst inhibit-startup-message nil
49   "*Non-nil inhibits the initial startup message.
50 This is for use in your personal init file, once you are familiar
51 with the contents of the startup message.")
52
53 ;; #### FSFmacs randomness
54 ;;(defconst inhibit-startup-echo-area-message nil
55 ;;  "*Non-nil inhibits the initial startup echo area message.
56 ;;Inhibition takes effect only if your `.emacs' file contains
57 ;;a line of this form:
58 ;; (setq inhibit-startup-echo-area-message \"YOUR-USER-NAME\")
59 ;;If your `.emacs' file is byte-compiled, use the following form instead:
60 ;; (eval '(setq inhibit-startup-echo-area-message \"YOUR-USER-NAME\"))
61 ;;Thus, someone else using a copy of your `.emacs' file will see
62 ;;the startup message unless he personally acts to inhibit it.")
63
64 (defconst inhibit-default-init nil
65   "*Non-nil inhibits loading the `default' library.")
66
67 (defvar command-line-args-left nil
68   "List of command-line args not yet processed.") ; bound by `command-line'
69
70 (defvar command-line-default-directory nil
71   "Default directory to use for command line arguments.
72 This is normally copied from `default-directory' when XEmacs starts.")
73
74 (defvar before-init-hook nil
75   "Functions to call after handling urgent options but before init files.
76 The frame system uses this to open frames to display messages while
77 XEmacs loads the user's initialization file.")
78
79 (defvar after-init-hook nil
80   "*Functions to call after loading the init file (`.emacs').
81 The call is not protected by a condition-case, so you can set `debug-on-error'
82 in `.emacs', and put all the actual code on `after-init-hook'.")
83
84 (defvar term-setup-hook nil
85   "*Functions to be called after loading terminal-specific Lisp code.
86 See `run-hooks'.  This variable exists for users to set, so as to
87 override the definitions made by the terminal-specific file.  XEmacs
88 never sets this variable itself.")
89
90 (defvar keyboard-type nil
91   "The brand of keyboard you are using.
92 This variable is used to define the proper function and keypad keys
93 for use under X.  It is used in a fashion analogous to the environment
94 value TERM.")
95
96 (defvar window-setup-hook nil
97   "Normal hook run to initialize window system display.
98 XEmacs runs this hook after processing the command line arguments and loading
99 the user's init file.")
100
101 (defconst initial-major-mode 'lisp-interaction-mode
102   "Major mode command symbol to use for the initial *scratch* buffer.")
103
104 (defvar emacs-roots nil
105   "List of plausible roots of the XEmacs hierarchy.")
106
107 (defvar user-init-directory-base ".xemacs"
108   "Base of directory where user-installed init files may go.")
109
110 (defvar user-init-file-base-list (append
111                                   '(".emacs.elc" ".emacs.el" ".emacs")
112                                   (and (eq system-type 'windows-nt)
113                                        '("_emacs.elc" "_emacs.el" "_emacs")))
114   "List of allowed init files.  The first one found takes precedence.")
115
116 (defvar user-init-directory
117   (file-name-as-directory
118    (paths-construct-path (list "~" user-init-directory-base)))
119   "Directory where user-installed init files may go.")
120
121 (defvar load-user-init-file-p t
122   "Non-nil if XEmacs should load the user's init file.")
123
124 ;; #### called `site-run-file' in FSFmacs
125
126 (defvar site-start-file (purecopy "site-start")
127   "File containing site-wide run-time initializations.
128 This file is loaded at run-time before `.emacs'.  It
129 contains inits that need to be in place for the entire site, but
130 which, due to their higher incidence of change, don't make sense to
131 load into XEmacs' dumped image.  Thus, the run-time load order is:
132
133   1. file described in this variable, if non-nil;
134   2. `.emacs';
135   3. `/path/to/xemacs/lisp/default.el'.
136
137 Don't use the `site-start.el' file for things some users may not like.
138 Put them in `default.el' instead, so that users can more easily
139 override them.  Users can prevent loading `default.el' with the `-q'
140 option or by setting `inhibit-default-init' in their own init files,
141 but inhibiting `site-start.el' requires `--no-site-file', which
142 is less convenient.")
143
144 ;;(defconst iso-8859-1-locale-regexp "8859[-_]?1"
145 ;;  "Regexp that specifies when to enable the ISO 8859-1 character set.
146 ;;We do that if this regexp matches the locale name
147 ;;specified by the LC_ALL, LC_CTYPE and LANG environment variables.")
148
149 (defvar mail-host-address nil
150   "*Name of this machine, for purposes of naming users.")
151
152 (defvar user-mail-address nil
153   "*Full mailing address of this user.
154 This is initialized based on `mail-host-address',
155 after your init file is read, in case it sets `mail-host-address'.")
156
157 (defvar auto-save-list-file-prefix "~/.saves-"
158   "Prefix for generating auto-save-list-file-name.
159 Emacs's pid and the system name will be appended to
160 this prefix to create a unique file name.")
161
162 (defvar init-file-debug nil)
163
164 (defvar init-file-had-error nil)
165
166 (defvar init-file-loaded nil
167   "True after the user's init file has been loaded (or suppressed with -q).
168 This will be true when `after-init-hook' is run and at all times
169 after, and will not be true at any time before.")
170
171 (defvar initial-frame-unmapped-p nil)
172
173 \f
174
175 (defvar command-switch-alist
176   (purecopy
177    '(("-help"   . command-line-do-help)
178      ("-version". command-line-do-version)
179      ("-V"      . command-line-do-version)
180      ("-funcall". command-line-do-funcall)
181      ("-f"      . command-line-do-funcall)
182      ("-e"      . command-line-do-funcall-1)
183      ("-eval"   . command-line-do-eval)
184      ("-load"   . command-line-do-load)
185      ("-l"      . command-line-do-load)
186      ("-insert" . command-line-do-insert)
187      ("-i"      . command-line-do-insert)
188      ("-kill"   . command-line-do-kill)
189      ;; Options like +35 are handled specially.
190      ;; Window-system, site, or package-specific code might add to this.
191      ;; X11 handles its options by letting Xt remove args from this list.
192      ))
193   "Alist of command-line switches.
194 Elements look like (SWITCH-STRING . HANDLER-FUNCTION).
195 HANDLER-FUNCTION receives switch name as sole arg;
196 remaining command-line args are in the variable `command-line-args-left'.")
197
198 ;;; default switches
199 ;;; Note: these doc strings are semi-magical.
200
201 (defun command-line-do-help (arg)
202   "Print the XEmacs usage message and exit."
203   (let ((standard-output 'external-debugging-output))
204     (princ (concat "\n" (emacs-version) "\n\n"))
205     (princ
206      (if (featurep 'x)
207          (concat "When creating a window on an X display, "
208                  (emacs-name)
209                  " accepts all standard X Toolkit
210 command line options plus the following:
211   -iconname <title>     Use title as the icon name.
212   -mc <color>           Use color as the mouse color.
213   -cr <color>           Use color as the text-cursor foregound color.
214   -private              Install a private colormap.
215
216 In addition, the")
217        "The"))
218     (princ " following options are accepted:
219   -t <device>           Use TTY <device> instead of the terminal for input
220                         and output.  This implies the -nw option.
221   -nw                   Inhibit the use of any window-system-specific
222                         display code: use the current tty.
223   -batch                Execute noninteractively (messages go to stderr).
224   -debug-init           Enter the debugger if an error in the init file occurs.
225   -unmapped             Do not map the initial frame.
226   -no-site-file         Do not load the site-specific init file (site-start.el).
227   -no-init-file         Do not load the user-specific init file (~/.emacs).
228   -no-early-packages    Do not process early packages.
229   -no-autoloads         Do not load global symbol files (auto-autoloads) at
230                         startup.  Also implies `-vanilla'.
231   -vanilla              Equivalent to -q -no-site-file -no-early-packages.
232   -q                    Same as -no-init-file.
233   -user-init-file <file> Use <file> as init file.
234   -user-init-directory <directory> use <directory> as init directory.
235   -user <user>          Load user's init file instead of your own.
236                         Equivalent to -user-init-file ~<user>/.emacs
237                                       -user-init-directory ~<user>/.xemacs/
238   -u <user>             Same as -user.\n")
239    (let ((l command-switch-alist)
240           (insert (lambda (&rest x)
241                     (princ "  ")
242                     (let ((len 2))
243                       (while x
244                         (princ (car x))
245                         (incf len (length (car x)))
246                         (setq x (cdr x)))
247                       (when (>= len 24)
248                         (terpri) (setq len 0))
249                       (while (< len 24)
250                         (princ " ")
251                         (incf len))))))
252       (while l
253         (let ((name (car (car l)))
254               (fn (cdr (car l)))
255               doc arg cons)
256           (cond
257            ((and (symbolp fn) (get fn 'undocumented)) nil)
258            (t
259             (setq doc (documentation fn))
260             (if (member doc '(nil "")) (setq doc "(undocumented)"))
261             (cond ((string-match "\n\\(<.*>\\)\n?\\'" doc)
262                    ;; Doc of the form "The frobber switch\n<arg1> <arg2>"
263                    (setq arg (substring doc (match-beginning 1) (match-end 1))
264                          doc (substring doc 0 (match-beginning 0))))
265                   ((string-match "\n+\\'" doc)
266                    (setq doc (substring doc 0 (match-beginning 0)))))
267             (if (and (setq cons (rassq fn command-switch-alist))
268                      (not (eq cons (car l))))
269                 (setq doc (format "Same as %s." (car cons))))
270             (if arg
271                 (funcall insert name " " arg)
272               (funcall insert name))
273             (princ doc)
274             (terpri))))
275         (setq l (cdr l))))
276     (princ (concat "\
277   +N <file>             Start displaying <file> at line N.
278
279 Anything else is considered a file name, and is placed into a buffer for
280 editing.
281
282 " (emacs-name) " has an online tutorial and manuals.  Type ^Ht (Control-h t) after
283 starting XEmacs to run the tutorial.  Type ^Hi to enter the manual browser.
284 Type ^H^H^H (Control-h Control-h Control-h) to get more help options.\n")
285
286     (kill-emacs 0))))
287
288 (defun command-line-do-funcall (arg)
289   "Invoke the named lisp function with no arguments.
290 <function>"
291   (funcall (intern (pop command-line-args-left))))
292 (fset 'command-line-do-funcall-1 'command-line-do-funcall)
293 (put 'command-line-do-funcall-1 'undocumented t)
294
295 (defun command-line-do-eval (arg)
296   "Evaluate the lisp form.  Quote it carefully.
297 <form>"
298   (eval (read (pop command-line-args-left))))
299
300 (defun command-line-do-load (arg)
301   "Load the named file of Lisp code into XEmacs.
302 <file>"
303   (let ((file (pop command-line-args-left)))
304     ;; Take file from default dir if it exists there;
305     ;; otherwise let `load' search for it.
306     (if (file-exists-p (expand-file-name file))
307         (setq file (expand-file-name file)))
308     (load file nil t)))
309
310 (defun command-line-do-insert (arg)
311   "Insert file into the current buffer.
312 <file>"
313   (insert-file-contents (pop command-line-args-left)))
314
315 (defun command-line-do-kill (arg)
316   "Exit XEmacs."
317   (kill-emacs t))
318
319 (defun command-line-do-version (arg)
320   "Print version info and exit."
321   (princ (concat (emacs-version) "\n"))
322   (kill-emacs 0))
323
324 \f
325 ;;; Processing the command line and loading various init files
326
327 (defun early-error-handler (&rest debugger-args)
328   "You should probably not be using this."
329   ;; Used as the debugger during XEmacs initialization; if an error occurs,
330   ;; print some diagnostics, and kill XEmacs.
331
332   ;; output the contents of the warning buffer, since it won't be seen
333   ;; otherwise.
334   ;; #### kludge!  The call to Feval forces the pending warnings to
335   ;; get output.  There definitely needs to be a better way.
336   (let ((buffer (eval (get-buffer-create "*Warnings*"))))
337     (princ (buffer-substring (point-min buffer) (point-max buffer) buffer)
338            'external-debugging-output))
339
340   (let ((string "Initialization error")
341         (error (nth 1 debugger-args))
342         (debug-on-error nil)
343         (stream 'external-debugging-output))
344     (if (null error)
345         (princ string stream)
346       (princ (concat "\n" string ": ") stream)
347       (condition-case ()
348           (display-error error stream)
349         (error (princ "<<< error printing error message >>>" stream)))
350       (princ "\n" stream)
351       (if (memq (car-safe error) '(void-function void-variable))
352           (princ "
353         This probably means that XEmacs is picking up an old version of
354         the lisp library, or that some .elc files are not up-to-date.\n"
355                  stream)))
356     (when (not suppress-early-error-handler-backtrace)
357       (let ((print-length 1000)
358             (print-level 1000)
359             (print-escape-newlines t)
360             (print-readably nil))
361         (when (getenv "EMACSLOADPATH")
362           (princ (format "\n$EMACSLOADPATH is %s" (getenv "EMACSLOADPATH"))
363                  stream))
364         (princ (format "\nexec-directory is %S" exec-directory) stream)
365         (princ (format "\ndata-directory is %S" data-directory) stream)
366         (princ (format "\ndata-directory-list is %S" data-directory-list) stream)
367         (princ (format "\ndoc-directory is %S" doc-directory) stream)
368         (princ (format "\nload-path is %S" load-path) stream)
369         (princ "\n\n" stream)))
370     (when (not suppress-early-error-handler-backtrace)
371       (backtrace stream t)))
372   (if (fboundp 'mswindows-message-box)
373       (mswindows-message-box "Initialization error"))
374   (kill-emacs -1))
375
376 (defun normal-top-level ()
377   (if command-line-processed
378       (message "Back to top level.")
379     (setq command-line-processed t)
380     ;; Canonicalize HOME (PWD is canonicalized by init_buffer in buffer.c)
381     (let ((value (user-home-directory)))
382       (if (and value
383                (< (length value) (length default-directory))
384                (equal (file-attributes default-directory)
385                       (file-attributes value)))
386           (setq default-directory (file-name-as-directory value))))
387     (setq default-directory (abbreviate-file-name default-directory))
388     (initialize-xemacs-paths)
389
390     (startup-set-invocation-environment)
391
392     (let ((debug-paths (or debug-paths
393                            (and (getenv "EMACSDEBUGPATHS")
394                                 t))))
395
396       (setq emacs-roots (paths-find-emacs-roots invocation-directory
397                                                 invocation-name))
398
399       (if debug-paths
400           (princ (format "emacs-roots:\n%S\n" emacs-roots)
401                  'external-debugging-output))
402
403       (if (null emacs-roots)
404           (startup-find-roots-warning)
405         (startup-setup-paths emacs-roots
406                              user-init-directory
407                              inhibit-early-packages
408                              inhibit-site-lisp
409                              debug-paths))
410       (startup-setup-paths-warning))
411
412     (if (and (not inhibit-autoloads)
413              lisp-directory)
414         (load (expand-file-name (file-name-sans-extension autoload-file-name)
415                                 lisp-directory) nil t))
416
417     (if (not inhibit-autoloads)
418         (progn
419           (if (not inhibit-early-packages)
420               (packages-load-package-auto-autoloads early-package-load-path))
421           (packages-load-package-auto-autoloads late-package-load-path)
422           (packages-load-package-auto-autoloads last-package-load-path)))
423
424     (unwind-protect
425         (command-line)
426       ;; Do this again, in case .emacs defined more abbreviations.
427       (setq default-directory (abbreviate-file-name default-directory))
428       ;; Specify the file for recording all the auto save files of
429       ;; this session.  This is used by recover-session.
430       (setq auto-save-list-file-name
431             (expand-file-name
432              (format "%s%d-%s"
433                      auto-save-list-file-prefix
434                      (emacs-pid)
435                      (system-name))))
436       (run-hooks 'emacs-startup-hook)
437       (and term-setup-hook
438            (run-hooks 'term-setup-hook))
439       (setq term-setup-hook nil)
440       ;;      ;; Modify the initial frame based on what .emacs puts into
441       ;;      ;; ...-frame-alist.
442       (frame-notice-user-settings)
443       ;;      ;;####FSFmacs junk
444       ;;      ;; Now we know the user's default font, so add it to the menu.
445       ;;      (if (fboundp 'font-menu-add-default)
446       ;;          (font-menu-add-default))
447       (when window-setup-hook
448         (run-hooks 'window-setup-hook))
449       (setq window-setup-hook nil))
450     ;;####FSFmacs junk
451     ;;      (or menubar-bindings-done
452     ;;    (precompute-menubar-bindings))
453     ))
454
455 ;;####FSFmacs junk
456 ;;; Precompute the keyboard equivalents in the menu bar items.
457 ;;(defun precompute-menubar-bindings ()
458 ;;  (if (eq window-system 'x)
459 ;;      (let ((submap (lookup-key global-map [menu-bar])))
460 ;;      (while submap
461 ;;        (and (consp (car submap))
462 ;;             (symbolp (car (car submap)))
463 ;;             (stringp (car-safe (cdr (car submap))))
464 ;;             (keymapp (cdr (cdr (car submap))))
465 ;;             (x-popup-menu nil (cdr (cdr (car submap)))))
466 ;;        (setq submap (cdr submap))))))
467
468 (defun command-line-early (args)
469   ;; This processes those switches which need to be processed before
470   ;; starting up the window system.
471
472   (setq command-line-default-directory default-directory)
473
474   ;; See if we should import version-control from the environment variable.
475   (let ((vc (getenv "VERSION_CONTROL")))
476     (cond ((eq vc nil))                 ;don't do anything if not set
477           ((or (string= vc "t")
478                (string= vc "numbered"))
479            (setq version-control t))
480           ((or (string= vc "nil")
481                (string= vc "existing"))
482            (setq version-control nil))
483           ((or (string= vc "never")
484                (string= vc "simple"))
485            (setq version-control 'never))))
486
487   ;;####FSFmacs
488   ;;  (if (let ((ctype
489   ;;         ;; Use the first of these three envvars that has a nonempty value.
490   ;;         (or (let ((string (getenv "LC_ALL")))
491   ;;               (and (not (equal string "")) string))
492   ;;             (let ((string (getenv "LC_CTYPE")))
493   ;;               (and (not (equal string "")) string))
494   ;;             (let ((string (getenv "LANG")))
495   ;;               (and (not (equal string "")) string)))))
496   ;;    (and ctype
497   ;;         (string-match iso-8859-1-locale-regexp ctype)))
498   ;;      (progn
499   ;;    (standard-display-european t)
500   ;;    (require 'iso-syntax)))
501
502   (setq load-user-init-file-p (not (noninteractive)))
503
504   ;; Allow (at least) these arguments anywhere in the command line
505   (let ((new-args nil)
506         (arg      nil))
507     (while args
508       (setq arg (pop args))
509       (cond
510        ((or (string= arg "-q")
511             (string= arg "-no-init-file"))
512         (setq load-user-init-file-p nil))
513        ((string= arg "-no-site-file")
514         (setq site-start-file nil))
515        ((or (string= arg "-no-early-packages")
516             (string= arg "--no-early-packages"))
517         (setq inhibit-early-packages t))
518        ((or (string= arg "-vanilla")
519             (string= arg "--vanilla")
520             ;; Some work on this one already done in emacs.c.
521             (string= arg "-no-autoloads")
522             (string= arg "--no-autoloads"))
523         (setq load-user-init-file-p nil
524               site-start-file nil))
525        ((string= arg "-user-init-file")
526         (setq user-init-file (pop args)))
527        ((string= arg "-user-init-directory")
528         (setq user-init-directory (file-name-as-directory (pop args))))
529        ((or (string= arg "-u")
530             (string= arg "-user"))
531         (let* ((user (pop args))
532                (home-user (concat "~" user)))
533           (setq user-init-file (find-user-init-file home-user)
534                 user-init-directory (file-name-as-directory
535                                      (paths-construct-path
536                                       (list home-user user-init-directory-base))))))
537        ((string= arg "-debug-init")
538         (setq init-file-debug t))
539        ((string= arg "-unmapped")
540         (setq initial-frame-unmapped-p t))
541        ((or (string= arg "-debug-paths")
542             (string= arg "--debug-paths"))
543         t)
544        ((or (string= arg "--") (string= arg "-"))
545         (while args
546           (push (pop args) new-args)))
547        (t (push arg new-args))))
548
549     (setq init-file-user (and load-user-init-file-p ""))
550
551     (nreverse new-args)))
552
553 (defconst initial-scratch-message "\
554 ;; This buffer is for notes you don't want to save, and for Lisp evaluation.
555 ;; If you want to create a file, first visit that file with C-x C-f,
556 ;; then enter the text in that file's own buffer.
557
558 "
559   "Initial message displayed in *scratch* buffer at startup.
560 If this is nil, no message will be displayed.")
561
562 (defun command-line ()
563   (let ((command-line-args-left (cdr command-line-args)))
564
565     (let ((debugger 'early-error-handler)
566           (debug-on-error t))
567
568       ;; Process magic command-line switches like -q and -u.  Do this
569       ;; before creating the first frame because some of these switches
570       ;; may affect that.  I think it's ok to do this before establishing
571       ;; the X connection, and maybe someday things like -nw can be
572       ;; handled here instead of down in C.
573       (setq command-line-args-left (command-line-early command-line-args-left))
574
575       ;; Setup the toolbar icon directory
576       (when (featurep 'toolbar)
577         (init-toolbar-location))
578
579       ;; Run the window system's init function.  tty is considered to be
580       ;; a type of window system for this purpose.  This creates the
581       ;; initial (non stdio) device.
582       (when (and initial-window-system (not noninteractive))
583         (funcall (intern (concat "init-"
584                                  (symbol-name initial-window-system)
585                                  "-win"))))
586
587       ;; When not in batch mode, this creates the first visible frame,
588       ;; and deletes the stdio device.
589       (frame-initialize))
590
591     ;; Reinitialize faces if necessary.  This function changes face if
592     ;; it is created during auto-autoloads loading.  Otherwise, it
593     ;; does nothing.
594     (startup-initialize-custom-faces)
595
596     ;;
597     ;; We have normality, I repeat, we have normality.  Anything you still
598     ;; can't cope with is therefore your own problem.  (And we don't need
599     ;; to kill XEmacs for it.)
600     ;;
601
602     ;;; Load init files.
603     (load-init-file)
604
605     (with-current-buffer (get-buffer "*scratch*")
606       (erase-buffer)
607       ;; (insert initial-scratch-message)
608       (set-buffer-modified-p nil)
609       (when (eq major-mode 'fundamental-mode)
610         (funcall initial-major-mode)))
611
612     ;; Load library for our terminal type.
613     ;; User init file can set term-file-prefix to nil to prevent this.
614     ;; Note that for any TTY's opened subsequently, the TTY init
615     ;; code will run this.
616     (when (and (eq 'tty (console-type))
617                (not (noninteractive)))
618       (load-terminal-library))
619
620     ;; Process the remaining args.
621     (command-line-1)
622
623     ;; it was turned on by default so that the warnings don't get displayed
624     ;; until after the splash screen.
625     (setq inhibit-warning-display nil)
626     ;; If -batch, terminate after processing the command options.
627     (when (noninteractive) (kill-emacs t))))
628
629 (defun load-terminal-library ()
630   (when term-file-prefix
631     (let ((term (getenv "TERM"))
632           hyphend)
633       (while (and term
634                   (not (load (concat term-file-prefix term) t t)))
635         ;; Strip off last hyphen and what follows, then try again
636         (if (setq hyphend (string-match "[-_][^-_]+\\'" term))
637             (setq term (substring term 0 hyphend))
638           (setq term nil))))))
639
640 (defun find-user-init-file (&optional directory)
641   "Determine the user's init file."
642   (unless directory
643     (setq directory "~"))
644   (dolist (file user-init-file-base-list)
645     (let ((expanded (paths-construct-path (list directory file))))
646       (when (file-exists-p expanded)
647         (return expanded)))))
648
649 (defun load-user-init-file ()
650   "This function actually reads the init file, .emacs."
651   (if (or user-init-file
652           (setq user-init-file (find-user-init-file)))
653       (load user-init-file t t t))
654   (unless inhibit-default-init
655     (let ((inhibit-startup-message nil))
656       ;; Users are supposed to be told their rights.
657       ;; (Plus how to get help and how to undo.)
658       ;; Don't you dare turn this off for anyone except yourself.
659       (load "default" t t))))
660
661 ;;; Load user's init file and default ones.
662 (defun load-init-file ()
663   (run-hooks 'before-init-hook)
664
665   ;; Run the site-start library if it exists.  The point of this file is
666   ;; that it is run before .emacs.  There is no point in doing this after
667   ;; .emacs; that is useless.
668   (when site-start-file
669     (load site-start-file t t))
670
671   ;; Sites should not disable this.  Only individuals should disable
672   ;; the startup message.
673   (setq inhibit-startup-message nil)
674
675   (let (debug-on-error-from-init-file
676         debug-on-error-should-be-set
677         (debug-on-error-initial
678          (if (eq init-file-debug t) 'startup init-file-debug)))
679     (let ((debug-on-error debug-on-error-initial))
680       (if (and load-user-init-file-p init-file-debug)
681           ;; Do this without a condition-case if the user wants to debug.
682           (load-user-init-file)
683         (condition-case error
684             (progn
685               (if load-user-init-file-p
686                   (load-user-init-file))
687               (setq init-file-had-error nil))
688           (error
689            (message "Error in init file: %s" (error-message-string error))
690            (display-warning 'initialization
691              (format "\
692 An error has occurred while loading %s:
693
694 %s
695
696 To ensure normal operation, you should investigate the cause of the error
697 in your initialization file and remove it.  Use the `-debug-init' option
698 to XEmacs to view a complete error backtrace."
699                      user-init-file (error-message-string error))
700              'error)
701            (setq init-file-had-error t))))
702       ;; If we can tell that the init file altered debug-on-error,
703       ;; arrange to preserve the value that it set up.
704       (or (eq debug-on-error debug-on-error-initial)
705           (setq debug-on-error-should-be-set t
706                 debug-on-error-from-init-file debug-on-error)))
707     (when debug-on-error-should-be-set
708       (setq debug-on-error debug-on-error-from-init-file)))
709
710   (setq init-file-loaded t)
711
712   ;; Do this here in case the init file sets mail-host-address.
713   ;; Don't do this here unless noninteractive, it is frequently wrong. -sb
714   ;; (or user-mail-address
715   (when noninteractive
716     (setq user-mail-address (concat (user-login-name) "@"
717                                     (or mail-host-address
718                                         (system-name)))))
719
720   (run-hooks 'after-init-hook)
721   nil)
722
723 (defun load-options-file (filename)
724   "Load the file of saved options (from the Options menu) called FILENAME.
725 Currently this does nothing but call `load', but it might be redefined
726 in the future to support automatically converting older options files to
727 a new format, when variables have changed, etc."
728   (load filename))
729
730 (defun command-line-1 ()
731   (cond
732    ((null command-line-args-left)
733     (unless noninteractive
734       ;; If there are no switches to process, run the term-setup-hook
735       ;; before displaying the copyright notice; there may be some need
736       ;; to do it before doing any output.  If we're not going to
737       ;; display a copyright notice (because other options are present)
738       ;; then this is run after those options are processed.
739       (run-hooks 'term-setup-hook)
740       ;; Don't let the hook be run twice.
741       (setq term-setup-hook nil)
742
743       ;; Don't clobber a non-scratch buffer if init file
744       ;; has selected it.
745       (when (string= (buffer-name) "*scratch*")
746         (unless (or inhibit-startup-message
747                     (input-pending-p))
748           (let (tmout circ-tmout)
749             (unwind-protect
750                 ;; Guts of with-timeout
751                 (catch 'tmout
752                   (setq tmout (add-timeout startup-message-timeout
753                                            (lambda (ignore)
754                                              (condition-case nil
755                                                  (throw 'tmout t)
756                                                (error nil)))
757                                            nil))
758                   (setq circ-tmout (display-splash-frame))
759                   (or nil;; (pos-visible-in-window-p (point-min))
760                       (goto-char (point-min)))
761                   (sit-for 0)
762                   (setq unread-command-event (next-command-event)))
763               (when tmout (disable-timeout tmout))
764               (when circ-tmout (disable-timeout circ-tmout)))))
765         (with-current-buffer (get-buffer "*scratch*")
766           ;; In case the XEmacs server has already selected
767           ;; another buffer, erase the one our message is in.
768           (erase-buffer)
769           (when (stringp initial-scratch-message)
770             (insert initial-scratch-message))
771           (set-buffer-modified-p nil)))))
772
773    (t
774     ;; Command-line-options exist
775     (let ((dir command-line-default-directory)
776           (file-count 0)
777           (line nil)
778           (end-of-options nil)
779           file-p arg tem)
780       (while command-line-args-left
781         (setq arg (pop command-line-args-left))
782         (cond
783          (end-of-options
784           (setq file-p t))
785          ((setq tem (when (eq (aref arg 0) ?-)
786                       (or (assoc arg command-switch-alist)
787                           (assoc (substring arg 1)
788                                  command-switch-alist))))
789           (funcall (cdr tem) arg))
790          ((string-match "\\`\\+[0-9]+\\'" arg)
791           (setq line (string-to-int arg)))
792          ;; "- file" means don't treat "file" as a switch
793          ;;  ("+0 file" has the same effect; "-" added
794          ;;   for unixoidiality).
795          ;; This is worthless; the `unixoid' way is "./file". -jwz
796          ((or (string= arg "-") (string= arg "--"))
797           (setq end-of-options t))
798          (t
799           (setq file-p t)))
800
801         (when file-p
802           (setq file-p nil)
803           (incf file-count)
804           (setq arg (expand-file-name arg dir))
805           (cond
806            ((= file-count 1)
807             (find-file arg))
808            (noninteractive (find-file arg))
809            (t (find-file-other-window arg)))
810           (when line
811             (goto-line line)
812             (setq line nil))))))))
813
814 (defvar startup-presentation-hack-keymap
815   (let ((map (make-sparse-keymap)))
816     (set-keymap-name map 'startup-presentation-hack-keymap)
817     (define-key map '[button1] 'startup-presentation-hack)
818     (define-key map '[button2] 'startup-presentation-hack)
819     map)
820   "Putting yesterday in the future tomorrow.")
821
822 (defun startup-presentation-hack ()
823   (interactive)
824   (let ((e last-command-event))
825     (and (button-press-event-p e)
826          (setq e (extent-at (event-point e)
827                             (event-buffer e)
828                             'startup-presentation-hack))
829          (setq e (extent-property e 'startup-presentation-hack))
830          (if (consp e)
831              (apply (car e) (cdr e))
832            (while (keymapp (indirect-function e))
833              (let ((map e)
834                    (overriding-local-map (indirect-function e)))
835                (setq e (read-key-sequence
836                         (let ((p (keymap-prompt map t)))
837                           (cond ((symbolp map)
838                                  (if p
839                                      (format "%s %s " map p)
840                                    (format "%s " map)))
841                                 (p)
842                                 (t
843                                  (prin1-to-string map))))))
844                (if (and (button-release-event-p (elt e 0))
845                         (null (key-binding e)))
846                    (setq e map)         ; try again
847                  (setq e (key-binding e)))))
848            (call-interactively e)))))
849
850 (defun startup-presentation-hack-help (e)
851   (setq e (extent-property e 'startup-presentation-hack))
852   (if (consp e)
853       (format "Evaluate %S" e)
854     (symbol-name e)))
855
856 (defun splash-frame-present-hack (e v)
857   ;;   (set-extent-property e 'mouse-face 'highlight)
858   ;;   (set-extent-property e 'keymap
859   ;;                           startup-presentation-hack-keymap)
860   ;;   (set-extent-property e 'startup-presentation-hack v)
861   ;;   (set-extent-property e 'help-echo
862   ;;                           'startup-presentation-hack-help)
863   )
864
865 (defun splash-hack-version-string ()
866   (save-excursion
867     (save-restriction
868       (goto-char (point-min))
869       (re-search-forward "^XEmacs" nil t)
870       (narrow-to-region (point-at-bol) (point-at-eol))
871       (goto-char (point-min))
872       (when (re-search-forward " \\[Lucid\\]" nil t)
873         (delete-region (match-beginning 0) (match-end 0)))
874       (when (re-search-forward "[^(][^)]*-[^)]*-" nil t)
875         (delete-region (1+ (match-beginning 0)) (match-end 0))
876         (insert "("))
877       (goto-char (point-max))
878       (search-backward " " nil t)
879       (when (search-forward "." nil t)
880         (delete-region (1- (point)) (point-max))))))
881
882 (defun splash-frame-present (l)
883   (cond ((stringp l)
884          (insert l))
885         ((eq (car-safe l) 'face)
886          ;; (face name string)
887          (let ((p (point)))
888            (splash-frame-present (elt l 2))
889            (if (fboundp 'set-extent-face)
890                (set-extent-face (make-extent p (point))
891                                 (elt l 1)))))
892         ((eq (car-safe l) 'key)
893          (let* ((c (elt l 1))
894                 (p (point))
895                 (k (where-is-internal c nil t)))
896            (insert (if k (key-description k)
897                      (format "M-x %s" c)))
898            (if (fboundp 'set-extent-face)
899                (let ((e (make-extent p (point))))
900                  (set-extent-face e 'bold)
901                  (splash-frame-present-hack e c)))))
902         ((eq (car-safe l) 'funcall)
903          ;; (funcall (fun . args) string)
904          (let ((p (point)))
905            (splash-frame-present (elt l 2))
906            (if (fboundp 'set-extent-face)
907                (splash-frame-present-hack (make-extent p (point))
908                                           (elt l 1)))))
909         ((consp l)
910          (mapcar 'splash-frame-present l))
911         (t
912          (error "WTF!?"))))
913
914 (defun startup-center-spaces (glyph)
915   ;; Return the number of spaces to insert in order to center
916   ;; the given glyph (may be a string or a pixmap).
917   ;; Assume spaces are as wide as avg-pixwidth.
918   ;; Won't be quite right for proportional fonts, but it's the best we can do.
919   ;; Maybe the new redisplay will export something a glyph-width function.
920   ;;; #### Yes, there is a glyph-width function but it isn't quite what
921   ;;; #### this was expecting.  Or is it?
922   ;; (An alternate way to get avg-pixwidth would be to use x-font-properties
923   ;; and calculate RESOLUTION_X * AVERAGE_WIDTH / 722.7, but it's no better.)
924
925   ;; This function is used in about.el too.
926   (let* ((avg-pixwidth     (round (/ (frame-pixel-width) (frame-width))))
927          (fill-area-width  (* avg-pixwidth (- fill-column left-margin)))
928          (glyph-pixwidth   (cond ((stringp glyph)
929                                   (* avg-pixwidth (length glyph)))
930                                  ;; #### the pixmap option should be removed
931                                  ;;((pixmapp glyph)
932                                  ;; (pixmap-width glyph))
933                                  ((glyphp glyph)
934                                   (glyph-width glyph))
935                                  (t
936                                   (error "startup-center-spaces: bad arg")))))
937     (+ left-margin
938        (round (/ (/ (- fill-area-width glyph-pixwidth) 2) avg-pixwidth)))))
939
940 (defun splash-frame-body ()
941   `[((face (blue bold underline)
942            "\nDistribution, copying license, warranty:\n\n")
943      "Please visit the XEmacs website at http://www.xemacs.org !\n\n"
944      ,@(if (featurep 'sparcworks)
945            `( "\
946 Sun provides support for the WorkShop/XEmacs integration package only.
947 All other XEmacs packages are provided to you \"AS IS\".\n"
948               ,@(let ((lang (or (getenv "LC_ALL") (getenv "LC_MESSAGES")
949                                 (getenv "LANG"))))
950                   (if (and
951                        (not (featurep 'mule)) ;; Already got mule?
952                        ;; No Mule support on tty's yet
953                        (not (eq 'tty (console-type)))
954                        lang ;; Non-English locale?
955                        (not (string= lang "C"))
956                        (not (string-match "^en" lang))
957                        ;; Comes with Sun WorkShop
958                        (locate-file "xemacs-mule" exec-path))
959                       '( "\
960 This version of XEmacs has been built with support for Latin-1 languages only.
961 To handle other languages you need to run a Multi-lingual (`Mule') version of
962 XEmacs, by either running the command `xemacs-mule', or by using the X resource
963 `ESERVE*defaultXEmacsPath: xemacs-mule' when starting XEmacs from Sun WorkShop.
964 \n")))))
965      ((key describe-no-warranty)
966       ": "(face (red bold) "XEmacs comes with ABSOLUTELY NO WARRANTY\n"))
967      ((key describe-copying)
968       ": conditions to give out copies of XEmacs\n")
969      ((key describe-distribution)
970       ": how to get the latest version\n")
971      "\n--\n"
972      (face italic "\
973 Copyright (C) 1985-1999 Free Software Foundation, Inc.
974 Copyright (C) 1990-1994 Lucid, Inc.
975 Copyright (C) 1993-1997 Sun Microsystems, Inc. All Rights Reserved.
976 Copyright (C) 1994-1996 Board of Trustees, University of Illinois
977 Copyright (C) 1995-1996 Ben Wing\n"))
978
979     ((face (blue bold underline) "\nInformation, on-line help:\n\n")
980      "XEmacs comes with plenty of documentation...\n\n"
981      ,@(if (string-match "beta" emacs-version)
982            `((key describe-beta)
983              ": " (face (red bold)
984                         "This is an Experimental version of XEmacs.\n"))
985          `( "\n"))
986      ((key xemacs-local-faq)
987       ": read the XEmacs FAQ (a " (face underline "capital") " F!)\n")
988      ((key help-with-tutorial)
989       ": read the XEmacs tutorial (also available through the "
990       (face bold "Help") " menu)\n")
991      ((key help-command)
992       ": get help on using XEmacs (also available through the "
993       (face bold "Help") " menu)\n")
994      ((key info) ": read the on-line documentation\n\n")
995      ((key describe-project) ": read about the GNU project\n")
996      ((key about-xemacs) ": see who's developing XEmacs\n"))
997
998     ((face (blue bold underline) "\nUseful stuff:\n\n")
999      "Things that you should know rather quickly...\n\n"
1000      ((key find-file) ": visit a file\n")
1001      ((key save-buffer) ": save changes\n")
1002      ((key advertised-undo) ": undo changes\n")
1003      ((key save-buffers-kill-emacs) ": exit XEmacs\n"))
1004     ])
1005
1006 ;; I really hate global variables, oh well.
1007 ;(defvar xemacs-startup-logo-function nil
1008 ;  "If non-nil, function called to provide the startup logo.
1009 ;This function should return an initialized glyph if it is used.")
1010
1011 ;; This will hopefully go away when gettext is functional.
1012 (defconst splash-frame-static-body
1013   `(,(emacs-version) "\n\n"
1014     (face italic "`C-' means the control key,`M-' means the meta key\n\n")))
1015
1016
1017 (defun circulate-splash-frame-elements (client-data)
1018   (with-current-buffer (aref client-data 2)
1019     (let ((buffer-read-only nil)
1020           (elements (aref client-data 3))
1021           (indice (aref client-data 0)))
1022       (goto-char (aref client-data 1))
1023       (delete-region (point) (point-max))
1024       (splash-frame-present (aref elements indice))
1025       (set-buffer-modified-p nil)
1026       (aset client-data 0
1027             (if (= indice (- (length elements) 1))
1028                 0
1029               (1+ indice )))
1030       )))
1031
1032 ;; #### This function now returns the (possibly nil) timeout circulating the
1033 ;; splash-frame elements
1034 (defun display-splash-frame ()
1035   (let ((logo xemacs-logo)
1036         (buffer-read-only nil)
1037         (cramped-p (eq 'tty (console-type))))
1038     (unless cramped-p (insert "\n"))
1039     (indent-to (startup-center-spaces logo))
1040     (set-extent-begin-glyph (make-extent (point) (point)) logo)
1041     ;;(splash-frame-present-hack (make-extent p (point)) 'about-xemacs))
1042     (insert "\n\n")
1043     (splash-frame-present splash-frame-static-body)
1044     (splash-hack-version-string)
1045     (goto-char (point-max))
1046     (let* ((after-change-functions nil) ; no font-lock, thank you
1047            (elements (splash-frame-body))
1048            (client-data `[ 1 ,(point) ,(current-buffer) ,elements ])
1049            tmout)
1050       (if (listp  elements) ;; A single element to display
1051           (splash-frame-present (splash-frame-body))
1052         ;; several elements to rotate
1053         (splash-frame-present (aref elements 0))
1054         (setq tmout (add-timeout splash-frame-timeout
1055                                  'circulate-splash-frame-elements
1056                                  client-data splash-frame-timeout)))
1057       (set-buffer-modified-p nil)
1058       tmout)))
1059
1060 ;;  (let ((present-file
1061 ;;         #'(lambda (f)
1062 ;;             (splash-frame-present
1063 ;;            (list 'funcall
1064 ;;                  (list 'find-file-other-window
1065 ;;                        (expand-file-name f data-directory))
1066 ;;                  f)))))
1067 ;;    (insert "For customization examples, see the files ")
1068 ;;    (funcall present-file "sample.emacs")
1069 ;;    (insert " and ")
1070 ;;    (funcall present-file "sample.Xdefaults")
1071 ;;    (insert (format "\nin the directory %s." data-directory)))
1072
1073 (defun startup-set-invocation-environment ()
1074   ;; XEmacs -- Steven Baur says invocation directory is nil if you
1075   ;; try to use XEmacs as a login shell.
1076   (or invocation-directory (setq invocation-directory default-directory))
1077   (setq invocation-directory
1078         ;; don't let /tmp_mnt/... get into the load-path or exec-path.
1079         (abbreviate-file-name invocation-directory)))
1080
1081 (defun startup-setup-paths (roots user-init-directory
1082                                   &optional
1083                                   inhibit-early-packages inhibit-site-lisp
1084                                   debug-paths)
1085   "Setup all the various paths.
1086 ROOTS is a list of plausible roots of the XEmacs directory hierarchy.
1087 If INHIBIT-PACKAGES is non-NIL, don't do packages.
1088 If INHIBIT-SITE-LISP is non-NIL, don't do site-lisp.
1089 If DEBUG-PATHS is non-NIL, print paths as they are detected.
1090 It's idempotent, so call this as often as you like!"
1091
1092   (apply #'(lambda (early late last)
1093              (setq early-packages (and (not inhibit-early-packages)
1094                                        early))
1095              (setq late-packages late)
1096              (setq last-packages last))
1097          (packages-find-packages
1098           roots
1099           (packages-compute-package-locations user-init-directory)))
1100
1101   (setq early-package-load-path (packages-find-package-load-path early-packages))
1102   (setq late-package-load-path (packages-find-package-load-path late-packages))
1103   (setq last-package-load-path (packages-find-package-load-path last-packages))
1104
1105   (if debug-paths
1106       (progn
1107         (princ (format "configure-package-path:\n%S\n" configure-package-path)
1108                'external-debugging-output)
1109         (princ (format "early-packages and early-package-load-path:\n%S\n%S\n"
1110                        early-packages early-package-load-path)
1111                'external-debugging-output)
1112         (princ (format "late-packages and late-package-load-path:\n%S\n%S\n"
1113                        late-packages late-package-load-path)
1114                'external-debugging-output)
1115         (princ (format "last-packages and last-package-load-path:\n%S\n%S\n"
1116                        last-packages last-package-load-path)
1117                'external-debugging-output)))
1118
1119   (setq lisp-directory (paths-find-lisp-directory roots))
1120
1121   (if debug-paths
1122       (princ (format "lisp-directory:\n%S\n" lisp-directory)
1123              'external-debugging-output))
1124
1125   (setq site-directory (and (null inhibit-site-lisp)
1126                             (paths-find-site-lisp-directory roots)))
1127
1128   (if (and debug-paths (null inhibit-site-lisp))
1129       (princ (format "site-directory:\n%S\n" site-directory)
1130              'external-debugging-output))
1131
1132   (setq load-path (paths-construct-load-path roots
1133                                              early-package-load-path
1134                                              late-package-load-path
1135                                              last-package-load-path
1136                                              lisp-directory
1137                                              site-directory))
1138
1139   (setq Info-directory-list
1140         (paths-construct-info-path roots
1141                                    early-packages late-packages last-packages))
1142
1143
1144   (if debug-paths
1145       (princ (format "Info-directory-list:\n%S\n" Info-directory-list)
1146              'external-debugging-output))
1147
1148   (setq exec-directory (paths-find-exec-directory roots))
1149
1150   (if debug-paths
1151       (princ (format "exec-directory:\n%s\n" exec-directory)
1152              'external-debugging-output))
1153
1154   (setq exec-path
1155         (paths-construct-exec-path roots exec-directory
1156                                    early-packages late-packages last-packages))
1157
1158   (if debug-paths
1159       (princ (format "exec-path:\n%S\n" exec-path)
1160              'external-debugging-output))
1161
1162   (setq doc-directory (paths-find-doc-directory roots))
1163
1164   (if debug-paths
1165       (princ (format "doc-directory:\n%S\n" doc-directory)
1166              'external-debugging-output))
1167
1168   (setq data-directory (paths-find-data-directory roots))
1169
1170   (if debug-paths
1171       (princ (format "data-directory:\n%S\n" data-directory)
1172              'external-debugging-output))
1173
1174   (setq data-directory-list (paths-construct-data-directory-list data-directory
1175                                                                  early-packages
1176                                                                  late-packages
1177                                                                  last-packages))
1178   (if debug-paths
1179       (princ (format "data-directory-list:\n%S\n" data-directory-list)
1180              'external-debugging-output)))
1181
1182 (defun startup-find-roots-warning ()
1183   (save-excursion
1184     (set-buffer (get-buffer-create " *warning-tmp*"))
1185     (erase-buffer)
1186     (buffer-disable-undo (current-buffer))
1187
1188     (insert "Couldn't find an obvious default for the root of the\n"
1189             "XEmacs hierarchy.")
1190
1191     (princ "\nWARNING:\n" 'external-debugging-output)
1192     (princ (buffer-string) 'external-debugging-output)))
1193
1194 (defun startup-setup-paths-warning ()
1195   (let ((warnings '()))
1196     (cond
1197      ((null (and lisp-directory exec-directory data-directory doc-directory
1198                  load-path))
1199       (save-excursion
1200         (set-buffer (get-buffer-create " *warning-tmp*"))
1201         (erase-buffer)
1202         (buffer-disable-undo (current-buffer))
1203         (if (null lisp-directory) (push "lisp-directory" warnings))
1204         (if (null exec-directory) (push "exec-directory" warnings))
1205         (if (null data-directory) (push "data-directory" warnings))
1206         (if (null doc-directory)  (push "doc-directory"  warnings))
1207         (if (null load-path)      (push "load-path"      warnings))
1208
1209         (insert "Couldn't find obvious defaults for:\n")
1210         (while warnings
1211           (insert (car warnings) "\n")
1212           (setq warnings (cdr warnings)))
1213         (insert "Perhaps some directories don't exist, "
1214                 "or the XEmacs executable,\n" (concat invocation-directory
1215                                                      invocation-name)
1216                 "\nis in a strange place?")
1217
1218         (princ "\nWARNING:\n" 'external-debugging-output)
1219         (princ (buffer-string) 'external-debugging-output)
1220         (erase-buffer)
1221         t)))))
1222
1223 ;;; startup.el ends here