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