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