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