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