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