XEmacs 21.2.27 "Hera".
[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 (cond
111                              ((eq system-type 'ms-dos) "_emacs")
112                              (t ".emacs"))
113   "Base of init file.")
114
115 (defvar user-init-directory
116   (file-name-as-directory
117    (paths-construct-path (list "~" user-init-directory-base)))
118   "Directory where user-installed init files may go.")
119
120 (defvar load-user-init-file-p t
121   "Non-nil if XEmacs should load the user's init file.")
122
123 ;; #### called `site-run-file' in FSFmacs
124
125 (defvar site-start-file (purecopy "site-start")
126   "File containing site-wide run-time initializations.
127 This file is loaded at run-time before `.emacs'.  It
128 contains inits that need to be in place for the entire site, but
129 which, due to their higher incidence of change, don't make sense to
130 load into XEmacs' dumped image.  Thus, the run-time load order is:
131
132   1. file described in this variable, if non-nil;
133   2. `.emacs';
134   3. `/path/to/xemacs/lisp/default.el'.
135
136 Don't use the `site-start.el' file for things some users may not like.
137 Put them in `default.el' instead, so that users can more easily
138 override them.  Users can prevent loading `default.el' with the `-q'
139 option or by setting `inhibit-default-init' in their own init files,
140 but inhibiting `site-start.el' requires `--no-site-file', which
141 is less convenient.")
142
143 ;;(defconst iso-8859-1-locale-regexp "8859[-_]?1"
144 ;;  "Regexp that specifies when to enable the ISO 8859-1 character set.
145 ;;We do that if this regexp matches the locale name
146 ;;specified by the LC_ALL, LC_CTYPE and LANG environment variables.")
147
148 (defvar mail-host-address nil
149   "*Name of this machine, for purposes of naming users.")
150
151 (defvar user-mail-address nil
152   "*Full mailing address of this user.
153 This is initialized based on `mail-host-address',
154 after your init file is read, in case it sets `mail-host-address'.")
155
156 (defvar auto-save-list-file-prefix "~/.saves-"
157   "Prefix for generating auto-save-list-file-name.
158 Emacs's pid and the system name will be appended to
159 this prefix to create a unique file name.")
160
161 (defvar init-file-debug nil)
162
163 (defvar init-file-had-error nil)
164
165 (defvar init-file-loaded nil
166   "True after the user's init file has been loaded (or suppressed with -q).
167 This will be true when `after-init-hook' is run and at all times
168 after, and will not be true at any time before.")
169
170 (defvar initial-frame-unmapped-p nil)
171
172 \f
173
174 (defvar command-switch-alist
175   (purecopy
176    '(("-help"   . command-line-do-help)
177      ("-version". command-line-do-version)
178      ("-V"      . command-line-do-version)
179      ("-funcall". command-line-do-funcall)
180      ("-f"      . command-line-do-funcall)
181      ("-e"      . command-line-do-funcall-1)
182      ("-eval"   . command-line-do-eval)
183      ("-load"   . command-line-do-load)
184      ("-l"      . command-line-do-load)
185      ("-insert" . command-line-do-insert)
186      ("-i"      . command-line-do-insert)
187      ("-kill"   . command-line-do-kill)
188      ;; Options like +35 are handled specially.
189      ;; Window-system, site, or package-specific code might add to this.
190      ;; X11 handles its options by letting Xt remove args from this list.
191      ))
192   "Alist of command-line switches.
193 Elements look like (SWITCH-STRING . HANDLER-FUNCTION).
194 HANDLER-FUNCTION receives switch name as sole arg;
195 remaining command-line args are in the variable `command-line-args-left'.")
196
197 ;;; default switches
198 ;;; Note: these doc strings are semi-magical.
199
200 (defun command-line-do-help (arg)
201   "Print the XEmacs usage message and exit."
202   (let ((standard-output 'external-debugging-output))
203     (princ (concat "\n" (emacs-version) "\n\n"))
204     (princ
205      (if (featurep 'x)
206          (concat "When creating a window on an X display, "
207                  (emacs-name)
208                  " accepts all standard X Toolkit
209 command line options plus the following:
210   -iconname <title>     Use title as the icon name.
211   -mc <color>           Use color as the mouse color.
212   -cr <color>           Use color as the text-cursor foregound color.
213   -private              Install a private colormap.
214
215 In addition, the")
216        "The"))
217     (princ " following options are accepted:
218   -t <device>           Use TTY <device> instead of the terminal for input
219                         and output.  This implies the -nw option.
220   -nw                   Inhibit the use of any window-system-specific
221                         display code: use the current tty.
222   -batch                Execute noninteractively (messages go to stderr).
223   -debug-init           Enter the debugger if an error in the init file occurs.
224   -unmapped             Do not map the initial frame.
225   -no-site-file         Do not load the site-specific init file (site-start.el).
226   -no-init-file         Do not load the user-specific init file (~/.emacs).
227   -no-early-packages    Do not process early packages.
228   -no-autoloads         Do not load global symbol files (auto-autoloads) at
229                         startup.  Also implies `-vanilla'.
230   -vanilla              Equivalent to -q -no-site-file -no-early-packages.
231   -q                    Same as -no-init-file.
232   -user-init-file <file> Use <file> as init file.
233   -user-init-directory <directory> use <directory> as init directory.
234   -user <user>          Load user's init file instead of your own.
235                         Equivalent to -user-init-file ~<user>/.emacs
236                                       -user-init-directory ~<user>/.xemacs/
237   -u <user>             Same as -user.\n")
238    (let ((l command-switch-alist)
239           (insert (lambda (&rest x)
240                     (princ "  ")
241                     (let ((len 2))
242                       (while x
243                         (princ (car x))
244                         (incf len (length (car x)))
245                         (setq x (cdr x)))
246                       (when (>= len 24)
247                         (terpri) (setq len 0))
248                       (while (< len 24)
249                         (princ " ")
250                         (incf len))))))
251       (while l
252         (let ((name (car (car l)))
253               (fn (cdr (car l)))
254               doc arg cons)
255           (cond
256            ((and (symbolp fn) (get fn 'undocumented)) nil)
257            (t
258             (setq doc (documentation fn))
259             (if (member doc '(nil "")) (setq doc "(undocumented)"))
260             (cond ((string-match "\n\\(<.*>\\)\n?\\'" doc)
261                    ;; Doc of the form "The frobber switch\n<arg1> <arg2>"
262                    (setq arg (substring doc (match-beginning 1) (match-end 1))
263                          doc (substring doc 0 (match-beginning 0))))
264                   ((string-match "\n+\\'" doc)
265                    (setq doc (substring doc 0 (match-beginning 0)))))
266             (if (and (setq cons (rassq fn command-switch-alist))
267                      (not (eq cons (car l))))
268                 (setq doc (format "Same as %s." (car cons))))
269             (if arg
270                 (funcall insert name " " arg)
271               (funcall insert name))
272             (princ doc)
273             (terpri))))
274         (setq l (cdr l))))
275     (princ (concat "\
276   +N <file>             Start displaying <file> at line N.
277
278 Anything else is considered a file name, and is placed into a buffer for
279 editing.
280
281 " (emacs-name) " has an online tutorial and manuals.  Type ^Ht (Control-h t) after
282 starting XEmacs to run the tutorial.  Type ^Hi to enter the manual browser.
283 Type ^H^H^H (Control-h Control-h Control-h) to get more help options.\n")
284
285     (kill-emacs 0))))
286
287 (defun command-line-do-funcall (arg)
288   "Invoke the named lisp function with no arguments.
289 <function>"
290   (funcall (intern (pop command-line-args-left))))
291 (fset 'command-line-do-funcall-1 'command-line-do-funcall)
292 (put 'command-line-do-funcall-1 'undocumented t)
293
294 (defun command-line-do-eval (arg)
295   "Evaluate the lisp form.  Quote it carefully.
296 <form>"
297   (eval (read (pop command-line-args-left))))
298
299 (defun command-line-do-load (arg)
300   "Load the named file of Lisp code into XEmacs.
301 <file>"
302   (let ((file (pop command-line-args-left)))
303     ;; Take file from default dir if it exists there;
304     ;; otherwise let `load' search for it.
305     (if (file-exists-p (expand-file-name file))
306         (setq file (expand-file-name file)))
307     (load file nil t)))
308
309 (defun command-line-do-insert (arg)
310   "Insert file into the current buffer.
311 <file>"
312   (insert-file-contents (pop command-line-args-left)))
313
314 (defun command-line-do-kill (arg)
315   "Exit XEmacs."
316   (kill-emacs t))
317
318 (defun command-line-do-version (arg)
319   "Print version info and exit."
320   (princ (concat (emacs-version) "\n"))
321   (kill-emacs 0))
322
323 \f
324 ;;; Processing the command line and loading various init files
325
326 (defun early-error-handler (&rest debugger-args)
327   "You should probably not be using this."
328   ;; Used as the debugger during XEmacs initialization; if an error occurs,
329   ;; print some diagnostics, and kill XEmacs.
330
331   ;; output the contents of the warning buffer, since it won't be seen
332   ;; otherwise.
333   ;; #### kludge!  The call to Feval forces the pending warnings to
334   ;; get output.  There definitely needs to be a better way.
335   (let ((buffer (eval (get-buffer-create "*Warnings*"))))
336     (princ (buffer-substring (point-min buffer) (point-max buffer) buffer)
337            'external-debugging-output))
338
339   (let ((string "Initialization error")
340         (error (nth 1 debugger-args))
341         (debug-on-error nil)
342         (stream 'external-debugging-output))
343     (if (null error)
344         (princ string stream)
345       (princ (concat "\n" string ": ") stream)
346       (condition-case ()
347           (display-error error stream)
348         (error (princ "<<< error printing error message >>>" stream)))
349       (princ "\n" stream)
350       (if (memq (car-safe error) '(void-function void-variable))
351           (princ "
352         This probably means that XEmacs is picking up an old version of
353         the lisp library, or that some .elc files are not up-to-date.\n"
354                  stream)))
355     (when (not suppress-early-error-handler-backtrace)
356       (let ((print-length 1000)
357             (print-level 1000)
358             (print-escape-newlines t)
359             (print-readably nil))
360         (when (getenv "EMACSLOADPATH")
361           (princ (format "\n$EMACSLOADPATH is %s" (getenv "EMACSLOADPATH"))
362                  stream))
363         (princ (format "\nexec-directory is %S" exec-directory) stream)
364         (princ (format "\ndata-directory is %S" data-directory) stream)
365         (princ (format "\ndata-directory-list is %S" data-directory-list) stream)
366         (princ (format "\ndoc-directory is %S" doc-directory) stream)
367         (princ (format "\nload-path is %S" load-path) stream)
368         (princ "\n\n" stream)))
369     (when (not suppress-early-error-handler-backtrace)
370       (backtrace stream t)))
371   (kill-emacs -1))
372
373 (defvar lock-directory)
374 (defvar superlock-file)
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
534                 (paths-construct-path (list home-user user-init-file-base)))
535           (setq user-init-directory
536                 (file-name-as-directory
537                  (paths-construct-path (list home-user user-init-directory-base))))))
538        ((string= arg "-debug-init")
539         (setq init-file-debug t))
540        ((string= arg "-unmapped")
541         (setq initial-frame-unmapped-p t))
542        ((or (string= arg "-debug-paths")
543             (string= arg "--debug-paths"))
544         t)
545        ((or (string= arg "--") (string= arg "-"))
546         (while args
547           (push (pop args) new-args)))
548        (t (push arg new-args))))
549
550     (setq init-file-user (and load-user-init-file-p ""))
551
552     (nreverse new-args)))
553
554 (defconst initial-scratch-message "\
555 ;; This buffer is for notes you don't want to save, and for Lisp evaluation.
556 ;; If you want to create a file, first visit that file with C-x C-f,
557 ;; then enter the text in that file's own buffer.
558
559 "
560   "Initial message displayed in *scratch* buffer at startup.
561 If this is nil, no message will be displayed.")
562
563 (defun command-line ()
564   (let ((command-line-args-left (cdr command-line-args)))
565
566     (let ((debugger 'early-error-handler)
567           (debug-on-error t))
568
569       ;; Process magic command-line switches like -q and -u.  Do this
570       ;; before creating the first frame because some of these switches
571       ;; may affect that.  I think it's ok to do this before establishing
572       ;; the X connection, and maybe someday things like -nw can be
573       ;; handled here instead of down in C.
574       (setq command-line-args-left (command-line-early command-line-args-left))
575
576       ;; Setup the toolbar icon directory
577       (when (featurep 'toolbar)
578         (init-toolbar-location))
579
580       ;; Run the window system's init function.  tty is considered to be
581       ;; a type of window system for this purpose.  This creates the
582       ;; initial (non stdio) device.
583       (when (and initial-window-system (not noninteractive))
584         (funcall (intern (concat "init-"
585                                  (symbol-name initial-window-system)
586                                  "-win"))))
587
588       ;; When not in batch mode, this creates the first visible frame,
589       ;; and deletes the stdio device.
590       (frame-initialize))
591
592     ;;
593     ;; We have normality, I repeat, we have normality.  Anything you still
594     ;; can't cope with is therefore your own problem.  (And we don't need
595     ;; to kill XEmacs for it.)
596     ;;
597
598     ;;; Load init files.
599     (load-init-file)
600
601     (with-current-buffer (get-buffer "*scratch*")
602       (erase-buffer)
603       ;; (insert initial-scratch-message)
604       (set-buffer-modified-p nil)
605       (when (eq major-mode 'fundamental-mode)
606         (funcall initial-major-mode)))
607
608     ;; Load library for our terminal type.
609     ;; User init file can set term-file-prefix to nil to prevent this.
610     ;; Note that for any TTY's opened subsequently, the TTY init
611     ;; code will run this.
612     (when (and (eq 'tty (console-type))
613                (not (noninteractive)))
614       (load-terminal-library))
615
616     ;; Process the remaining args.
617     (command-line-1)
618
619     ;; it was turned on by default so that the warnings don't get displayed
620     ;; until after the splash screen.
621     (setq inhibit-warning-display nil)
622     ;; If -batch, terminate after processing the command options.
623     (when (noninteractive) (kill-emacs t))))
624
625 (defun load-terminal-library ()
626   (when term-file-prefix
627     (let ((term (getenv "TERM"))
628           hyphend)
629       (while (and term
630                   (not (load (concat term-file-prefix term) t t)))
631         ;; Strip off last hyphen and what follows, then try again
632         (if (setq hyphend (string-match "[-_][^-_]+\\'" term))
633             (setq term (substring term 0 hyphend))
634           (setq term nil))))))
635
636 (defun load-user-init-file ()
637   "This function actually reads the init file, .emacs."
638   (if (not user-init-file)
639       (setq user-init-file
640             (paths-construct-path (list "~" user-init-file-base))))
641   (load user-init-file t t t)
642   (unless inhibit-default-init
643     (let ((inhibit-startup-message nil))
644       ;; Users are supposed to be told their rights.
645       ;; (Plus how to get help and how to undo.)
646       ;; Don't you dare turn this off for anyone except yourself.
647       (load "default" t t))))
648
649 ;;; Load user's init file and default ones.
650 (defun load-init-file ()
651   (run-hooks 'before-init-hook)
652
653   ;; Run the site-start library if it exists.  The point of this file is
654   ;; that it is run before .emacs.  There is no point in doing this after
655   ;; .emacs; that is useless.
656   (when site-start-file
657     (load site-start-file t t))
658
659   ;; Sites should not disable this.  Only individuals should disable
660   ;; the startup message.
661   (setq inhibit-startup-message nil)
662
663   (let (debug-on-error-from-init-file
664         debug-on-error-should-be-set
665         (debug-on-error-initial
666          (if (eq init-file-debug t) 'startup init-file-debug)))
667     (let ((debug-on-error debug-on-error-initial))
668       (if (and load-user-init-file-p init-file-debug)
669           ;; Do this without a condition-case if the user wants to debug.
670           (load-user-init-file)
671         (condition-case error
672             (progn
673               (if load-user-init-file-p
674                   (load-user-init-file))
675               (setq init-file-had-error nil))
676           (error
677            (message "Error in init file: %s" (error-message-string error))
678            (display-warning 'initialization
679              (format "\
680 An error has occurred while loading %s:
681
682 %s
683
684 To ensure normal operation, you should investigate the cause of the error
685 in your initialization file and remove it.  Use the `-debug-init' option
686 to XEmacs to view a complete error backtrace."
687                      user-init-file (error-message-string error))
688              'error)
689            (setq init-file-had-error t))))
690       ;; If we can tell that the init file altered debug-on-error,
691       ;; arrange to preserve the value that it set up.
692       (or (eq debug-on-error debug-on-error-initial)
693           (setq debug-on-error-should-be-set t
694                 debug-on-error-from-init-file debug-on-error)))
695     (when debug-on-error-should-be-set
696       (setq debug-on-error debug-on-error-from-init-file)))
697
698   (setq init-file-loaded t)
699
700   ;; Do this here in case the init file sets mail-host-address.
701   ;; Don't do this here unless noninteractive, it is frequently wrong. -sb
702   ;; (or user-mail-address
703   (when noninteractive
704     (setq user-mail-address (concat (user-login-name) "@"
705                                     (or mail-host-address
706                                         (system-name)))))
707
708   (run-hooks 'after-init-hook)
709   nil)
710
711 (defun load-options-file (filename)
712   "Load the file of saved options (from the Options menu) called FILENAME.
713 Currently this does nothing but call `load', but it might be redefined
714 in the future to support automatically converting older options files to
715 a new format, when variables have changed, etc."
716   (load filename))
717
718 (defun command-line-1 ()
719   (cond
720    ((null command-line-args-left)
721     (unless noninteractive
722       ;; If there are no switches to process, run the term-setup-hook
723       ;; before displaying the copyright notice; there may be some need
724       ;; to do it before doing any output.  If we're not going to
725       ;; display a copyright notice (because other options are present)
726       ;; then this is run after those options are processed.
727       (run-hooks 'term-setup-hook)
728       ;; Don't let the hook be run twice.
729       (setq term-setup-hook nil)
730
731       ;; Don't clobber a non-scratch buffer if init file
732       ;; has selected it.
733       (when (string= (buffer-name) "*scratch*")
734         (unless (or inhibit-startup-message
735                     (input-pending-p))
736           (let (tmout circ-tmout)
737             (unwind-protect
738                 ;; Guts of with-timeout
739                 (catch 'tmout
740                   (setq tmout (add-timeout startup-message-timeout
741                                            (lambda (ignore)
742                                              (condition-case nil
743                                                  (throw 'tmout t)
744                                                (error nil)))
745                                            nil))
746                   (setq circ-tmout (display-splash-frame))
747                   (or nil;; (pos-visible-in-window-p (point-min))
748                       (goto-char (point-min)))
749                   (sit-for 0)
750                   (setq unread-command-event (next-command-event)))
751               (when tmout (disable-timeout tmout))
752               (when circ-tmout (disable-timeout circ-tmout)))))
753         (with-current-buffer (get-buffer "*scratch*")
754           ;; In case the XEmacs server has already selected
755           ;; another buffer, erase the one our message is in.
756           (erase-buffer)
757           (when (stringp initial-scratch-message)
758             (insert initial-scratch-message))
759           (set-buffer-modified-p nil)))))
760
761    (t
762     ;; Command-line-options exist
763     (let ((dir command-line-default-directory)
764           (file-count 0)
765           (line nil)
766           (end-of-options nil)
767           first-file-buffer file-p arg tem)
768       (while command-line-args-left
769         (setq arg (pop command-line-args-left))
770         (cond
771          (end-of-options
772           (setq file-p t))
773          ((setq tem (when (eq (aref arg 0) ?-)
774                       (or (assoc arg command-switch-alist)
775                           (assoc (substring arg 1)
776                                  command-switch-alist))))
777           (funcall (cdr tem) arg))
778          ((string-match "\\`\\+[0-9]+\\'" arg)
779           (setq line (string-to-int arg)))
780          ;; "- file" means don't treat "file" as a switch
781          ;;  ("+0 file" has the same effect; "-" added
782          ;;   for unixoidiality).
783          ;; This is worthless; the `unixoid' way is "./file". -jwz
784          ((or (string= arg "-") (string= arg "--"))
785           (setq end-of-options t))
786          (t
787           (setq file-p t)))
788
789         (when file-p
790           (setq file-p nil)
791           (incf file-count)
792           (setq arg (expand-file-name arg dir))
793           (cond
794            ((= file-count 1) (setq first-file-buffer
795                                    (progn (find-file arg) (current-buffer))))
796            (noninteractive (find-file arg))
797            (t (find-file-other-window arg)))
798           (when line
799             (goto-line line)
800             (setq line nil))))))))
801
802 (defvar startup-presentation-hack-keymap
803   (let ((map (make-sparse-keymap)))
804     (set-keymap-name map 'startup-presentation-hack-keymap)
805     (define-key map '[button1] 'startup-presentation-hack)
806     (define-key map '[button2] 'startup-presentation-hack)
807     map)
808   "Putting yesterday in the future tomorrow.")
809
810 (defun startup-presentation-hack ()
811   (interactive)
812   (let ((e last-command-event))
813     (and (button-press-event-p e)
814          (setq e (extent-at (event-point e)
815                             (event-buffer e)
816                             'startup-presentation-hack))
817          (setq e (extent-property e 'startup-presentation-hack))
818          (if (consp e)
819              (apply (car e) (cdr e))
820            (while (keymapp (indirect-function e))
821              (let ((map e)
822                    (overriding-local-map (indirect-function e)))
823                (setq e (read-key-sequence
824                         (let ((p (keymap-prompt map t)))
825                           (cond ((symbolp map)
826                                  (if p
827                                      (format "%s %s " map p)
828                                    (format "%s " map)))
829                                 (p)
830                                 (t
831                                  (prin1-to-string map))))))
832                (if (and (button-release-event-p (elt e 0))
833                         (null (key-binding e)))
834                    (setq e map)         ; try again
835                  (setq e (key-binding e)))))
836            (call-interactively e)))))
837
838 (defun startup-presentation-hack-help (e)
839   (setq e (extent-property e 'startup-presentation-hack))
840   (if (consp e)
841       (format "Evaluate %S" e)
842     (symbol-name e)))
843
844 (defun splash-frame-present-hack (e v)
845   ;;   (set-extent-property e 'mouse-face 'highlight)
846   ;;   (set-extent-property e 'keymap
847   ;;                           startup-presentation-hack-keymap)
848   ;;   (set-extent-property e 'startup-presentation-hack v)
849   ;;   (set-extent-property e 'help-echo
850   ;;                           'startup-presentation-hack-help)
851   )
852
853 (defun splash-hack-version-string ()
854   (save-excursion
855     (save-restriction
856       (goto-char (point-min))
857       (re-search-forward "^XEmacs" nil t)
858       (narrow-to-region (point-at-bol) (point-at-eol))
859       (goto-char (point-min))
860       (when (re-search-forward " \\[Lucid\\]" nil t)
861         (delete-region (match-beginning 0) (match-end 0)))
862       (when (re-search-forward "[^(][^)]*-[^)]*-" nil t)
863         (delete-region (1+ (match-beginning 0)) (match-end 0))
864         (insert "("))
865       (goto-char (point-max))
866       (search-backward " " nil t)
867       (when (search-forward "." nil t)
868         (delete-region (1- (point)) (point-max))))))
869
870 (defun splash-frame-present (l)
871   (cond ((stringp l)
872          (insert l))
873         ((eq (car-safe l) 'face)
874          ;; (face name string)
875          (let ((p (point)))
876            (splash-frame-present (elt l 2))
877            (if (fboundp 'set-extent-face)
878                (set-extent-face (make-extent p (point))
879                                 (elt l 1)))))
880         ((eq (car-safe l) 'key)
881          (let* ((c (elt l 1))
882                 (p (point))
883                 (k (where-is-internal c nil t)))
884            (insert (if k (key-description k)
885                      (format "M-x %s" c)))
886            (if (fboundp 'set-extent-face)
887                (let ((e (make-extent p (point))))
888                  (set-extent-face e 'bold)
889                  (splash-frame-present-hack e c)))))
890         ((eq (car-safe l) 'funcall)
891          ;; (funcall (fun . args) string)
892          (let ((p (point)))
893            (splash-frame-present (elt l 2))
894            (if (fboundp 'set-extent-face)
895                (splash-frame-present-hack (make-extent p (point))
896                                           (elt l 1)))))
897         ((consp l)
898          (mapcar 'splash-frame-present l))
899         (t
900          (error "WTF!?"))))
901
902 (defun startup-center-spaces (glyph)
903   ;; Return the number of spaces to insert in order to center
904   ;; the given glyph (may be a string or a pixmap).
905   ;; Assume spaces are as wide as avg-pixwidth.
906   ;; Won't be quite right for proportional fonts, but it's the best we can do.
907   ;; Maybe the new redisplay will export something a glyph-width function.
908   ;;; #### Yes, there is a glyph-width function but it isn't quite what
909   ;;; #### this was expecting.  Or is it?
910   ;; (An alternate way to get avg-pixwidth would be to use x-font-properties
911   ;; and calculate RESOLUTION_X * AVERAGE_WIDTH / 722.7, but it's no better.)
912
913   ;; This function is used in about.el too.
914   (let* ((avg-pixwidth     (round (/ (frame-pixel-width) (frame-width))))
915          (fill-area-width  (* avg-pixwidth (- fill-column left-margin)))
916          (glyph-pixwidth   (cond ((stringp glyph)
917                                   (* avg-pixwidth (length glyph)))
918                                  ;; #### the pixmap option should be removed
919                                  ;;((pixmapp glyph)
920                                  ;; (pixmap-width glyph))
921                                  ((glyphp glyph)
922                                   (glyph-width glyph))
923                                  (t
924                                   (error "startup-center-spaces: bad arg")))))
925     (+ left-margin
926        (round (/ (/ (- fill-area-width glyph-pixwidth) 2) avg-pixwidth)))))
927
928 (defun splash-frame-body ()
929   `[((face (blue bold underline)
930            "\nDistribution, copying license, warranty:\n\n")
931      "Please visit the XEmacs website at http://www.xemacs.org !\n\n"
932      ,@(if (featurep 'sparcworks)
933            `( "\
934 Sun provides support for the WorkShop/XEmacs integration package only.
935 All other XEmacs packages are provided to you \"AS IS\".\n"
936               ,@(let ((lang (or (getenv "LC_ALL") (getenv "LC_MESSAGES")
937                                 (getenv "LANG"))))
938                   (if (and
939                        (not (featurep 'mule)) ;; Already got mule?
940                        ;; No Mule support on tty's yet
941                        (not (eq 'tty (console-type)))
942                        lang ;; Non-English locale?
943                        (not (string= lang "C"))
944                        (not (string-match "^en" lang))
945                        ;; Comes with Sun WorkShop
946                        (locate-file "xemacs-mule" exec-path))
947                       '( "\
948 This version of XEmacs has been built with support for Latin-1 languages only.
949 To handle other languages you need to run a Multi-lingual (`Mule') version of
950 XEmacs, by either running the command `xemacs-mule', or by using the X resource
951 `ESERVE*defaultXEmacsPath: xemacs-mule' when starting XEmacs from Sun WorkShop.
952 \n")))))
953      ((key describe-no-warranty)
954       ": "(face (red bold) "XEmacs comes with ABSOLUTELY NO WARRANTY\n"))
955      ((key describe-copying)
956       ": conditions to give out copies of XEmacs\n")
957      ((key describe-distribution)
958       ": how to get the latest version\n")
959      "\n--\n"
960      (face italic "\
961 Copyright (C) 1985-1999 Free Software Foundation, Inc.
962 Copyright (C) 1990-1994 Lucid, Inc.
963 Copyright (C) 1993-1997 Sun Microsystems, Inc. All Rights Reserved.
964 Copyright (C) 1994-1996 Board of Trustees, University of Illinois
965 Copyright (C) 1995-1996 Ben Wing\n"))
966
967     ((face (blue bold underline) "\nInformation, on-line help:\n\n")
968      "XEmacs comes with plenty of documentation...\n\n"
969      ,@(if (string-match "beta" emacs-version)
970            `((key describe-beta)
971              ": " (face (red bold)
972                         "This is an Experimental version of XEmacs.\n"))
973          `( "\n"))
974      ((key xemacs-local-faq)
975       ": read the XEmacs FAQ (a " (face underline "capital") " F!)\n")
976      ((key help-with-tutorial)
977       ": read the XEmacs tutorial (also available through the "
978       (face bold "Help") " menu)\n")
979      ((key help-command)
980       ": get help on using XEmacs (also available through the "
981       (face bold "Help") " menu)\n")
982      ((key info) ": read the on-line documentation\n\n")
983      ((key describe-project) ": read about the GNU project\n")
984      ((key about-xemacs) ": see who's developing XEmacs\n"))
985
986     ((face (blue bold underline) "\nUseful stuff:\n\n")
987      "Things that you should know rather quickly...\n\n"
988      ((key find-file) ": visit a file\n")
989      ((key save-buffer) ": save changes\n")
990      ((key advertised-undo) ": undo changes\n")
991      ((key save-buffers-kill-emacs) ": exit XEmacs\n"))
992     ])
993
994 ;; I really hate global variables, oh well.
995 ;(defvar xemacs-startup-logo-function nil
996 ;  "If non-nil, function called to provide the startup logo.
997 ;This function should return an initialized glyph if it is used.")
998
999 ;; This will hopefully go away when gettext is functional.
1000 (defconst splash-frame-static-body
1001   `(,(emacs-version) "\n\n"
1002     (face italic "`C-' means the control key,`M-' means the meta key\n\n")))
1003
1004
1005 (defun circulate-splash-frame-elements (client-data)
1006   (with-current-buffer (aref client-data 2)
1007     (let ((buffer-read-only nil)
1008           (elements (aref client-data 3))
1009           (indice (aref client-data 0)))
1010       (goto-char (aref client-data 1))
1011       (delete-region (point) (point-max))
1012       (splash-frame-present (aref elements indice))
1013       (set-buffer-modified-p nil)
1014       (aset client-data 0
1015             (if (= indice (- (length elements) 1))
1016                 0
1017               (1+ indice )))
1018       )))
1019
1020 ;; ### This function now returns the (possibly nil) timeout circulating the
1021 ;; splash-frame elements
1022 (defun display-splash-frame ()
1023   (let ((logo xemacs-logo)
1024         (buffer-read-only nil)
1025         (cramped-p (eq 'tty (console-type))))
1026     (unless cramped-p (insert "\n"))
1027     (indent-to (startup-center-spaces logo))
1028     (set-extent-begin-glyph (make-extent (point) (point)) logo)
1029     ;;(splash-frame-present-hack (make-extent p (point)) 'about-xemacs))
1030     (insert "\n\n")
1031     (splash-frame-present splash-frame-static-body)
1032     (splash-hack-version-string)
1033     (goto-char (point-max))
1034     (let* ((after-change-functions nil) ; no font-lock, thank you
1035            (elements (splash-frame-body))
1036            (client-data `[ 1 ,(point) ,(current-buffer) ,elements ])
1037            tmout)
1038       (if (listp  elements) ;; A single element to display
1039           (splash-frame-present (splash-frame-body))
1040         ;; several elements to rotate
1041         (splash-frame-present (aref elements 0))
1042         (setq tmout (add-timeout splash-frame-timeout
1043                                  'circulate-splash-frame-elements
1044                                  client-data splash-frame-timeout)))
1045       (set-buffer-modified-p nil)
1046       tmout)))
1047
1048 ;;  (let ((present-file
1049 ;;         #'(lambda (f)
1050 ;;             (splash-frame-present
1051 ;;            (list 'funcall
1052 ;;                  (list 'find-file-other-window
1053 ;;                        (expand-file-name f data-directory))
1054 ;;                  f)))))
1055 ;;    (insert "For customization examples, see the files ")
1056 ;;    (funcall present-file "sample.emacs")
1057 ;;    (insert " and ")
1058 ;;    (funcall present-file "sample.Xdefaults")
1059 ;;    (insert (format "\nin the directory %s." data-directory)))
1060
1061 (defun startup-set-invocation-environment ()
1062   ;; XEmacs -- Steven Baur says invocation directory is nil if you
1063   ;; try to use XEmacs as a login shell.
1064   (or invocation-directory (setq invocation-directory default-directory))
1065   (setq invocation-directory
1066         ;; don't let /tmp_mnt/... get into the load-path or exec-path.
1067         (abbreviate-file-name invocation-directory)))
1068
1069 (defun startup-setup-paths (roots user-init-directory
1070                                   &optional
1071                                   inhibit-early-packages inhibit-site-lisp
1072                                   debug-paths)
1073   "Setup all the various paths.
1074 ROOTS is a list of plausible roots of the XEmacs directory hierarchy.
1075 If INHIBIT-PACKAGES is non-NIL, don't do packages.
1076 If INHIBIT-SITE-LISP is non-NIL, don't do site-lisp.
1077 If DEBUG-PATHS is non-NIL, print paths as they are detected.
1078 It's idempotent, so call this as often as you like!"
1079
1080   (apply #'(lambda (early late last)
1081              (setq early-packages (and (not inhibit-early-packages)
1082                                        early))
1083              (setq late-packages late)
1084              (setq last-packages last))
1085          (packages-find-packages
1086           roots
1087           (packages-compute-package-locations user-init-directory)))
1088
1089   (setq early-package-load-path (packages-find-package-load-path early-packages))
1090   (setq late-package-load-path (packages-find-package-load-path late-packages))
1091   (setq last-package-load-path (packages-find-package-load-path last-packages))
1092
1093   (if debug-paths
1094       (progn
1095         (princ (format "configure-package-path:\n%S\n" configure-package-path)
1096                'external-debugging-output)
1097         (princ (format "early-packages and early-package-load-path:\n%S\n%S\n"
1098                        early-packages early-package-load-path)
1099                'external-debugging-output)
1100         (princ (format "late-packages and late-package-load-path:\n%S\n%S\n"
1101                        late-packages late-package-load-path)
1102                'external-debugging-output)
1103         (princ (format "last-packages and last-package-load-path:\n%S\n%S\n"
1104                        last-packages last-package-load-path)
1105                'external-debugging-output)))
1106
1107   (setq lisp-directory (paths-find-lisp-directory roots))
1108
1109   (if debug-paths
1110       (princ (format "lisp-directory:\n%S\n" lisp-directory)
1111              'external-debugging-output))
1112
1113   (setq site-directory (and (null inhibit-site-lisp)
1114                             (paths-find-site-lisp-directory roots)))
1115
1116   (if (and debug-paths (null inhibit-site-lisp))
1117       (princ (format "site-directory:\n%S\n" site-directory)
1118              'external-debugging-output))
1119
1120   (setq load-path (paths-construct-load-path roots
1121                                              early-package-load-path
1122                                              late-package-load-path
1123                                              last-package-load-path
1124                                              lisp-directory
1125                                              site-directory))
1126
1127   (setq Info-directory-list
1128         (paths-construct-info-path roots
1129                                    early-packages late-packages last-packages))
1130
1131
1132   (if debug-paths
1133       (princ (format "Info-directory-list:\n%S\n" Info-directory-list)
1134              'external-debugging-output))
1135
1136   (if (boundp 'lock-directory)
1137       (progn
1138         (setq lock-directory (paths-find-lock-directory roots))
1139         (setq superlock-file (paths-find-superlock-file lock-directory))
1140
1141         (if debug-paths
1142             (progn
1143               (princ (format "lock-directory:\n%S\n" lock-directory)
1144                      'external-debugging-output)
1145               (princ (format "superlock-file:\n%S\n" superlock-file)
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 ((lock (if (boundp 'lock-directory) lock-directory 't))
1196         (warnings '()))
1197     (if (and (stringp lock) (null (file-directory-p lock)))
1198         (setq lock nil))
1199     (cond
1200      ((null (and lisp-directory exec-directory data-directory doc-directory
1201                  load-path
1202                  lock))
1203       (save-excursion
1204         (set-buffer (get-buffer-create " *warning-tmp*"))
1205         (erase-buffer)
1206         (buffer-disable-undo (current-buffer))
1207         (if (null lisp-directory) (push "lisp-directory" warnings))
1208         (if (null lock)           (push "lock-directory" warnings))
1209         (if (null exec-directory) (push "exec-directory" warnings))
1210         (if (null data-directory) (push "data-directory" warnings))
1211         (if (null doc-directory)  (push "doc-directory"  warnings))
1212         (if (null load-path)      (push "load-path"      warnings))
1213
1214         (insert "Couldn't find obvious defaults for:\n")
1215         (while warnings
1216           (insert (car warnings) "\n")
1217           (setq warnings (cdr warnings)))
1218         (insert "Perhaps some directories don't exist, "
1219                 "or the XEmacs executable,\n" (concat invocation-directory
1220                                                      invocation-name)
1221                 "\nis in a strange place?")
1222
1223         (princ "\nWARNING:\n" 'external-debugging-output)
1224         (princ (buffer-string) 'external-debugging-output)
1225         (erase-buffer)
1226         t)))))
1227
1228 ;;; startup.el ends here