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