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