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