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