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