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