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