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