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