]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
remove more forms.h cruft
[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
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 const 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                         FileInfo fi(LYX_DIR);
316                         if (!fi.exist()) {
317                                 lyxerr << "Couldn't even find the default LYX_DIR." << endl
318                                         << "Giving up." << endl;
319                                 exit(1);
320                         }
321                         lyxerr << _("Using built-in default ") 
322                                << LYX_DIR << _(" but expect problems.")
323                                << endl;
324                 } else {
325                         lyxerr << _("Expect problems.") << endl;
326                 }
327                 system_lyxdir = LYX_DIR;
328                 path_shown = true;
329         }
330
331         // Report the system directory if debugging is on
332         if (!path_shown)
333                 lyxerr[Debug::INIT] << "System directory: '"
334                                     << system_lyxdir << '\'' << endl; 
335
336         //
337         // Determine user lyx-dir
338         //
339         
340         // Directories are searched in this order:
341         // 1) -userdir command line parameter
342         // 2) LYX_USERDIR_11x environment variable
343         // 3) $HOME/.<name of binary>
344
345         // If we had a command line switch, user_lyxdir is already set
346         bool explicit_userdir = true;
347         if (user_lyxdir.empty()) {
348
349                 // LYX_USERDIR_11x environment variable
350                 user_lyxdir = GetEnvPath("LYX_USERDIR_11x");
351
352                 // default behaviour
353                 if (user_lyxdir.empty())
354                         user_lyxdir = AddPath(GetEnvPath("HOME"),
355                                                         string(".") + PACKAGE);
356                         explicit_userdir = false;
357         }
358
359         lyxerr[Debug::INIT] << "User LyX directory: '" 
360                             <<  user_lyxdir << '\'' << endl;
361
362         // Check that user LyX directory is ok. We don't do that if
363         // running in batch mode.
364         if (gui)
365                 queryUserLyXDir(explicit_userdir);
366         else
367                 first_start = false;
368
369         //
370         // Shine up lyxrc defaults
371         //
372
373         // Default template path: system_dir/templates
374         if (lyxrc.template_path.empty()){
375                 lyxrc.template_path = AddPath(system_lyxdir, "templates");
376         }
377    
378         // Default lastfiles file: $HOME/.lyx/lastfiles
379         if (lyxrc.lastfiles.empty()){
380                 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
381         }
382
383         // Disable gui when either lyxrc or easyparse says so
384         if (!gui)
385                 lyxrc.use_gui = false;
386  
387         // Calculate screen dpi as average of x-DPI and y-DPI:
388         if (lyxrc.use_gui) {
389                 lyxrc.dpi = getScreenDPI();
390                 lyxerr[Debug::INIT] << "DPI setting detected to be "
391                                                 << lyxrc.dpi + 0.5 << endl;
392         } else {
393                 lyxrc.dpi = 1; // I hope this is safe
394         }
395
396         //
397         // Read configuration files
398         //
399
400         readRcFile("lyxrc.defaults");
401         system_lyxrc = lyxrc;
402         system_formats = formats;
403         system_converters = converters;
404         system_lcolor = lcolor;
405
406         // If there is a preferences file we read that instead
407         // of the old lyxrc file.
408         if (!readRcFile("preferences"))
409             readRcFile("lyxrc");
410
411         // Read encodings
412         readEncodingsFile("encodings");
413         // Read languages
414         readLanguagesFile("languages");
415
416         // Load the layouts
417         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
418         LyXSetStyle();
419
420         // Ensure that we have really read a bind file, so that LyX is
421         // usable.
422         lyxrc.readBindFileIfNeeded();
423
424         // Read menus
425         readUIFile(lyxrc.ui_file);
426
427         // Bind the X dead keys to the corresponding LyX functions if
428         // necessary. 
429         if (lyxrc.override_x_deadkeys)
430                 deadKeyBindings(toplevel_keymap.get());
431
432         if (lyxerr.debugging(Debug::LYXRC)) {
433                 lyxrc.print();
434         }
435
436         // Create temp directory        
437         os::setTmpDir(CreateLyXTmpDir(lyxrc.tempdir_path));
438         system_tempdir = os::getTmpDir();
439         if (lyxerr.debugging(Debug::INIT)) {
440                 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
441         }
442
443         // load the lastfiles mini-database
444         lyxerr[Debug::INIT] << "Reading lastfiles `"
445                             << lyxrc.lastfiles << "'..." << endl; 
446         lastfiles = new LastFiles(lyxrc.lastfiles, 
447                                   lyxrc.check_lastfiles,
448                                   lyxrc.num_lastfiles);
449
450         // start up the lyxserver. (is this a bit early?) (Lgb)
451         // 0.12 this will be way to early, we need the GUI to be initialized
452         // first, so move it for now.
453         // lyxserver = new LyXServer;
454 }
455
456
457 // These are the default bindings known to LyX
458 void LyX::defaultKeyBindings(kb_keymap  * kbmap)
459 {
460         kbmap->bind("Right", LFUN_RIGHT);
461         kbmap->bind("Left", LFUN_LEFT);
462         kbmap->bind("Up", LFUN_UP);
463         kbmap->bind("Down", LFUN_DOWN);
464         
465         kbmap->bind("Tab", LFUN_TAB);
466         kbmap->bind("ISO_Left_Tab", LFUN_TAB); // jbl 2001-23-02
467         
468         kbmap->bind("Home", LFUN_HOME);
469         kbmap->bind("End", LFUN_END);
470         kbmap->bind("Prior", LFUN_PRIOR);
471         kbmap->bind("Next", LFUN_NEXT);
472         
473         kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
474         //kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
475         
476         kbmap->bind("Delete", LFUN_DELETE);
477         kbmap->bind("BackSpace", LFUN_BACKSPACE);
478         
479         // kbmap->bindings to enable the use of the numeric keypad
480         // e.g. Num Lock set
481         //kbmap->bind("KP_0", LFUN_SELFINSERT);
482         //kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
483         kbmap->bind("KP_Enter", LFUN_BREAKPARAGRAPH);
484         //kbmap->bind("KP_1", LFUN_SELFINSERT);
485         //kbmap->bind("KP_2", LFUN_SELFINSERT);
486         //kbmap->bind("KP_3", LFUN_SELFINSERT);
487         //kbmap->bind("KP_4", LFUN_SELFINSERT);
488         //kbmap->bind("KP_5", LFUN_SELFINSERT);
489         //kbmap->bind("KP_6", LFUN_SELFINSERT);
490         //kbmap->bind("KP_Add", LFUN_SELFINSERT);
491         //kbmap->bind("KP_7", LFUN_SELFINSERT);
492         //kbmap->bind("KP_8", LFUN_SELFINSERT);
493         //kbmap->bind("KP_9", LFUN_SELFINSERT);
494         //kbmap->bind("KP_Divide", LFUN_SELFINSERT);
495         //kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
496         //kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
497         kbmap->bind("KP_Right", LFUN_RIGHT);
498         kbmap->bind("KP_Left", LFUN_LEFT);
499         kbmap->bind("KP_Up", LFUN_UP);
500         kbmap->bind("KP_Down", LFUN_DOWN);
501         kbmap->bind("KP_Home", LFUN_HOME);
502         kbmap->bind("KP_End", LFUN_END);
503         kbmap->bind("KP_Prior", LFUN_PRIOR);
504         kbmap->bind("KP_Next", LFUN_NEXT);
505         
506         kbmap->bind("C-Tab", LFUN_TABINSERT);  // ale970515
507         kbmap->bind("S-Tab", LFUN_SHIFT_TAB);  // jug20000522
508         kbmap->bind("S-ISO_Left_Tab", LFUN_SHIFT_TAB); // jbl 2001-23-02
509 }
510
511
512 // LyX can optionally take over the handling of deadkeys
513 void LyX::deadKeyBindings(kb_keymap * kbmap)
514 {
515         // bindKeyings for transparent handling of deadkeys
516         // The keysyms are gotten from XFree86 X11R6
517         kbmap->bind("~C-~S-~M-dead_acute", LFUN_ACUTE);
518         kbmap->bind("~C-~S-~M-dead_breve", LFUN_BREVE);
519         kbmap->bind("~C-~S-~M-dead_caron", LFUN_CARON);
520         kbmap->bind("~C-~S-~M-dead_cedilla", LFUN_CEDILLA);
521         kbmap->bind("~C-~S-~M-dead_abovering", LFUN_CIRCLE);
522         kbmap->bind("~C-~S-~M-dead_circumflex", LFUN_CIRCUMFLEX);
523         kbmap->bind("~C-~S-~M-dead_abovedot", LFUN_DOT);
524         kbmap->bind("~C-~S-~M-dead_grave", LFUN_GRAVE);
525         kbmap->bind("~C-~S-~M-dead_doubleacute", LFUN_HUNG_UMLAUT);
526         kbmap->bind("~C-~S-~M-dead_macron", LFUN_MACRON);
527         // nothing with this name
528         // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
529         kbmap->bind("~C-~S-~M-dead_tilde", LFUN_TILDE);
530         kbmap->bind("~C-~S-~M-dead_diaeresis", LFUN_UMLAUT);
531         // nothing with this name either...
532         //kbmap->bind("~C-~S-~M-dead_underbar", LFUN_UNDERBAR);
533         kbmap->bind("~C-~S-~M-dead_belowdot", LFUN_UNDERDOT);
534         kbmap->bind("~C-~S-~M-dead_tie", LFUN_TIE);
535         kbmap->bind("~C-~S-~M-dead_ogonek", LFUN_OGONEK);
536 }
537
538
539 // This one is not allowed to use anything on the main form, since that
540 // one does not exist yet. (Asger)
541 void LyX::queryUserLyXDir(bool explicit_userdir)
542 {
543         // Does user directory exist?
544         FileInfo fileInfo(user_lyxdir);
545         if (fileInfo.isOK() && fileInfo.isDir()) {
546                 first_start = false;
547                 return;
548         } else {
549                 first_start = true;
550         }
551         
552         // Nope
553         // Different wording if the user specifically requested a directory
554         if (!AskQuestion( explicit_userdir
555                          ? _("You have specified an invalid LyX directory.")
556                          : _("You don't have a personal LyX directory.") ,
557
558                          _("It is needed to keep your own configuration."),
559                          _("Should I try to set it up for you (recommended)?"))) {
560                 lyxerr << _("Running without personal LyX directory.") << endl;
561                 // No, let's use $HOME instead.
562                 user_lyxdir = GetEnvPath("HOME");
563                 return;
564         }
565
566         // Tell the user what is going on
567         lyxerr << _("LyX: Creating directory ") << user_lyxdir
568                << _(" and running configure...") << endl;
569
570         // Create directory structure
571         if (!createDirectory(user_lyxdir, 0755)) {
572                 // Failed, let's use $HOME instead.
573                 user_lyxdir = GetEnvPath("HOME");
574                 lyxerr << _("Failed. Will use ") << user_lyxdir
575                        << _(" instead.") << endl;
576                 return;
577         }
578
579         // Run configure in user lyx directory
580         Path p(user_lyxdir);
581         ::system(AddName(system_lyxdir, "configure").c_str());
582         lyxerr << "LyX: " << _("Done!") << endl;
583 }
584
585
586 // Read the rc file `name'
587 bool LyX::readRcFile(string const & name)
588 {
589         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
590         
591         string lyxrc_path = LibFileSearch(string(), name);
592         if (!lyxrc_path.empty()){
593                 lyxerr[Debug::INIT] << "Found " << name
594                                     << " in " << lyxrc_path << endl;
595                 if (lyxrc.read(lyxrc_path) < 0) { 
596                         WriteAlert(_("LyX Warning!"), 
597                                    _("Error while reading ") + lyxrc_path + ".",
598                                    _("Using built-in defaults."));
599                         return false;
600                 }
601                 return true;
602         } else
603                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
604         return false;
605 }
606
607
608 // Read the ui file `name'
609 void LyX::readUIFile(string const & name)
610 {
611         enum Uitags {
612                 ui_menuset = 1,
613                 ui_toolbar,
614                 ui_last
615         };
616
617         struct keyword_item uitags[ui_last-1] = {
618                 { "menuset", ui_menuset },
619                 { "toolbar", ui_toolbar }
620         };
621
622         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
623         
624         string ui_path = LibFileSearch("ui", name, "ui");
625
626         if (ui_path.empty()) {
627                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
628                 menubackend.defaults();
629                 return;
630         }
631         
632         lyxerr[Debug::INIT] << "Found " << name
633                             << " in " << ui_path << endl;
634         LyXLex lex(uitags, ui_last - 1);
635         lex.setFile(ui_path);
636         if (!lex.IsOK()) {
637                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
638                        << endl;
639         }
640         
641         if (lyxerr.debugging(Debug::PARSER))
642                 lex.printTable(lyxerr);
643
644         while (lex.IsOK()) {
645                 switch (lex.lex()) {
646                 case ui_menuset: 
647                         menubackend.read(lex);
648                         break;
649
650                 case ui_toolbar:
651                         toolbardefaults.read(lex);
652                         break;
653
654                 default:
655                         if(!strip(lex.GetString()).empty())
656                                 lex.printError("LyX::ReadUIFile: "
657                                                "Unknown menu tag: `$$Token'");
658                         break;
659                 }
660         }
661 }
662
663
664 // Read the languages file `name'
665 void LyX::readLanguagesFile(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 namespace {
694
695 // Set debugging level and report result to user
696 void setDebuggingLevel(string const & dbgLevel)
697 {
698         lyxerr << _("Setting debug level to ") <<  dbgLevel << endl;
699         lyxerr.level(Debug::value(dbgLevel));
700         Debug::showLevel(lyxerr, lyxerr.level());
701 }
702
703
704 // Give command line help
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 } // namespace anon
729
730
731 bool LyX::easyParse(int * argc, char * argv[])
732 {
733         bool gui = true;
734         int removeargs = 0; // used when options are read
735         for (int i = 1; i < *argc; ++i) {
736                 string arg = argv[i];
737
738                 // Check for -dbg int
739                 if (arg == "-dbg") {
740                         if (i + 1 < *argc) {
741                                 setDebuggingLevel(argv[i + 1]);
742                                 removeargs = 2;
743                         } else {
744                                 lyxerr << _("List of supported debug flags:")
745                                        << endl;
746                                 Debug::showTags(lyxerr);
747                                 exit(0);
748                         }
749                 } 
750                 // Check for "-sysdir"
751                 else if (arg == "-sysdir") {
752                         if (i + 1 < *argc) {
753                                 system_lyxdir = argv[i + 1];
754                                 removeargs = 2;
755                         } else {
756                                 lyxerr << _("Missing directory for -sysdir switch!") 
757                                        << endl;
758                                 exit(0);
759                         }
760                 }
761                 // Check for "-userdir"
762                 else if (arg == "-userdir") {
763                         if (i + 1 < *argc) {
764                                 user_lyxdir = argv[i + 1];
765                                 removeargs = 2;
766                         } else {
767                                 lyxerr << _("Missing directory for -userdir switch!")
768                                        << endl;
769                                 exit(0);
770                         }
771                 }
772                 // Check for --help or -help
773                 else if (arg == "--help" || arg == "-help") {
774                         commandLineHelp();
775                         exit(0);
776                 } 
777                 // Check for "-nw": No XWindows as for emacs this should
778                 // give a LyX that could be used in a terminal window.
779                 //else if (arg == "-nw") {
780                 //      gui = false;
781                 //}
782
783                 // Check for "-x": Execute commands
784                 else if (arg == "-x" || arg == "--execute") {
785                         if (i + 1 < *argc) {
786                                 batch_command = string(argv[i + 1]);
787                                 removeargs = 2;
788                         }
789                         else
790                                 lyxerr << _("Missing command string after  -x switch!") << endl;
791
792                         // Argh. Setting gui to false segfaults..
793                         //gui = false;
794                 }
795
796                 else if (arg == "-e" || arg == "--export") {
797                         if (i + 1 < *argc) {
798                                 string type(argv[i+1]);
799                                 removeargs = 2;
800                                 batch_command = "buffer-export " + type;
801                                 gui = false;
802                         } else
803                                 lyxerr << _("Missing file type [eg latex, "
804                                             "ps...] after ")
805                                        << arg << _(" switch!") << endl;
806                 }
807                 else if (arg == "-i" || arg == "--import") {
808                         if (i + 1 < *argc) {
809                                 string type(argv[i+1]);
810                                 string file(argv[i+2]);
811                                 removeargs = 3;
812         
813                                 batch_command = "buffer-import " + type + " " + file;
814                                 lyxerr << "batch_command: "
815                                        << batch_command << endl;
816
817                         } else
818                                 lyxerr << _("Missing type [eg latex, "
819                                             "ps...] after ")
820                                        << arg << _(" switch!") << endl;
821                 }
822
823                 if (removeargs > 0) {
824                         // Now, remove used arguments by shifting
825                         // the following ones removeargs places down.
826                         (*argc) -= removeargs;
827                         for (int j = i; j < (*argc); ++j)
828                                 argv[j] = argv[j + removeargs];
829                         --i; // After shift, check this number again.
830                         removeargs = 0;
831                 }
832
833         }
834
835         return gui;
836 }
837
838
839 extern "C"
840 void error_handler(int err_sig)
841 {
842         switch (err_sig) {
843         case SIGHUP:
844                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
845                 break;
846         case SIGINT:
847                 // no comments
848                 break;
849         case SIGFPE:
850                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
851                 break;
852         case SIGSEGV:
853                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
854                 lyxerr <<
855                         "Sorry, you have found a bug in LyX."
856                         " If possible, please read 'Known bugs'\n"
857                         "under the Help menu and then send us "
858                         "a full bug report. Thanks!" << endl;
859                 break;
860         case SIGTERM:
861                 // no comments
862                 break;
863         }
864    
865         // Deinstall the signal handlers
866         signal(SIGHUP, SIG_DFL);
867         signal(SIGINT, SIG_DFL);
868         signal(SIGFPE, SIG_DFL);
869         signal(SIGSEGV, SIG_DFL);
870         signal(SIGTERM, SIG_DFL);
871
872         bufferlist.emergencyWriteAll();
873
874         lyxerr << "Bye." << endl;
875         if (err_sig!= SIGHUP && 
876            (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
877                 lyx::abort();
878         exit(0);
879 }