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