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