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