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