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