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