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