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