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