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