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