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