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