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::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;
77 using lyx::support::os::getTmpDir;
78 using lyx::support::os::setTmpDir;
84 #ifndef CXX_GLOBAL_CSTD
91 extern void QuitLyX();
93 extern LyXServer * lyxserver;
95 // This is the global bufferlist object
96 BufferList bufferlist;
98 // convenient to have it here.
99 boost::scoped_ptr<kb_keymap> toplevel_keymap;
103 void showFileError(string const & error)
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));
114 boost::scoped_ptr<LyX> LyX::singleton_;
116 void LyX::exec(int & argc, char * argv[])
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);
130 BOOST_ASSERT(singleton_.get());
131 return *singleton_.get();
135 LyX const & LyX::cref()
137 BOOST_ASSERT(singleton_.get());
138 return *singleton_.get();
147 LastFiles & LyX::lastfiles()
149 BOOST_ASSERT(lastfiles_.get());
150 return *lastfiles_.get();
154 LastFiles const & LyX::lastfiles() const
156 BOOST_ASSERT(lastfiles_.get());
157 return *lastfiles_.get();
161 void LyX::addLyXView(boost::shared_ptr<LyXView> const & lyxview)
163 views_.push_back(lyxview);
167 Buffer const * const LyX::updateInset(InsetBase const * inset) const
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);
184 void LyX::priv_exec(int & argc, char * argv[])
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);
191 lyx_gui::parse_init(argc, argv);
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."),
203 // Initialization of LyX (reads lyxrc and more)
204 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
206 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
209 lyx_gui::parse_lyxrc();
213 vector<string> files;
215 for (int argi = argc - 1; argi >= 1; --argi)
216 files.push_back(argv[argi]);
219 files.push_back(i18nLibFileSearch("examples", "splash.lyx"));
221 // Execute batch commands if available
222 if (!batch_command.empty()) {
224 lyxerr[Debug::INIT] << "About to handle -x '"
225 << batch_command << '\'' << endl;
227 Buffer * last_loaded = 0;
229 vector<string>::const_iterator it = files.begin();
230 vector<string>::const_iterator end = files.end();
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");
237 last_loaded = newFile(*it, string(), true);
239 Buffer * buf = bufferlist.newBuffer(s, false);
240 buf->error.connect(boost::bind(&LyX::printError, this, _1));
241 if (loadLyXFile(buf, s))
244 bufferlist.release(buf);
248 // try to dispatch to last loaded buffer first
250 bool success = false;
251 if (last_loaded->dispatch(batch_command, &success)) {
256 files.clear(); // the files are already loaded
259 lyx_gui::start(batch_command, files);
265 static void error_handler(int err_sig)
267 // Throw away any signals other than the first one received.
268 static sig_atomic_t handling_error = false;
271 handling_error = true;
273 // We have received a signal indicating a fatal error, so
274 // try and save the data ASAP.
275 LyX::cref().emergencyCleanup();
277 // These lyxerr calls may or may not work:
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
286 // This shouldn't matter here, however, as we've already invoked
290 lyxerr << "\nlyx: SIGHUP signal caught\nBye." << endl;
293 lyxerr << "\nlyx: SIGFPE signal caught\nBye." << endl;
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;
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);
315 if (err_sig == SIGSEGV ||
316 (err_sig != SIGHUP && !GetEnv("LYXDEBUG").empty()))
317 lyx::support::abort();
324 void LyX::printError(ErrorItem const & ei)
326 std::cerr << _("LyX: ") << ei.error
327 << ':' << ei.description << std::endl;
332 void LyX::init(bool gui)
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.
341 bool const explicit_userdir = setLyxPaths();
343 // Check that user LyX directory is ok. We don't do that if
344 // running in batch mode.
346 queryUserLyXDir(explicit_userdir);
351 // Disable gui when easyparse says so
352 lyx_gui::use_gui = gui;
354 if (lyxrc.template_path.empty()) {
355 lyxrc.template_path = AddPath(system_lyxdir(), "templates");
358 if (lyxrc.lastfiles.empty()) {
359 lyxrc.lastfiles = AddName(user_lyxdir(), "lastfiles");
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();
370 // Read configuration files
373 readRcFile("lyxrc.defaults");
374 system_lyxrc = lyxrc;
375 system_formats = formats;
376 system_converters = converters;
377 system_movers = movers;
378 system_lcolor = lcolor;
380 string prefsfile = "preferences";
381 // back compatibility to lyxs < 1.1.6
382 if (LibFileSearch(string(), prefsfile).empty())
384 if (!LibFileSearch(string(), prefsfile).empty())
385 readRcFile(prefsfile);
387 readEncodingsFile("encodings");
388 readLanguagesFile("languages");
391 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
396 toplevel_keymap.reset(new kb_keymap);
397 defaultKeyBindings(toplevel_keymap.get());
398 toplevel_keymap->read(lyxrc.bind_file);
401 readUIFile(lyxrc.ui_file);
404 if (lyxerr.debugging(Debug::LYXRC))
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.
422 if (lyxerr.debugging(Debug::INIT)) {
423 lyxerr << "LyX tmp dir: `" << getTmpDir() << '\'' << endl;
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));
434 void LyX::defaultKeyBindings(kb_keymap * kbmap)
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));
441 kbmap->bind("Tab", FuncRequest(LFUN_CELL_FORWARD));
442 kbmap->bind("ISO_Left_Tab", FuncRequest(LFUN_CELL_FORWARD));
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));
449 kbmap->bind("Return", FuncRequest(LFUN_BREAKPARAGRAPH));
450 //kbmap->bind("~C-~S-~M-nobreakspace", FuncRequest(LFUN_PROTECTEDSPACE));
452 kbmap->bind("Delete", FuncRequest(LFUN_DELETE));
453 kbmap->bind("BackSpace", FuncRequest(LFUN_BACKSPACE));
455 // kbmap->bindings to enable the use of the numeric keypad
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));
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));
488 void LyX::emergencyCleanup() const
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
495 bufferlist.emergencyWriteAll();
497 lyxserver->emergencyCleanup();
501 void LyX::deadKeyBindings(kb_keymap * kbmap)
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));
527 void LyX::queryUserLyXDir(bool explicit_userdir)
529 string const configure_script = AddName(system_lyxdir(), "configure");
531 // Does user directory exist?
532 FileInfo fileInfo(user_lyxdir());
533 if (fileInfo.isOK() && fileInfo.isDir()) {
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")
541 Path p(user_lyxdir());
542 ::system(configure_script.c_str());
543 lyxerr << "LyX: " << _("Done!") << endl;
548 first_start = !explicit_userdir;
550 lyxerr << bformat(_("LyX: Creating directory %1$s"
551 " and running configure..."), user_lyxdir()) << endl;
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;
561 // Run configure in user lyx directory
562 Path p(user_lyxdir());
563 ::system(configure_script.c_str());
564 lyxerr << "LyX: " << _("Done!") << endl;
568 void LyX::readRcFile(string const & name)
570 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
572 string const lyxrc_path = LibFileSearch(string(), name);
573 if (!lyxrc_path.empty()) {
575 lyxerr[Debug::INIT] << "Found " << name
576 << " in " << lyxrc_path << endl;
578 if (lyxrc.read(lyxrc_path) >= 0)
586 // Read the ui file `name'
587 void LyX::readUIFile(string const & name)
597 struct keyword_item uitags[ui_last - 1] = {
598 { "include", ui_include },
599 { "menuset", ui_menuset },
600 { "toolbar", ui_toolbar },
601 { "toolbars", ui_toolbars }
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);
610 lyxerr[Debug::INIT] << "UI file '" << name
611 << "' has been read already. "
612 << "Is this an include loop?"
617 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
619 string const ui_path = LibFileSearch("ui", name, "ui");
621 if (ui_path.empty()) {
622 lyxerr[Debug::INIT] << "Could not find " << name << endl;
626 uifiles.push_back(name);
628 lyxerr[Debug::INIT] << "Found " << name
629 << " in " << ui_path << endl;
630 LyXLex lex(uitags, ui_last - 1);
631 lex.setFile(ui_path);
633 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
637 if (lyxerr.debugging(Debug::PARSER))
638 lex.printTable(lyxerr);
644 string const file = lex.getString();
649 menubackend.read(lex);
653 toolbarbackend.read(lex);
657 toolbarbackend.readToolbars(lex);
661 if (!rtrim(lex.getString()).empty())
662 lex.printError("LyX::ReadUIFile: "
663 "Unknown menu tag: `$$Token'");
670 // Read the languages file `name'
671 void LyX::readLanguagesFile(string const & name)
673 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
675 string const lang_path = LibFileSearch(string(), name);
676 if (lang_path.empty()) {
680 languages.read(lang_path);
684 // Read the encodings file `name'
685 void LyX::readEncodingsFile(string const & name)
687 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
689 string const enc_path = LibFileSearch(string(), name);
690 if (enc_path.empty()) {
694 encodings.read(enc_path);
703 /// return the the number of arguments consumed
704 typedef boost::function<int(string const &, string const &)> cmd_helper;
706 int parse_dbg(string const & arg, string const &)
709 lyxerr << _("List of supported debug flags:") << endl;
710 Debug::showTags(lyxerr);
713 lyxerr << bformat(_("Setting debug level to %1$s"), arg) << endl;
715 lyxerr.level(Debug::value(arg));
716 Debug::showLevel(lyxerr, lyxerr.level());
721 int parse_help(string const &, string const &)
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;
746 int parse_version(string const &, string const &)
748 lyxerr << "LyX " << lyx_version
749 << " of " << lyx_release_date << endl;
750 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
752 lyxerr << lyx_version_info << endl;
757 int parse_sysdir(string const & arg, string const &)
760 lyxerr << _("Missing directory for -sysdir switch") << endl;
767 int parse_userdir(string const & arg, string const &)
770 lyxerr << _("Missing directory for -userdir switch") << endl;
777 int parse_execute(string const & arg, string const &)
780 lyxerr << _("Missing command string after --execute switch") << endl;
784 // Argh. Setting gui to false segfaults..
785 // FIXME: when ? how ?
790 int parse_export(string const & type, string const &)
793 lyxerr << _("Missing file type [eg latex, ps...] after "
794 "--export switch") << endl;
797 batch = "buffer-export " + type;
802 int parse_import(string const & type, string const & file)
805 lyxerr << _("Missing file type [eg latex, ps...] after "
806 "--import switch") << endl;
810 lyxerr << _("Missing filename for --import") << endl;
814 batch = "buffer-import " + type + ' ' + file;
821 bool LyX::easyParse(int & argc, char * argv[])
823 std::map<string, cmd_helper> cmdmap;
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;
839 for (int i = 1; i < argc; ++i) {
840 std::map<string, cmd_helper>::const_iterator it
841 = cmdmap.find(argv[i]);
843 // don't complain if not found - may be parsed later
844 if (it == cmdmap.end())
847 string arg((i + 1 < argc) ? argv[i + 1] : "");
848 string arg2((i + 2 < argc) ? argv[i + 2] : "");
850 int const remove = 1 + it->second(arg, arg2);
852 // Now, remove used arguments by shifting
853 // the following ones remove places down.
855 for (int j = i; j < argc; ++j)
856 argv[j] = argv[j + remove];
860 batch_command = batch;