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