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