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