3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
10 * \author André Pönitz
12 * Full author contact details are available in file CREDITS.
21 #include "buffer_funcs.h"
22 #include "bufferlist.h"
23 #include "converter.h"
26 #include "errorlist.h"
31 #include "lastfiles.h"
36 #include "lyxtextclasslist.h"
37 #include "lyxserver.h"
38 #include "MenuBackend.h"
40 #include "ToolbarBackend.h"
42 #include "mathed/math_inset.h"
44 #include "frontends/Alert.h"
45 #include "frontends/lyx_gui.h"
46 #include "frontends/LyXView.h"
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"
55 #include <boost/bind.hpp>
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;
76 using lyx::support::os::getTmpDir;
77 using lyx::support::os::setTmpDir;
79 namespace os = lyx::support::os;
85 #ifndef CXX_GLOBAL_CSTD
92 extern void QuitLyX();
94 extern LyXServer * lyxserver;
96 // This is the global bufferlist object
97 BufferList bufferlist;
99 // convenient to have it here.
100 boost::scoped_ptr<kb_keymap> toplevel_keymap;
104 void showFileError(string const & error)
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));
115 boost::scoped_ptr<LyX> LyX::singleton_;
117 void LyX::exec(int & argc, char * argv[])
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);
131 BOOST_ASSERT(singleton_.get());
132 return *singleton_.get();
136 LyX const & LyX::cref()
138 BOOST_ASSERT(singleton_.get());
139 return *singleton_.get();
148 LastFiles & LyX::lastfiles()
150 BOOST_ASSERT(lastfiles_.get());
151 return *lastfiles_.get();
155 LastFiles const & LyX::lastfiles() const
157 BOOST_ASSERT(lastfiles_.get());
158 return *lastfiles_.get();
162 void LyX::addLyXView(boost::shared_ptr<LyXView> const & lyxview)
164 views_.push_back(lyxview);
168 Buffer const * const LyX::updateInset(InsetBase const * inset) const
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);
185 void LyX::priv_exec(int & argc, char * argv[])
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);
192 lyx_gui::parse_init(argc, argv);
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."),
204 // Initialization of LyX (reads lyxrc and more)
205 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
207 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
210 lyx_gui::parse_lyxrc();
214 vector<string> files;
216 for (int argi = argc - 1; argi >= 1; --argi)
217 files.push_back(argv[argi]);
220 files.push_back(i18nLibFileSearch("examples", "splash.lyx"));
222 // Execute batch commands if available
223 if (!batch_command.empty()) {
225 lyxerr[Debug::INIT] << "About to handle -x '"
226 << batch_command << '\'' << endl;
228 Buffer * last_loaded = 0;
230 vector<string>::const_iterator it = files.begin();
231 vector<string>::const_iterator end = files.end();
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");
238 last_loaded = newFile(*it, string(), true);
240 Buffer * buf = bufferlist.newBuffer(s, false);
241 buf->error.connect(boost::bind(&LyX::printError, this, _1));
242 if (loadLyXFile(buf, s))
245 bufferlist.release(buf);
249 // try to dispatch to last loaded buffer first
251 bool success = false;
252 if (last_loaded->dispatch(batch_command, &success)) {
257 files.clear(); // the files are already loaded
260 lyx_gui::start(batch_command, files);
266 static void error_handler(int err_sig)
268 // Throw away any signals other than the first one received.
269 static sig_atomic_t handling_error = false;
272 handling_error = true;
274 // We have received a signal indicating a fatal error, so
275 // try and save the data ASAP.
276 LyX::cref().emergencyCleanup();
278 // These lyxerr calls may or may not work:
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
287 // This shouldn't matter here, however, as we've already invoked
291 lyxerr << "\nlyx: SIGHUP signal caught\nBye." << endl;
294 lyxerr << "\nlyx: SIGFPE signal caught\nBye." << endl;
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;
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);
316 if (err_sig == SIGSEGV ||
317 (err_sig != SIGHUP && !GetEnv("LYXDEBUG").empty()))
318 lyx::support::abort();
325 void LyX::printError(ErrorItem const & ei)
327 std::cerr << _("LyX: ") << ei.error
328 << ':' << ei.description << std::endl;
333 void LyX::init(bool gui)
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.
342 bool const explicit_userdir = setLyxPaths();
344 // Check that user LyX directory is ok. We don't do that if
345 // running in batch mode.
347 queryUserLyXDir(explicit_userdir);
352 // Disable gui when easyparse says so
353 lyx_gui::use_gui = gui;
355 if (lyxrc.template_path.empty()) {
356 lyxrc.template_path = AddPath(system_lyxdir(), "templates");
359 if (lyxrc.lastfiles.empty()) {
360 lyxrc.lastfiles = AddName(user_lyxdir(), "lastfiles");
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();
371 // Read configuration files
374 readRcFile("lyxrc.defaults");
375 system_lyxrc = lyxrc;
376 system_formats = formats;
377 system_converters = converters;
378 system_movers = movers;
379 system_lcolor = lcolor;
381 string prefsfile = "preferences";
382 // back compatibility to lyxs < 1.1.6
383 if (LibFileSearch(string(), prefsfile).empty())
385 if (!LibFileSearch(string(), prefsfile).empty())
386 readRcFile(prefsfile);
388 readEncodingsFile("encodings");
389 readLanguagesFile("languages");
392 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
397 toplevel_keymap.reset(new kb_keymap);
398 defaultKeyBindings(toplevel_keymap.get());
399 toplevel_keymap->read(lyxrc.bind_file);
402 readUIFile(lyxrc.ui_file);
405 if (lyxerr.debugging(Debug::LYXRC))
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.
423 if (lyxerr.debugging(Debug::INIT)) {
424 lyxerr << "LyX tmp dir: `" << getTmpDir() << '\'' << endl;
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));
435 void LyX::defaultKeyBindings(kb_keymap * kbmap)
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));
442 kbmap->bind("Tab", FuncRequest(LFUN_CELL_FORWARD));
443 kbmap->bind("ISO_Left_Tab", FuncRequest(LFUN_CELL_FORWARD));
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));
450 kbmap->bind("Return", FuncRequest(LFUN_BREAKPARAGRAPH));
451 //kbmap->bind("~C-~S-~M-nobreakspace", FuncRequest(LFUN_PROTECTEDSPACE));
453 kbmap->bind("Delete", FuncRequest(LFUN_DELETE));
454 kbmap->bind("BackSpace", FuncRequest(LFUN_BACKSPACE));
456 // kbmap->bindings to enable the use of the numeric keypad
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));
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));
489 void LyX::emergencyCleanup() const
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
496 bufferlist.emergencyWriteAll();
498 lyxserver->emergencyCleanup();
502 void LyX::deadKeyBindings(kb_keymap * kbmap)
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));
528 void LyX::queryUserLyXDir(bool explicit_userdir)
530 string const configure_script = AddName(system_lyxdir(), "configure");
532 // Does user directory exist?
533 FileInfo fileInfo(user_lyxdir());
534 if (fileInfo.isOK() && fileInfo.isDir()) {
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")
542 Path p(user_lyxdir());
543 ::system(configure_script.c_str());
544 lyxerr << "LyX: " << _("Done!") << endl;
549 first_start = !explicit_userdir;
551 lyxerr << bformat(_("LyX: Creating directory %1$s"
552 " and running configure..."), user_lyxdir()) << endl;
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;
562 // Run configure in user lyx directory
563 Path p(user_lyxdir());
564 ::system(configure_script.c_str());
565 lyxerr << "LyX: " << _("Done!") << endl;
569 void LyX::readRcFile(string const & name)
571 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
573 string const lyxrc_path = LibFileSearch(string(), name);
574 if (!lyxrc_path.empty()) {
576 lyxerr[Debug::INIT] << "Found " << name
577 << " in " << lyxrc_path << endl;
579 if (lyxrc.read(lyxrc_path) >= 0)
587 // Read the ui file `name'
588 void LyX::readUIFile(string const & name)
598 struct keyword_item uitags[ui_last - 1] = {
599 { "include", ui_include },
600 { "menuset", ui_menuset },
601 { "toolbar", ui_toolbar },
602 { "toolbars", ui_toolbars }
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);
611 lyxerr[Debug::INIT] << "UI file '" << name
612 << "' has been read already. "
613 << "Is this an include loop?"
618 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
620 string const ui_path = LibFileSearch("ui", name, "ui");
622 if (ui_path.empty()) {
623 lyxerr[Debug::INIT] << "Could not find " << name << endl;
627 uifiles.push_back(name);
629 lyxerr[Debug::INIT] << "Found " << name
630 << " in " << ui_path << endl;
631 LyXLex lex(uitags, ui_last - 1);
632 lex.setFile(ui_path);
634 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
638 if (lyxerr.debugging(Debug::PARSER))
639 lex.printTable(lyxerr);
645 string const file = lex.getString();
650 menubackend.read(lex);
654 toolbarbackend.read(lex);
658 toolbarbackend.readToolbars(lex);
662 if (!rtrim(lex.getString()).empty())
663 lex.printError("LyX::ReadUIFile: "
664 "Unknown menu tag: `$$Token'");
671 // Read the languages file `name'
672 void LyX::readLanguagesFile(string const & name)
674 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
676 string const lang_path = LibFileSearch(string(), name);
677 if (lang_path.empty()) {
681 languages.read(lang_path);
685 // Read the encodings file `name'
686 void LyX::readEncodingsFile(string const & name)
688 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
690 string const enc_path = LibFileSearch(string(), name);
691 if (enc_path.empty()) {
695 encodings.read(enc_path);
704 /// return the the number of arguments consumed
705 typedef boost::function<int(string const &, string const &)> cmd_helper;
707 int parse_dbg(string const & arg, string const &)
710 lyxerr << _("List of supported debug flags:") << endl;
711 Debug::showTags(lyxerr);
714 lyxerr << bformat(_("Setting debug level to %1$s"), arg) << endl;
716 lyxerr.level(Debug::value(arg));
717 Debug::showLevel(lyxerr, lyxerr.level());
722 int parse_help(string const &, string const &)
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;
747 int parse_version(string const &, string const &)
749 lyxerr << "LyX " << lyx_version
750 << " of " << lyx_release_date << endl;
751 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
753 lyxerr << lyx_version_info << endl;
758 int parse_sysdir(string const & arg, string const &)
761 lyxerr << _("Missing directory for -sysdir switch") << endl;
768 int parse_userdir(string const & arg, string const &)
771 lyxerr << _("Missing directory for -userdir switch") << endl;
778 int parse_execute(string const & arg, string const &)
781 lyxerr << _("Missing command string after --execute switch") << endl;
785 // Argh. Setting gui to false segfaults..
786 // FIXME: when ? how ?
791 int parse_export(string const & type, string const &)
794 lyxerr << _("Missing file type [eg latex, ps...] after "
795 "--export switch") << endl;
798 batch = "buffer-export " + type;
803 int parse_import(string const & type, string const & file)
806 lyxerr << _("Missing file type [eg latex, ps...] after "
807 "--import switch") << endl;
811 lyxerr << _("Missing filename for --import") << endl;
815 batch = "buffer-import " + type + ' ' + file;
822 bool LyX::easyParse(int & argc, char * argv[])
824 std::map<string, cmd_helper> cmdmap;
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;
840 for (int i = 1; i < argc; ++i) {
841 std::map<string, cmd_helper>::const_iterator it
842 = cmdmap.find(argv[i]);
844 // don't complain if not found - may be parsed later
845 if (it == cmdmap.end())
848 string arg((i + 1 < argc) ? argv[i + 1] : "");
849 string arg2((i + 2 < argc) ? argv[i + 2] : "");
851 int const remove = 1 + it->second(arg, arg2);
853 // Now, remove used arguments by shifting
854 // the following ones remove places down.
856 for (int j = i; j < argc; ++j)
857 argv[j] = argv[j + remove];
861 batch_command = batch;