]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
e55212f0388ea4df967ec2801a5dbec6e71988cb
[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 USE_BOOST_FORMAT
602         lyxerr << boost::format(_("LyX: Creating directory %1$s"
603                                   " and running configure..."))
604                 % user_lyxdir
605                << endl;
606 #else
607         lyxerr << _("LyX: Creating directory ") << user_lyxdir
608                << _(" and running configure...")
609                << endl;
610 #endif
611
612         if (!createDirectory(user_lyxdir, 0755)) {
613                 // Failed, let's use $HOME instead.
614                 user_lyxdir = GetEnvPath("HOME");
615 #if USE_BOOST_FORMAT
616                 lyxerr << boost::format(_("Failed. Will use %1$s instead."))
617                         % user_lyxdir
618                        << endl;
619 #else
620                 lyxerr << _("Failed. Will use ") << user_lyxdir <<
621                         _(" instead.")
622                        << endl;
623 #endif
624                 return;
625         }
626
627         // Run configure in user lyx directory
628         Path p(user_lyxdir);
629         ::system(configure_script.c_str());
630         lyxerr << "LyX: " << _("Done!") << endl;
631 }
632
633
634 bool LyX::readRcFile(string const & name)
635 {
636         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
637
638         string const lyxrc_path = LibFileSearch(string(), name);
639         if (!lyxrc_path.empty()) {
640                 lyxerr[Debug::INIT] << "Found " << name
641                                     << " in " << lyxrc_path << endl;
642                 if (lyxrc.read(lyxrc_path) < 0) {
643 #if USE_BOOST_FORMAT
644                         Alert::alert(_("LyX Warning!"),
645                                    boost::io::str(boost::format(_("Error while reading %1$s.")) % lyxrc_path),
646                                    _("Using built-in defaults."));
647 #else
648                         Alert::alert(_("LyX Warning!"),
649                                    _("Error while reading ") + lyxrc_path,
650                                    _("Using built-in defaults."));
651 #endif
652                         return false;
653                 }
654                 return true;
655         } else {
656                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
657         }
658
659         return false;
660 }
661
662
663 // Read the ui file `name'
664 void LyX::readUIFile(string const & name)
665 {
666         enum Uitags {
667                 ui_menuset = 1,
668                 ui_toolbar,
669                 ui_last
670         };
671
672         struct keyword_item uitags[ui_last - 1] = {
673                 { "menuset", ui_menuset },
674                 { "toolbar", ui_toolbar }
675         };
676
677         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
678
679         string const ui_path = LibFileSearch("ui", name, "ui");
680
681         if (ui_path.empty()) {
682                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
683                 menubackend.defaults();
684                 return;
685         }
686
687         lyxerr[Debug::INIT] << "Found " << name
688                             << " in " << ui_path << endl;
689         LyXLex lex(uitags, ui_last - 1);
690         lex.setFile(ui_path);
691         if (!lex.isOK()) {
692                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
693                        << endl;
694         }
695
696         if (lyxerr.debugging(Debug::PARSER))
697                 lex.printTable(lyxerr);
698
699         while (lex.isOK()) {
700                 switch (lex.lex()) {
701                 case ui_menuset:
702                         menubackend.read(lex);
703                         break;
704
705                 case ui_toolbar:
706                         toolbardefaults.read(lex);
707                         break;
708
709                 default:
710                         if (!rtrim(lex.getString()).empty())
711                                 lex.printError("LyX::ReadUIFile: "
712                                                "Unknown menu tag: `$$Token'");
713                         break;
714                 }
715         }
716 }
717
718
719 // Read the languages file `name'
720 void LyX::readLanguagesFile(string const & name)
721 {
722         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
723
724         string const lang_path = LibFileSearch(string(), name);
725         if (lang_path.empty()) {
726                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
727                 languages.setDefaults();
728                 return;
729         }
730         languages.read(lang_path);
731 }
732
733
734 // Read the encodings file `name'
735 void LyX::readEncodingsFile(string const & name)
736 {
737         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
738
739         string const enc_path = LibFileSearch(string(), name);
740         if (enc_path.empty()) {
741                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
742                 return;
743         }
744         encodings.read(enc_path);
745 }
746
747
748 namespace {
749
750 bool is_gui = true;
751 string batch;
752
753 /// return the the number of arguments consumed
754 typedef boost::function<int(string const &, string const &)> cmd_helper;
755
756 int parse_dbg(string const & arg, string const &)
757 {
758         if (arg.empty()) {
759                 lyxerr << _("List of supported debug flags:") << endl;
760                 Debug::showTags(lyxerr);
761                 exit(0);
762         }
763 #if USE_BOOST_FORMAT
764         lyxerr << boost::format(_("Setting debug level to %1$s"))
765                 % arg
766                << endl;
767 #else
768         lyxerr << _("Setting debug level to ") << arg << endl;
769 #endif
770
771         lyxerr.level(Debug::value(arg));
772         Debug::showLevel(lyxerr, lyxerr.level());
773         return 1;
774 }
775
776 int parse_help(string const &, string const &)
777 {
778         lyxerr <<
779                 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
780                   "Command line switches (case sensitive):\n"
781                   "\t-help              summarize LyX usage\n"
782                   "\t-userdir dir       try to set user directory to dir\n"
783                   "\t-sysdir dir        try to set system directory to dir\n"
784                   "\t-geometry WxH+X+Y  set geometry of the main window\n"
785                   "\t-dbg feature[,feature]...\n"
786                   "                  select the features to debug.\n"
787                   "                  Type `lyx -dbg' to see the list of features\n"
788                   "\t-x [--execute] command\n"
789                   "                  where command is a lyx command.\n"
790                   "\t-e [--export] fmt\n"
791                   "                  where fmt is the export format of choice.\n"
792                   "\t-i [--import] fmt file.xxx\n"
793                   "                  where fmt is the import format of choice\n"
794                   "                  and file.xxx is the file to be imported.\n"
795                   "\t-version        summarize version and build info\n"
796                   "Check the LyX man page for more details.") << endl;
797         exit(0);
798         return 0;
799 }
800
801 int parse_version(string const &, string const &)
802 {
803         lyxerr << "LyX " << lyx_version
804                << " of " << lyx_release_date << endl;
805         lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
806
807         lyxerr << lyx_version_info << endl;
808         exit(0);
809         return 0;
810 }
811
812 int parse_sysdir(string const & arg, string const &)
813 {
814         if (arg.empty()) {
815                 lyxerr << _("Missing directory for -sysdir switch") << endl;
816                 exit(1);
817         }
818         system_lyxdir = arg;
819         return 1;
820 }
821
822 int parse_userdir(string const & arg, string const &)
823 {
824         if (arg.empty()) {
825                 lyxerr << _("Missing directory for -userdir switch") << endl;
826                 exit(1);
827         }
828         user_lyxdir = arg;
829         return 1;
830 }
831
832 int parse_execute(string const & arg, string const &)
833 {
834         if (arg.empty()) {
835                 lyxerr << _("Missing command string after --execute switch") << endl;
836                 exit(1);
837         }
838         batch = arg;
839         // Argh. Setting gui to false segfaults..
840         // FIXME: when ? how ?
841         // is_gui = false;
842         return 1;
843 }
844
845 int parse_export(string const & type, string const &)
846 {
847         if (type.empty()) {
848                 lyxerr << _("Missing file type [eg latex, ps...] after "
849                         "--export switch") << endl;
850                 exit(1);
851         }
852         batch = "buffer-export " + type;
853         is_gui = false;
854         return 1;
855 }
856
857 int parse_import(string const & type, string const & file)
858 {
859         if (type.empty()) {
860                 lyxerr << _("Missing file type [eg latex, ps...] after "
861                         "--import switch") << endl;
862                 exit(1);
863         }
864         if (file.empty()) {
865                 lyxerr << _("Missing filename for --import") << endl;
866                 exit(1);
867         }
868
869         batch = "buffer-import " + type + ' ' + file;
870         return 2;
871 }
872
873 } // namespace anon
874
875
876 bool LyX::easyParse(int & argc, char * argv[])
877 {
878         std::map<string, cmd_helper> cmdmap;
879
880         cmdmap["-dbg"] = parse_dbg;
881         cmdmap["-help"] = parse_help;
882         cmdmap["--help"] = parse_help;
883         cmdmap["-version"] = parse_version;
884         cmdmap["--version"] = parse_version;
885         cmdmap["-sysdir"] = parse_sysdir;
886         cmdmap["-userdir"] = parse_userdir;
887         cmdmap["-x"] = parse_execute;
888         cmdmap["--execute"] = parse_execute;
889         cmdmap["-e"] = parse_export;
890         cmdmap["--export"] = parse_export;
891         cmdmap["-i"] = parse_import;
892         cmdmap["--import"] = parse_import;
893
894         for (int i = 1; i < argc; ++i) {
895                 std::map<string, cmd_helper>::const_iterator it
896                         = cmdmap.find(argv[i]);
897
898                 // don't complain if not found - may be parsed later
899                 if (it == cmdmap.end())
900                         continue;
901
902                 string arg((i + 1 < argc) ? argv[i + 1] : "");
903                 string arg2((i + 2 < argc) ? argv[i + 2] : "");
904
905                 int const remove = 1 + it->second(arg, arg2);
906
907                 // Now, remove used arguments by shifting
908                 // the following ones remove places down.
909                 argc -= remove;
910                 for (int j = i; j < argc; ++j)
911                         argv[j] = argv[j + remove];
912                 --i;
913         }
914
915         batch_command = batch;
916
917         return is_gui;
918 }