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