]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
Michael's text fixes
[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         lyxerr << argc << endl;
97
98         if (want_gui) {
99                 lyxerr <<  "parsinint" << endl;
100                 lyx_gui::parse_init(argc, argv);
101         }
102
103         lyxerr << argc << endl;
104
105         // check for any spurious extra arguments
106         // other than documents
107         for (int argi = 1; argi < argc ; ++argi) {
108                 if (argv[argi][0] == '-') {
109 #if USE_BOOST_FORMAT
110                         lyxerr << boost::format(_("Wrong command line option `%1$s'. Exiting."))
111                                 % argv[argi]
112                                << endl;
113 #else
114                         lyxerr << _("Wrong command line option `")
115                                << argv[argi] << _("'. Exiting.")
116                                << endl;
117 #endif
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
141         // Execute batch commands if available
142         if (!batch_command.empty()) {
143                 lyxerr[Debug::INIT] << "About to handle -x '"
144                        << batch_command << '\'' << endl;
145
146                 Buffer * last_loaded = 0;
147
148                 vector<string>::iterator it = files.begin();
149                 vector<string>::iterator end = files.end();
150                 for (; it != end; ++it) {
151                         last_loaded = bufferlist.loadLyXFile(*it);
152                 }
153
154                 files.clear();
155
156                 // no buffer loaded, create one
157                 if (!last_loaded)
158                         last_loaded = bufferlist.newFile("tmpfile", string());
159
160                 bool success = false;
161
162                 // try to dispatch to last loaded buffer first
163                 bool const dispatched = last_loaded->dispatch(batch_command, &success);
164
165                 if (dispatched) {
166                         QuitLyX();
167                         exit(!success);
168                 }
169         }
170
171         lyx_gui::start(batch_command, files);
172 }
173
174
175 extern "C" {
176
177 static void error_handler(int err_sig)
178 {
179         switch (err_sig) {
180         case SIGHUP:
181                 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
182                 break;
183         case SIGINT:
184                 // no comments
185                 break;
186         case SIGFPE:
187                 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
188                 break;
189         case SIGSEGV:
190                 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
191                 lyxerr <<
192                         "Sorry, you have found a bug in LyX. "
193                         "Please read the bug-reporting instructions "
194                         "in Help->Introduction and send us a bug report, "
195                         "if necessary. Thanks !" << endl;
196                 break;
197         case SIGTERM:
198                 // no comments
199                 break;
200         }
201
202         // Deinstall the signal handlers
203         signal(SIGHUP, SIG_DFL);
204         signal(SIGINT, SIG_DFL);
205         signal(SIGFPE, SIG_DFL);
206         signal(SIGSEGV, SIG_DFL);
207         signal(SIGTERM, SIG_DFL);
208
209         LyX::emergencyCleanup();
210
211         lyxerr << "Bye." << endl;
212         if (err_sig!= SIGHUP &&
213            (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
214                 lyx::abort();
215         exit(0);
216 }
217
218 }
219
220
221 void LyX::init(bool gui)
222 {
223         signal(SIGHUP, error_handler);
224         signal(SIGFPE, error_handler);
225         signal(SIGSEGV, error_handler);
226         signal(SIGINT, error_handler);
227         signal(SIGTERM, error_handler);
228
229         //
230         // Determine path of binary
231         //
232
233         string binpath = os::binpath();
234         string binname = os::binname();
235         string fullbinname = MakeAbsPath(binname, binpath);
236
237         if (binpath.empty()) {
238                 lyxerr << _("Warning: could not determine path of binary.")
239                        << "\n"
240                        << _("If you have problems, try starting LyX with an absolute path.")
241                        << endl;
242         }
243         lyxerr[Debug::INIT] << "Name of binary: " << binname << endl;
244         lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
245
246         //
247         // Determine system directory.
248         //
249
250         // Directories are searched in this order:
251         // 1) -sysdir command line parameter
252         // 2) LYX_DIR_13x environment variable
253         // 3) Maybe <path of binary>/TOP_SRCDIR/lib
254         // 4) <path of binary>/../share/<name of binary>/
255         // 4a) repeat 4 after following the Symlink if <path of
256         //     binary> is a symbolic link.
257         // 5) hardcoded lyx_dir
258         // The directory is checked for the presence of the file
259         // "chkconfig.ltx", and if that is present, the directory
260         // is accepted as the system directory.
261         // If no chkconfig.ltx file is found, a warning is given,
262         // and the hardcoded lyx_dir is used.
263
264         // If we had a command line switch, system_lyxdir is already set
265         string searchpath;
266         if (!system_lyxdir.empty())
267                 searchpath = MakeAbsPath(system_lyxdir) + ';';
268
269         string const lyxdir = GetEnvPath("LYX_DIR_13x");
270
271         if (!lyxdir.empty()) {
272                 lyxerr[Debug::INIT] << "LYX_DIR_13x: " << lyxdir << endl;
273                 searchpath += lyxdir + ';';
274         }
275
276         string fullbinpath = binpath;
277         FileInfo file(fullbinname, true);
278         if (file.isLink()) {
279                 lyxerr[Debug::INIT] << "binary is a link" << endl;
280                 string link;
281                 if (LyXReadLink(fullbinname, link, true)) {
282                         // Path of binary/../share/name of binary/
283                         searchpath += NormalizePath(AddPath(binpath,
284                                                             "../share/")
285                                                     + OnlyFilename(binname));
286                         searchpath += ';';
287                         fullbinpath = link;
288                         binpath = MakeAbsPath(OnlyPath(fullbinpath));
289                 }
290         }
291
292         bool followlink;
293         do {
294                 // Path of binary/../share/name of binary/
295                 searchpath += NormalizePath(AddPath(binpath, "../share/") +
296                       OnlyFilename(binname)) + ';';
297
298                 // Follow Symlinks
299                 FileInfo file(fullbinpath, true);
300                 followlink = file.isLink();
301                 if (followlink) {
302                         lyxerr[Debug::INIT] << " directory " << fullbinpath
303                                             << " is a link" << endl;
304                         string link;
305                         if (LyXReadLink(fullbinpath, link, true)) {
306                                 fullbinpath = link;
307                                 binpath = MakeAbsPath(OnlyPath(fullbinpath));
308                         }
309                         else {
310                                 followlink = false;
311                         }
312                 }
313         } while (followlink);
314
315         // <path of binary>/TOP_SRCDIR/lib
316         build_lyxdir = MakeAbsPath("../lib", binpath);
317         if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
318                 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
319                                           binpath) + ';';
320                 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
321                         "place... yes" << endl;
322         } else {
323                 lyxerr[Debug::INIT]
324                         << "Checking whether LyX is run in place... no"
325                         << endl;
326                 build_lyxdir.erase();
327         }
328
329         // Hardcoded dir
330         searchpath += LYX_DIR;
331
332         lyxerr[Debug::INIT] << "System directory search path: "
333                             << searchpath << endl;
334
335         string const filename = "chkconfig.ltx";
336         string const temp = FileOpenSearch(searchpath, filename, string());
337         system_lyxdir = OnlyPath(temp);
338
339         // Reduce "path/../path" stuff out of system directory
340         system_lyxdir = NormalizePath(system_lyxdir);
341
342         bool path_shown = false;
343
344         // Warn if environment variable is set, but unusable
345         if (!lyxdir.empty()) {
346                 if (system_lyxdir != NormalizePath(lyxdir)) {
347                         lyxerr <<_("LYX_DIR_13x environment variable no good.")
348                                << '\n'
349                                << _("System directory set to: ")
350                                << system_lyxdir << endl;
351                         path_shown = true;
352                 }
353         }
354
355         // Warn the user if we couldn't find "chkconfig.ltx"
356         if (system_lyxdir == "./") {
357                 lyxerr <<_("LyX Warning! Couldn't determine system directory. ")
358                        <<_("Try the '-sysdir' command line parameter or ")
359                        <<_("set the environment variable LYX_DIR_13x to the "
360                            "LyX system directory ")
361                        << _("containing the file `chkconfig.ltx'.") << endl;
362                 if (!path_shown) {
363                         FileInfo fi(LYX_DIR);
364                         if (!fi.exist()) {
365                                 lyxerr << "Couldn't even find the default LYX_DIR." << endl
366                                         << "Giving up." << endl;
367                                 exit(1);
368                         }
369 #if USE_BOOST_FORMAT
370                         lyxerr << boost::format(_("Using built-in default %1$s"
371                                                   " but expect problems."))
372                                 % static_cast<char *>(LYX_DIR)
373                                << endl;
374 #else
375                         lyxerr << _("Using built-in default ") << LYX_DIR
376                                << _(" but expect problems.")
377                                << endl;
378 #endif
379                 } else {
380                         lyxerr << _("Expect problems.") << endl;
381                 }
382                 system_lyxdir = LYX_DIR;
383                 path_shown = true;
384         }
385
386         if (!path_shown)
387                 lyxerr[Debug::INIT] << "System directory: '"
388                                     << system_lyxdir << '\'' << endl;
389
390         //
391         // Determine user lyx-dir
392         //
393
394         // Directories are searched in this order:
395         // 1) -userdir command line parameter
396         // 2) LYX_USERDIR_13x environment variable
397         // 3) $HOME/.<name of binary>
398
399         // If we had a command line switch, user_lyxdir is already set
400         bool explicit_userdir = true;
401         if (user_lyxdir.empty()) {
402
403                 // LYX_USERDIR_13x environment variable
404                 user_lyxdir = GetEnvPath("LYX_USERDIR_13x");
405
406                 // default behaviour
407                 if (user_lyxdir.empty())
408                         user_lyxdir = AddPath(GetEnvPath("HOME"),
409                                                         string(".") + PACKAGE);
410                         explicit_userdir = false;
411         }
412
413         lyxerr[Debug::INIT] << "User LyX directory: '"
414                             <<  user_lyxdir << '\'' << endl;
415
416         // Check that user LyX directory is ok. We don't do that if
417         // running in batch mode.
418         if (gui) {
419                 queryUserLyXDir(explicit_userdir);
420         } else {
421                 first_start = false;
422         }
423
424         //
425         // Shine up lyxrc defaults
426         //
427
428         // Default template path: system_dir/templates
429         if (lyxrc.template_path.empty()) {
430                 lyxrc.template_path = AddPath(system_lyxdir, "templates");
431         }
432
433         // Default lastfiles file: $HOME/.lyx/lastfiles
434         if (lyxrc.lastfiles.empty()) {
435                 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
436         }
437
438         // Disable gui when either lyxrc or easyparse says so
439         if (!gui)
440                 lyxrc.use_gui = false;
441
442         //
443         // Read configuration files
444         //
445
446         readRcFile("lyxrc.defaults");
447         system_lyxrc = lyxrc;
448         system_formats = formats;
449         system_converters = converters;
450         system_lcolor = lcolor;
451
452         // If there is a preferences file we read that instead
453         // of the old lyxrc file.
454         if (!readRcFile("preferences"))
455             readRcFile("lyxrc");
456
457         readEncodingsFile("encodings");
458         readLanguagesFile("languages");
459
460         // Load the layouts
461         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
462         LyXSetStyle();
463
464         // Ensure that we have really read a bind file, so that LyX is
465         // usable.
466         lyxrc.readBindFileIfNeeded();
467
468         // Read menus
469         readUIFile(lyxrc.ui_file);
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 }