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