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