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