]> git.lyx.org Git - features.git/blob - src/lyx_main.C
Compaq cxx 6.5 will now compile lyx.
[features.git] / src / lyx_main.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12 #include <version.h>
13
14 #ifdef __GNUG__
15 #pragma implementation
16 #endif
17
18 #include "lyx_main.h"
19 #include "lyx_gui.h"
20 #include "frontends/LyXView.h"
21 #include "lyxfunc.h"
22 #include "lyxrc.h"
23 #include "buffer.h"
24 #include "bufferlist.h"
25 #include "debug.h"
26 #include "lastfiles.h"
27 #include "intl.h"
28 #include "lyxserver.h"
29 //#include "layout.h"
30 #include "lyxtextclasslist.h"
31 #include "gettext.h"
32 #include "kbmap.h"
33 #include "MenuBackend.h"
34 #include "ToolbarDefaults.h"
35 #include "lyxlex.h"
36 #include "encoding.h"
37 #include "converter.h"
38 #include "language.h"
39
40 #include "frontends/Alert.h"
41 #include "frontends/GUIRunTime.h"
42
43 #include "support/path.h"
44 #include "support/filetools.h"
45 #include "support/FileInfo.h"
46 #include "support/os.h"
47
48 #include <cstdlib>
49 #include <csignal>
50
51 using std::endl;
52
53 #ifndef CXX_GLOBAL_CSTD
54 using std::exit;
55 using std::signal;
56 using std::system;
57 #endif
58
59 extern void LoadLyXFile(string const &);
60 extern void QuitLyX();
61
62 string system_lyxdir;
63 string build_lyxdir;
64 string system_tempdir;
65 string user_lyxdir;     // Default $HOME/.lyx
66
67 // Should this be kept global? Asger says Yes.
68 DebugStream lyxerr;
69
70 boost::scoped_ptr<LastFiles> lastfiles;
71
72 // This is the global bufferlist object
73 BufferList bufferlist;
74
75 LyXServer * lyxserver = 0;
76 // this should be static, but I need it in buffer.C
77 bool finished = false;  // flag, that we are quitting the program
78
79 // convenient to have it here.
80 boost::scoped_ptr<kb_keymap> toplevel_keymap;
81
82
83 LyX::LyX(int * argc, char * argv[])
84 {
85         // Here we need to parse the command line. At least
86         // we need to parse for "-dbg" and "-help"
87         bool gui = easyParse(argc, argv);
88
89         // Global bindings (this must be done as early as possible.) (Lgb)
90         toplevel_keymap.reset(new kb_keymap);
91         defaultKeyBindings(toplevel_keymap.get());
92
93         // Make the GUI object, and let it take care of the
94         // command line arguments that concerns it.
95         lyxerr[Debug::INIT] << "Initializing LyXGUI..." << endl;
96         lyxGUI.reset(new LyXGUI(this, argc, argv, gui));
97         lyxerr[Debug::INIT] << "Initializing LyXGUI...done" << endl;
98
99         // Now the GUI and LyX have taken care of their arguments, so
100         // the only thing left on the command line should be
101         // filenames. Let's check anyway.
102         for (int argi = 1; argi < *argc ; ++argi) {
103                 if (argv[argi][0] == '-') {
104                         lyxerr << _("Wrong command line option `")
105                                << argv[argi]
106                                << _("'. Exiting.") << endl;
107                         exit(1);
108                 }
109         }
110
111         // Initialization of LyX (reads lyxrc and more)
112         lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
113         init(gui);
114         lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
115
116         lyxGUI->init();
117
118         // Load the files specified in the command line.
119         if ((*argc) == 2)
120                 lyxerr[Debug::INFO] << "Opening document..." << endl;
121         else if ((*argc) > 2)
122                 lyxerr[Debug::INFO] << "Opening documents..." << endl;
123
124         Buffer * last_loaded = 0;
125
126         for (int argi = (*argc) - 1; argi >= 1; --argi) {
127                 Buffer * loadb = bufferlist.loadLyXFile(argv[argi]);
128                 if (loadb != 0) {
129                         last_loaded = loadb;
130                 }
131         }
132
133         if (first_start) {
134                 string const splash =
135                         i18nLibFileSearch("examples", "splash.lyx");
136                 lyxerr[Debug::INIT] << "Opening splash document "
137                                << splash << "..." << endl;
138                 Buffer * loadb = bufferlist.loadLyXFile(splash);
139                 if (loadb != 0) {
140                         last_loaded = loadb;
141                 }
142         }
143
144         if (last_loaded != 0) {
145                 lyxerr[Debug::INIT] << "Yes we loaded some files." << endl;
146                 if (lyxrc.use_gui)
147                         lyxGUI->regBuf(last_loaded);
148         }
149
150         // Execute batch commands if available
151         if (!batch_command.empty()) {
152                 lyxerr << "About to handle -x '"
153                        << batch_command << "'" << endl;
154
155                 // no buffer loaded, create one
156                 if (!last_loaded)
157                         last_loaded = bufferlist.newFile("tmpfile", string());
158
159                 bool success = false;
160  
161                 // try to dispatch to last loaded buffer first
162                 bool dispatched = last_loaded->dispatch(batch_command, &success);
163
164                 // if this was successful, return.
165                 // Maybe we could do something more clever than aborting...
166                 if (dispatched) {
167                         QuitLyX();
168                         exit(!success);
169                 }
170
171                 // otherwise, let the GUI handle the batch command
172                 lyxGUI->regBuf(last_loaded);
173                 lyxGUI->getLyXView()->getLyXFunc()->verboseDispatch(batch_command, false);
174
175                 // fall through...
176         }
177
178         // Let the ball begin...
179         lyxGUI->runTime();
180 }
181
182
183 // A destructor is always necessary  (asierra-970604)
184 LyX::~LyX()
185 {
186 }
187
188
189 extern "C" {
190
191 static
192 void error_handler(int err_sig)
193 {
194         switch (err_sig) {
195         case SIGHUP:
196                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
197                 break;
198         case SIGINT:
199                 // no comments
200                 break;
201         case SIGFPE:
202                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
203                 break;
204         case SIGSEGV:
205                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
206                 lyxerr <<
207                         "Sorry, you have found a bug in LyX. "
208                         "Please read the bug-reporting instructions "
209                         "in Help->Introduction and send us a bug report, "
210                         "if necessary. Thanks !" << endl;
211                 break;
212         case SIGTERM:
213                 // no comments
214                 break;
215         }
216
217         // Deinstall the signal handlers
218         signal(SIGHUP, SIG_DFL);
219         signal(SIGINT, SIG_DFL);
220         signal(SIGFPE, SIG_DFL);
221         signal(SIGSEGV, SIG_DFL);
222         signal(SIGTERM, SIG_DFL);
223
224         LyX::emergencyCleanup();
225
226         lyxerr << "Bye." << endl;
227         if (err_sig!= SIGHUP &&
228            (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
229                 lyx::abort();
230         exit(0);
231 }
232
233 }
234
235
236 void LyX::init(bool gui)
237 {
238         // Install the signal handlers
239         signal(SIGHUP, error_handler);
240         signal(SIGFPE, error_handler);
241         signal(SIGSEGV, error_handler);
242         signal(SIGINT, error_handler);
243         signal(SIGTERM, error_handler);
244
245         //
246         // Determine path of binary
247         //
248
249         string binpath = os::binpath();
250         string binname = os::binname();
251         string fullbinname = MakeAbsPath(binname, binpath);
252
253         if (binpath.empty()) {
254                 lyxerr << _("Warning: could not determine path of binary.")
255                        << "\n"
256                        << _("If you have problems, try starting LyX with an absolute path.")
257                        << endl;
258         }
259         lyxerr[Debug::INIT] << "Name of binary: " << binname << endl;
260         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
261
262         //
263         // Determine system directory.
264         //
265
266         // Directories are searched in this order:
267         // 1) -sysdir command line parameter
268         // 2) LYX_DIR_13x environment variable
269         // 3) Maybe <path of binary>/TOP_SRCDIR/lib
270         // 4) <path of binary>/../share/<name of binary>/
271         // 4a) repeat 4 after following the Symlink if <path of
272         //     binary> is a symbolic link.
273         // 5) hardcoded lyx_dir
274         // The directory is checked for the presence of the file
275         // "chkconfig.ltx", and if that is present, the directory
276         // is accepted as the system directory.
277         // If no chkconfig.ltx file is found, a warning is given,
278         // and the hardcoded lyx_dir is used.
279
280         // If we had a command line switch, system_lyxdir is already set
281         string searchpath;
282         if (!system_lyxdir.empty())
283                 searchpath= MakeAbsPath(system_lyxdir) + ';';
284
285         // LYX_DIR_13x environment variable
286         string const lyxdir = GetEnvPath("LYX_DIR_13x");
287
288         if (!lyxdir.empty()) {
289                 lyxerr[Debug::INIT] << "LYX_DIR_13x: " << lyxdir << endl;
290                 searchpath += lyxdir + ';';
291         }
292
293         string fullbinpath = binpath;
294         FileInfo file(fullbinname, true);
295         if (file.isLink()) {
296                 lyxerr[Debug::INIT] << "binary is a link" << endl;
297                 string link;
298                 if (LyXReadLink(fullbinname, link)) {
299                         // Path of binary/../share/name of binary/
300                         searchpath += NormalizePath(AddPath(binpath,
301                                                             "../share/")
302                                                     + OnlyFilename(binname));
303                         searchpath += ';';
304                         fullbinpath = link;
305                         binpath = MakeAbsPath(OnlyPath(fullbinpath));
306                 }
307         }
308
309         bool followlink;
310         do {
311                 // Path of binary/../share/name of binary/
312                 searchpath += NormalizePath(AddPath(binpath, "../share/") +
313                       OnlyFilename(binname)) + ';';
314
315                 // Follow Symlinks
316                 FileInfo file(fullbinpath, true);
317                 followlink = file.isLink();
318                 if (followlink) {
319                         lyxerr << " directory " << fullbinpath
320                                << " is a link" << endl;
321                         string link;
322                         if (LyXReadLink(fullbinpath, link)) {
323                                 fullbinpath = link;
324                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
325                         }
326                         else {
327                                 followlink = false;
328                         }
329                 }
330         } while (followlink);
331
332         // <path of binary>/TOP_SRCDIR/lib
333         build_lyxdir = MakeAbsPath("../lib", binpath);
334         if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
335                 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
336                                           binpath) + ';';
337                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
338                         "place... yes" << endl;
339         } else {
340                 lyxerr[Debug::INIT]
341                         << "Checking whether LyX is run in place... no"
342                         << endl;
343                 build_lyxdir.erase();
344         }
345
346         // Hardcoded dir
347         searchpath += LYX_DIR;
348
349         // If debugging, show complete search path
350         lyxerr[Debug::INIT] << "System directory search path: "
351                             << searchpath << endl;
352
353         string const filename = "chkconfig.ltx";
354         string const temp = FileOpenSearch(searchpath, filename, string());
355         system_lyxdir = OnlyPath(temp);
356
357         // Reduce "path/../path" stuff out of system directory
358         system_lyxdir = NormalizePath(system_lyxdir);
359
360         bool path_shown = false;
361
362         // Warn if environment variable is set, but unusable
363         if (!lyxdir.empty()) {
364                 if (system_lyxdir != NormalizePath(lyxdir)) {
365                         lyxerr <<_("LYX_DIR_13x environment variable no good.")
366                                << '\n'
367                                << _("System directory set to: ")
368                                << system_lyxdir << endl;
369                         path_shown = true;
370                 }
371         }
372
373         // Warn the user if we couldn't find "chkconfig.ltx"
374         if (system_lyxdir == "./") {
375                 lyxerr <<_("LyX Warning! Couldn't determine system directory. ")
376                        <<_("Try the '-sysdir' command line parameter or ")
377                        <<_("set the environment variable LYX_DIR_13x to the "
378                            "LyX system directory ")
379                        << _("containing the file `chkconfig.ltx'.") << endl;
380                 if (!path_shown) {
381                         FileInfo fi(LYX_DIR);
382                         if (!fi.exist()) {
383                                 lyxerr << "Couldn't even find the default LYX_DIR." << endl
384                                         << "Giving up." << endl;
385                                 exit(1);
386                         }
387                         lyxerr << _("Using built-in default ")
388                                << LYX_DIR << _(" but expect problems.")
389                                << endl;
390                 } else {
391                         lyxerr << _("Expect problems.") << endl;
392                 }
393                 system_lyxdir = LYX_DIR;
394                 path_shown = true;
395         }
396         // Report the system directory if debugging is on
397         if (!path_shown)
398                 lyxerr[Debug::INIT] << "System directory: '"
399                                     << system_lyxdir << '\'' << endl;
400
401         //
402         // Determine user lyx-dir
403         //
404
405         // Directories are searched in this order:
406         // 1) -userdir command line parameter
407         // 2) LYX_USERDIR_13x environment variable
408         // 3) $HOME/.<name of binary>
409
410         // If we had a command line switch, user_lyxdir is already set
411         bool explicit_userdir = true;
412         if (user_lyxdir.empty()) {
413
414                 // LYX_USERDIR_13x environment variable
415                 user_lyxdir = GetEnvPath("LYX_USERDIR_13x");
416
417                 // default behaviour
418                 if (user_lyxdir.empty())
419                         user_lyxdir = AddPath(GetEnvPath("HOME"),
420                                                         string(".") + PACKAGE);
421                         explicit_userdir = false;
422         }
423
424         lyxerr[Debug::INIT] << "User LyX directory: '"
425                             <<  user_lyxdir << '\'' << endl;
426
427         // Check that user LyX directory is ok. We don't do that if
428         // running in batch mode.
429         if (gui) {
430                 queryUserLyXDir(explicit_userdir);
431         } else {
432                 first_start = false;
433         }
434
435         //
436         // Shine up lyxrc defaults
437         //
438
439         // Default template path: system_dir/templates
440         if (lyxrc.template_path.empty()) {
441                 lyxrc.template_path = AddPath(system_lyxdir, "templates");
442         }
443
444         // Default lastfiles file: $HOME/.lyx/lastfiles
445         if (lyxrc.lastfiles.empty()) {
446                 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
447         }
448
449         // Disable gui when either lyxrc or easyparse says so
450         if (!gui)
451                 lyxrc.use_gui = false;
452
453         // Calculate screen dpi as average of x-DPI and y-DPI:
454         if (lyxrc.use_gui) {
455                 lyxrc.dpi = GUIRunTime::getScreenDPI();
456                 lyxerr[Debug::INIT] << "DPI setting detected to be "
457                                                 << lyxrc.dpi + 0.5 << endl;
458         } else {
459                 lyxrc.dpi = 1; // I hope this is safe
460         }
461
462         //
463         // Read configuration files
464         //
465
466         readRcFile("lyxrc.defaults");
467         system_lyxrc = lyxrc;
468         system_formats = formats;
469         system_converters = converters;
470         system_lcolor = lcolor;
471
472         // If there is a preferences file we read that instead
473         // of the old lyxrc file.
474         if (!readRcFile("preferences"))
475             readRcFile("lyxrc");
476
477         // Read encodings
478         readEncodingsFile("encodings");
479         // Read languages
480         readLanguagesFile("languages");
481
482         // Load the layouts
483         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
484         LyXSetStyle();
485
486         // Ensure that we have really read a bind file, so that LyX is
487         // usable.
488         lyxrc.readBindFileIfNeeded();
489
490         // Read menus
491         readUIFile(lyxrc.ui_file);
492
493         // Bind the X dead keys to the corresponding LyX functions if
494         // necessary.
495         if (lyxrc.override_x_deadkeys)
496                 deadKeyBindings(toplevel_keymap.get());
497
498         if (lyxerr.debugging(Debug::LYXRC)) {
499                 lyxrc.print();
500         }
501
502         // Create temp directory
503         os::setTmpDir(CreateLyXTmpDir(lyxrc.tempdir_path));
504         system_tempdir = os::getTmpDir();
505         if (lyxerr.debugging(Debug::INIT)) {
506                 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
507         }
508
509         // load the lastfiles mini-database
510         lyxerr[Debug::INIT] << "Reading lastfiles `"
511                             << lyxrc.lastfiles << "'..." << endl;
512         lastfiles.reset(new LastFiles(lyxrc.lastfiles,
513                                       lyxrc.check_lastfiles,
514                                       lyxrc.num_lastfiles));
515
516         // start up the lyxserver. (is this a bit early?) (Lgb)
517         // 0.12 this will be way to early, we need the GUI to be initialized
518         // first, so move it for now.
519         // lyxserver = new LyXServer;
520 }
521
522
523 // These are the default bindings known to LyX
524 void LyX::defaultKeyBindings(kb_keymap  * kbmap)
525 {
526         kbmap->bind("Right", LFUN_RIGHT);
527         kbmap->bind("Left", LFUN_LEFT);
528         kbmap->bind("Up", LFUN_UP);
529         kbmap->bind("Down", LFUN_DOWN);
530
531         kbmap->bind("Tab", LFUN_TAB);
532         kbmap->bind("ISO_Left_Tab", LFUN_TAB); // jbl 2001-23-02
533
534         kbmap->bind("Home", LFUN_HOME);
535         kbmap->bind("End", LFUN_END);
536         kbmap->bind("Prior", LFUN_PRIOR);
537         kbmap->bind("Next", LFUN_NEXT);
538
539         kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
540         //kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
541
542         kbmap->bind("Delete", LFUN_DELETE);
543         kbmap->bind("BackSpace", LFUN_BACKSPACE);
544
545         // sub- and superscript -MV
546         kbmap->bind("~S-underscore", LFUN_SUBSCRIPT);
547         kbmap->bind("~S-asciicircum", LFUN_SUPERSCRIPT);
548
549         // kbmap->bindings to enable the use of the numeric keypad
550         // e.g. Num Lock set
551         //kbmap->bind("KP_0", LFUN_SELFINSERT);
552         //kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
553         kbmap->bind("KP_Enter", LFUN_BREAKPARAGRAPH);
554         //kbmap->bind("KP_1", LFUN_SELFINSERT);
555         //kbmap->bind("KP_2", LFUN_SELFINSERT);
556         //kbmap->bind("KP_3", LFUN_SELFINSERT);
557         //kbmap->bind("KP_4", LFUN_SELFINSERT);
558         //kbmap->bind("KP_5", LFUN_SELFINSERT);
559         //kbmap->bind("KP_6", LFUN_SELFINSERT);
560         //kbmap->bind("KP_Add", LFUN_SELFINSERT);
561         //kbmap->bind("KP_7", LFUN_SELFINSERT);
562         //kbmap->bind("KP_8", LFUN_SELFINSERT);
563         //kbmap->bind("KP_9", LFUN_SELFINSERT);
564         //kbmap->bind("KP_Divide", LFUN_SELFINSERT);
565         //kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
566         //kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
567         kbmap->bind("KP_Right", LFUN_RIGHT);
568         kbmap->bind("KP_Left", LFUN_LEFT);
569         kbmap->bind("KP_Up", LFUN_UP);
570         kbmap->bind("KP_Down", LFUN_DOWN);
571         kbmap->bind("KP_Home", LFUN_HOME);
572         kbmap->bind("KP_End", LFUN_END);
573         kbmap->bind("KP_Prior", LFUN_PRIOR);
574         kbmap->bind("KP_Next", LFUN_NEXT);
575
576         kbmap->bind("C-Tab", LFUN_TABINSERT);  // ale970515
577         kbmap->bind("S-Tab", LFUN_SHIFT_TAB);  // jug20000522
578         kbmap->bind("S-ISO_Left_Tab", LFUN_SHIFT_TAB); // jbl 2001-23-02
579 }
580
581
582 void LyX::emergencyCleanup()
583 {
584         // what to do about tmpfiles is non-obvious. we would
585         // like to delete any we find, but our lyxdir might
586         // contain documents etc. which might be helpful on
587         // a crash
588
589         bufferlist.emergencyWriteAll();
590         if (lyxserver)
591                 lyxserver->emergencyCleanup();
592 }
593
594
595 // LyX can optionally take over the handling of deadkeys
596 void LyX::deadKeyBindings(kb_keymap * kbmap)
597 {
598         // bindKeyings for transparent handling of deadkeys
599         // The keysyms are gotten from XFree86 X11R6
600         kbmap->bind("~C-~S-~M-dead_acute", LFUN_ACUTE);
601         kbmap->bind("~C-~S-~M-dead_breve", LFUN_BREVE);
602         kbmap->bind("~C-~S-~M-dead_caron", LFUN_CARON);
603         kbmap->bind("~C-~S-~M-dead_cedilla", LFUN_CEDILLA);
604         kbmap->bind("~C-~S-~M-dead_abovering", LFUN_CIRCLE);
605         kbmap->bind("~C-~S-~M-dead_circumflex", LFUN_CIRCUMFLEX);
606         kbmap->bind("~C-~S-~M-dead_abovedot", LFUN_DOT);
607         kbmap->bind("~C-~S-~M-dead_grave", LFUN_GRAVE);
608         kbmap->bind("~C-~S-~M-dead_doubleacute", LFUN_HUNG_UMLAUT);
609         kbmap->bind("~C-~S-~M-dead_macron", LFUN_MACRON);
610         // nothing with this name
611         // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
612         kbmap->bind("~C-~S-~M-dead_tilde", LFUN_TILDE);
613         kbmap->bind("~C-~S-~M-dead_diaeresis", LFUN_UMLAUT);
614         // nothing with this name either...
615         //kbmap->bind("~C-~S-~M-dead_underbar", LFUN_UNDERBAR);
616         kbmap->bind("~C-~S-~M-dead_belowdot", LFUN_UNDERDOT);
617         kbmap->bind("~C-~S-~M-dead_tie", LFUN_TIE);
618         kbmap->bind("~C-~S-~M-dead_ogonek", LFUN_OGONEK);
619 }
620
621
622 // This one is not allowed to use anything on the main form, since that
623 // one does not exist yet. (Asger)
624 void LyX::queryUserLyXDir(bool explicit_userdir)
625 {
626         // Does user directory exist?
627         FileInfo fileInfo(user_lyxdir);
628         if (fileInfo.isOK() && fileInfo.isDir()) {
629                 first_start = false;
630                 return;
631         } else {
632                 first_start = !explicit_userdir;
633         }
634
635         // If the user specified explicitely a directory, ask whether
636         // to create it (otherwise, always create it)
637         if (explicit_userdir &&
638             !Alert::askQuestion(_("You have specified an invalid LyX directory."),
639                          _("It is needed to keep your own configuration."),
640                          _("Should I try to set it up for you (recommended)?"))) {
641                 lyxerr << _("Running without personal LyX directory.") << endl;
642                 // No, let's use $HOME instead.
643                 user_lyxdir = GetEnvPath("HOME");
644                 return;
645         }
646
647         // Tell the user what is going on
648         lyxerr << _("LyX: Creating directory ") << user_lyxdir
649                << _(" and running configure...") << endl;
650
651         // Create directory structure
652         if (!createDirectory(user_lyxdir, 0755)) {
653                 // Failed, let's use $HOME instead.
654                 user_lyxdir = GetEnvPath("HOME");
655                 lyxerr << _("Failed. Will use ") << user_lyxdir
656                        << _(" instead.") << endl;
657                 return;
658         }
659
660         // Run configure in user lyx directory
661         Path p(user_lyxdir);
662         ::system(AddName(system_lyxdir, "configure").c_str());
663         lyxerr << "LyX: " << _("Done!") << endl;
664 }
665
666
667 // Read the rc file `name'
668 bool LyX::readRcFile(string const & name)
669 {
670         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
671
672         string const lyxrc_path = LibFileSearch(string(), name);
673         if (!lyxrc_path.empty()) {
674                 lyxerr[Debug::INIT] << "Found " << name
675                                     << " in " << lyxrc_path << endl;
676                 if (lyxrc.read(lyxrc_path) < 0) {
677                         Alert::alert(_("LyX Warning!"),
678                                    _("Error while reading ") + lyxrc_path + ".",
679                                    _("Using built-in defaults."));
680                         return false;
681                 }
682                 return true;
683         } else {
684                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
685         }
686
687         return false;
688 }
689
690
691 // Read the ui file `name'
692 void LyX::readUIFile(string const & name)
693 {
694         enum Uitags {
695                 ui_menuset = 1,
696                 ui_toolbar,
697                 ui_last
698         };
699
700         struct keyword_item uitags[ui_last-1] = {
701                 { "menuset", ui_menuset },
702                 { "toolbar", ui_toolbar }
703         };
704
705         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
706
707         string const ui_path = LibFileSearch("ui", name, "ui");
708
709         if (ui_path.empty()) {
710                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
711                 menubackend.defaults();
712                 return;
713         }
714
715         lyxerr[Debug::INIT] << "Found " << name
716                             << " in " << ui_path << endl;
717         LyXLex lex(uitags, ui_last - 1);
718         lex.setFile(ui_path);
719         if (!lex.isOK()) {
720                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
721                        << endl;
722         }
723
724         if (lyxerr.debugging(Debug::PARSER))
725                 lex.printTable(lyxerr);
726
727         while (lex.isOK()) {
728                 switch (lex.lex()) {
729                 case ui_menuset:
730                         menubackend.read(lex);
731                         break;
732
733                 case ui_toolbar:
734                         toolbardefaults.read(lex);
735                         break;
736
737                 default:
738                         if (!strip(lex.getString()).empty())
739                                 lex.printError("LyX::ReadUIFile: "
740                                                "Unknown menu tag: `$$Token'");
741                         break;
742                 }
743         }
744 }
745
746
747 // Read the languages file `name'
748 void LyX::readLanguagesFile(string const & name)
749 {
750         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
751
752         string const lang_path = LibFileSearch(string(), name);
753         if (lang_path.empty()) {
754                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
755                 languages.setDefaults();
756                 return;
757         }
758         languages.read(lang_path);
759 }
760
761
762 // Read the encodings file `name'
763 void LyX::readEncodingsFile(string const & name)
764 {
765         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
766
767         string const enc_path = LibFileSearch(string(), name);
768         if (enc_path.empty()) {
769                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
770                 return;
771         }
772         encodings.read(enc_path);
773 }
774
775
776 namespace {
777
778 // Set debugging level and report result to user
779 void setDebuggingLevel(string const & dbgLevel)
780 {
781         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
782         lyxerr.level(Debug::value(dbgLevel));
783         Debug::showLevel(lyxerr, lyxerr.level());
784 }
785
786
787 // Give command line help
788 void commandLineHelp()
789 {
790         lyxerr <<
791                 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
792                   "Command line switches (case sensitive):\n"
793                   "\t-help              summarize LyX usage\n"
794                   "\t-userdir dir       try to set user directory to dir\n"
795                   "\t-sysdir dir        try to set system directory to dir\n"
796                   "\t-geometry WxH+X+Y  set geometry of the main window\n"
797                   "\t-dbg feature[,feature]...\n"
798                   "                  select the features to debug.\n"
799                   "                  Type `lyx -dbg' to see the list of features\n"
800                   "\t-x [--execute] command\n"
801                   "                  where command is a lyx command.\n"
802                   "\t-e [--export] fmt\n"
803                   "                  where fmt is the export format of choice.\n"
804                   "\t-i [--import] fmt file.xxx\n"
805                   "                  where fmt is the import format of choice\n"
806                   "                  and file.xxx is the file to be imported.\n"
807                   "\t-version        summarize version and build info\n"
808                   "Check the LyX man page for more details.") << endl;
809 }
810
811 // Give command line version information
812 void commandLineVersionInfo()
813 {
814         lyxerr << "LyX " << lyx_version
815                << " of " << lyx_release_date << endl;
816         lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
817
818         lyxerr << lyx_version_info << endl;
819 }
820
821
822 } // namespace anon
823
824
825 bool LyX::easyParse(int * argc, char * argv[])
826 {
827         bool gui = true;
828         int removeargs = 0; // used when options are read
829         for (int i = 1; i < *argc; ++i) {
830                 string arg = argv[i];
831
832                 // Check for -dbg int
833                 if (arg == "-dbg") {
834                         if (i + 1 < *argc) {
835                                 setDebuggingLevel(argv[i + 1]);
836                                 removeargs = 2;
837                         } else {
838                                 lyxerr << _("List of supported debug flags:")
839                                        << endl;
840                                 Debug::showTags(lyxerr);
841                                 exit(1);
842                         }
843                 }
844                 // Check for "-sysdir"
845                 else if (arg == "-sysdir") {
846                         if (i + 1 < *argc) {
847                                 system_lyxdir = argv[i + 1];
848                                 removeargs = 2;
849                         } else {
850                                 lyxerr << _("Missing directory for -sysdir switch!")
851                                        << endl;
852                                 exit(1);
853                         }
854                 }
855                 // Check for "-userdir"
856                 else if (arg == "-userdir") {
857                         if (i + 1 < *argc) {
858                                 user_lyxdir = argv[i + 1];
859                                 removeargs = 2;
860                         } else {
861                                 lyxerr << _("Missing directory for -userdir switch!")
862                                        << endl;
863                                 exit(1);
864                         }
865                 }
866                 // Check for --help or -help
867                 else if (arg == "--help" || arg == "-help") {
868                         commandLineHelp();
869                         exit(0);
870                 }
871                 // Check for --version or -version
872                 else if (arg == "--version" || arg == "-version") {
873                         commandLineVersionInfo();
874                         exit(0);
875                 }
876                 // FIXME: why is this commented out ? 
877                 // Check for "-nw": No XWindows as for emacs this should
878                 // give a LyX that could be used in a terminal window.
879                 //else if (arg == "-nw") {
880                 //      gui = false;
881                 //}
882
883                 // Check for "-x": Execute commands
884                 else if (arg == "-x" || arg == "--execute") {
885                         if (i + 1 < *argc) {
886                                 batch_command = string(argv[i + 1]);
887                                 removeargs = 2;
888                         }
889                         else
890                                 lyxerr << _("Missing command string after  -x switch!") << endl;
891
892                         // Argh. Setting gui to false segfaults..
893                         // FIXME: when ? how ? 
894                         // gui = false;
895                 }
896
897                 else if (arg == "-e" || arg == "--export") {
898                         if (i + 1 < *argc) {
899                                 string type(argv[i+1]);
900                                 removeargs = 2;
901                                 batch_command = "buffer-export " + type;
902                                 gui = false;
903                         } else {
904                                 lyxerr << _("Missing file type [eg latex, "
905                                             "ps...] after ")
906                                        << arg << _(" switch!") << endl;
907                                 exit(1);
908                         }
909                 }
910                 else if (arg == "-i" || arg == "--import") {
911                         if (i + 1 < *argc) {
912                                 if (!argv[i+2]) {
913                                         lyxerr << _("Missing filename for --import") << endl;
914                                         exit(1);
915                                 }
916  
917                                 string const file(argv[i+2]);
918                                 string const type(argv[i+1]);
919                                 removeargs = 3;
920  
921                                 batch_command = "buffer-import " + type + " " + file;
922                                 lyxerr << "batch_command: "
923                                        << batch_command << endl;
924
925                         } else {
926                                 lyxerr << _("Missing type [eg latex, "
927                                             "ps...] after ")
928                                        << arg << _(" switch!") << endl;
929                                 exit(1);
930                         }
931                 }
932
933                 if (removeargs > 0) {
934                         // Now, remove used arguments by shifting
935                         // the following ones removeargs places down.
936                         (*argc) -= removeargs;
937                         for (int j = i; j < (*argc); ++j)
938                                 argv[j] = argv[j + removeargs];
939                         --i; // After shift, check this number again.
940                         removeargs = 0;
941                 }
942
943         }
944
945         return gui;
946 }