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"
39 #include "ToolbarBackend.h"
41 #include "frontends/Alert.h"
42 #include "frontends/lyx_gui.h"
43 #include "frontends/LyXView.h"
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"
52 #include <boost/bind.hpp>
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;
74 namespace os = lyx::support::os;
80 #ifndef CXX_GLOBAL_CSTD
87 extern void QuitLyX();
89 extern LyXServer * lyxserver;
91 // This is the global bufferlist object
92 BufferList bufferlist;
94 // convenient to have it here.
95 boost::scoped_ptr<kb_keymap> toplevel_keymap;
99 void showFileError(string const & error)
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));
110 boost::scoped_ptr<LyX> LyX::singleton_;
112 void LyX::exec(int & argc, char * argv[])
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);
126 BOOST_ASSERT(singleton_.get());
127 return *singleton_.get();
131 LyX const & LyX::cref()
133 BOOST_ASSERT(singleton_.get());
134 return *singleton_.get();
143 LastFiles & LyX::lastfiles()
145 BOOST_ASSERT(lastfiles_.get());
146 return *lastfiles_.get();
150 LastFiles const & LyX::lastfiles() const
152 BOOST_ASSERT(lastfiles_.get());
153 return *lastfiles_.get();
157 void LyX::addLyXView(boost::shared_ptr<LyXView> const & lyxview)
159 views_.push_back(lyxview);
163 Buffer const * const LyX::updateInset(InsetOld const * inset) const
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);
180 void LyX::priv_exec(int & argc, char * argv[])
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);
187 lyx_gui::parse_init(argc, argv);
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."),
199 // Initialization of LyX (reads lyxrc and more)
200 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
202 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
205 lyx_gui::parse_lyxrc();
207 vector<string> files;
209 for (int argi = argc - 1; argi >= 1; --argi)
210 files.push_back(argv[argi]);
213 files.push_back(i18nLibFileSearch("examples", "splash.lyx"));
215 // Execute batch commands if available
216 if (!batch_command.empty()) {
218 lyxerr[Debug::INIT] << "About to handle -x '"
219 << batch_command << '\'' << endl;
221 Buffer * last_loaded = 0;
223 vector<string>::const_iterator it = files.begin();
224 vector<string>::const_iterator end = files.end();
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");
231 last_loaded = newFile(*it, string(), true);
233 Buffer * buf = bufferlist.newBuffer(s, false);
234 buf->error.connect(boost::bind(&LyX::printError, this, _1));
235 if (loadLyXFile(buf, s))
238 bufferlist.release(buf);
242 // try to dispatch to last loaded buffer first
244 bool success = false;
245 if (last_loaded->dispatch(batch_command, &success)) {
250 files.clear(); // the files are already loaded
253 lyx_gui::start(batch_command, files);
259 static void error_handler(int err_sig)
263 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
269 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
272 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
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;
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
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);
299 LyX::cref().emergencyCleanup();
301 lyxerr << "Bye." << endl;
302 if (err_sig!= SIGHUP &&
303 (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
304 lyx::support::abort();
311 void LyX::printError(ErrorItem const & ei)
313 std::cerr << _("LyX: ") << ei.error
314 << ':' << ei.description << std::endl;
319 void LyX::init(bool gui)
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);
328 bool const explicit_userdir = setLyxPaths();
330 // Check that user LyX directory is ok. We don't do that if
331 // running in batch mode.
333 queryUserLyXDir(explicit_userdir);
338 // Disable gui when easyparse says so
339 lyx_gui::use_gui = gui;
341 if (lyxrc.template_path.empty()) {
342 lyxrc.template_path = AddPath(system_lyxdir(), "templates");
345 if (lyxrc.lastfiles.empty()) {
346 lyxrc.lastfiles = AddName(user_lyxdir(), "lastfiles");
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();
357 // Read configuration files
360 readRcFile("lyxrc.defaults");
361 system_lyxrc = lyxrc;
362 system_formats = formats;
363 system_converters = converters;
364 system_lcolor = lcolor;
366 string prefsfile = "preferences";
367 // back compatibility to lyxs < 1.1.6
368 if (LibFileSearch(string(), prefsfile).empty())
370 if (!LibFileSearch(string(), prefsfile).empty())
371 readRcFile(prefsfile);
373 readEncodingsFile("encodings");
374 readLanguagesFile("languages");
377 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
382 toplevel_keymap.reset(new kb_keymap);
383 defaultKeyBindings(toplevel_keymap.get());
384 toplevel_keymap->read(lyxrc.bind_file);
387 readUIFile(lyxrc.ui_file);
390 if (lyxerr.debugging(Debug::LYXRC))
393 os::setTmpDir(CreateLyXTmpDir(lyxrc.tempdir_path));
394 if (lyxerr.debugging(Debug::INIT)) {
395 lyxerr << "LyX tmp dir: `" << os::getTmpDir() << '\'' << endl;
398 lyxerr[Debug::INIT] << "Reading lastfiles `"
399 << lyxrc.lastfiles << "'..." << endl;
400 lastfiles_.reset(new LastFiles(lyxrc.lastfiles,
401 lyxrc.check_lastfiles,
402 lyxrc.num_lastfiles));
406 void LyX::defaultKeyBindings(kb_keymap * kbmap)
408 kbmap->bind("Right", FuncRequest(LFUN_RIGHT));
409 kbmap->bind("Left", FuncRequest(LFUN_LEFT));
410 kbmap->bind("Up", FuncRequest(LFUN_UP));
411 kbmap->bind("Down", FuncRequest(LFUN_DOWN));
413 kbmap->bind("Tab", FuncRequest(LFUN_CELL_FORWARD));
414 kbmap->bind("ISO_Left_Tab", FuncRequest(LFUN_CELL_FORWARD));
416 kbmap->bind("Home", FuncRequest(LFUN_HOME));
417 kbmap->bind("End", FuncRequest(LFUN_END));
418 kbmap->bind("Prior", FuncRequest(LFUN_PRIOR));
419 kbmap->bind("Next", FuncRequest(LFUN_NEXT));
421 kbmap->bind("Return", FuncRequest(LFUN_BREAKPARAGRAPH));
422 //kbmap->bind("~C-~S-~M-nobreakspace", FuncRequest(LFUN_PROTECTEDSPACE));
424 kbmap->bind("Delete", FuncRequest(LFUN_DELETE));
425 kbmap->bind("BackSpace", FuncRequest(LFUN_BACKSPACE));
427 // sub- and superscript -MV
428 kbmap->bind("~S-underscore", FuncRequest(LFUN_SUBSCRIPT));
429 kbmap->bind("~S-asciicircum", FuncRequest(LFUN_SUPERSCRIPT));
431 // kbmap->bindings to enable the use of the numeric keypad
433 //kbmap->bind("KP_0", FuncRequest(LFUN_SELFINSERT));
434 //kbmap->bind("KP_Decimal", FuncRequest(LFUN_SELFINSERT));
435 kbmap->bind("KP_Enter", FuncRequest(LFUN_BREAKPARAGRAPH));
436 //kbmap->bind("KP_1", FuncRequest(LFUN_SELFINSERT));
437 //kbmap->bind("KP_2", FuncRequest(LFUN_SELFINSERT));
438 //kbmap->bind("KP_3", FuncRequest(LFUN_SELFINSERT));
439 //kbmap->bind("KP_4", FuncRequest(LFUN_SELFINSERT));
440 //kbmap->bind("KP_5", FuncRequest(LFUN_SELFINSERT));
441 //kbmap->bind("KP_6", FuncRequest(LFUN_SELFINSERT));
442 //kbmap->bind("KP_Add", FuncRequest(LFUN_SELFINSERT));
443 //kbmap->bind("KP_7", FuncRequest(LFUN_SELFINSERT));
444 //kbmap->bind("KP_8", FuncRequest(LFUN_SELFINSERT));
445 //kbmap->bind("KP_9", FuncRequest(LFUN_SELFINSERT));
446 //kbmap->bind("KP_Divide", FuncRequest(LFUN_SELFINSERT));
447 //kbmap->bind("KP_Multiply", FuncRequest(LFUN_SELFINSERT));
448 //kbmap->bind("KP_Subtract", FuncRequest(LFUN_SELFINSERT));
449 kbmap->bind("KP_Right", FuncRequest(LFUN_RIGHT));
450 kbmap->bind("KP_Left", FuncRequest(LFUN_LEFT));
451 kbmap->bind("KP_Up", FuncRequest(LFUN_UP));
452 kbmap->bind("KP_Down", FuncRequest(LFUN_DOWN));
453 kbmap->bind("KP_Home", FuncRequest(LFUN_HOME));
454 kbmap->bind("KP_End", FuncRequest(LFUN_END));
455 kbmap->bind("KP_Prior", FuncRequest(LFUN_PRIOR));
456 kbmap->bind("KP_Next", FuncRequest(LFUN_NEXT));
458 kbmap->bind("C-Tab", FuncRequest(LFUN_CELL_SPLIT));
459 kbmap->bind("S-Tab", FuncRequest(LFUN_CELL_BACKWARD));
460 kbmap->bind("S-ISO_Left_Tab", FuncRequest(LFUN_CELL_BACKWARD));
464 void LyX::emergencyCleanup() const
466 // what to do about tmpfiles is non-obvious. we would
467 // like to delete any we find, but our lyxdir might
468 // contain documents etc. which might be helpful on
471 bufferlist.emergencyWriteAll();
473 lyxserver->emergencyCleanup();
477 void LyX::deadKeyBindings(kb_keymap * kbmap)
479 // bindKeyings for transparent handling of deadkeys
480 // The keysyms are gotten from XFree86 X11R6
481 kbmap->bind("~C-~S-~M-dead_acute", FuncRequest(LFUN_ACUTE));
482 kbmap->bind("~C-~S-~M-dead_breve", FuncRequest(LFUN_BREVE));
483 kbmap->bind("~C-~S-~M-dead_caron", FuncRequest(LFUN_CARON));
484 kbmap->bind("~C-~S-~M-dead_cedilla", FuncRequest(LFUN_CEDILLA));
485 kbmap->bind("~C-~S-~M-dead_abovering", FuncRequest(LFUN_CIRCLE));
486 kbmap->bind("~C-~S-~M-dead_circumflex", FuncRequest(LFUN_CIRCUMFLEX));
487 kbmap->bind("~C-~S-~M-dead_abovedot", FuncRequest(LFUN_DOT));
488 kbmap->bind("~C-~S-~M-dead_grave", FuncRequest(LFUN_GRAVE));
489 kbmap->bind("~C-~S-~M-dead_doubleacute", FuncRequest(LFUN_HUNG_UMLAUT));
490 kbmap->bind("~C-~S-~M-dead_macron", FuncRequest(LFUN_MACRON));
491 // nothing with this name
492 // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
493 kbmap->bind("~C-~S-~M-dead_tilde", FuncRequest(LFUN_TILDE));
494 kbmap->bind("~C-~S-~M-dead_diaeresis", FuncRequest(LFUN_UMLAUT));
495 // nothing with this name either...
496 //kbmap->bind("~C-~S-~M-dead_underbar", FuncRequest(LFUN_UNDERBAR));
497 kbmap->bind("~C-~S-~M-dead_belowdot", FuncRequest(LFUN_UNDERDOT));
498 kbmap->bind("~C-~S-~M-dead_tie", FuncRequest(LFUN_TIE));
499 kbmap->bind("~C-~S-~M-dead_ogonek",FuncRequest(LFUN_OGONEK));
503 void LyX::queryUserLyXDir(bool explicit_userdir)
505 string const configure_script = AddName(system_lyxdir(), "configure");
507 // Does user directory exist?
508 FileInfo fileInfo(user_lyxdir());
509 if (fileInfo.isOK() && fileInfo.isDir()) {
511 FileInfo script(configure_script);
512 FileInfo defaults(AddName(user_lyxdir(), "lyxrc.defaults"));
513 if (defaults.isOK() && script.isOK()
514 && defaults.getModificationTime() < script.getModificationTime()) {
515 lyxerr << _("LyX: reconfiguring user directory")
517 Path p(user_lyxdir());
518 ::system(configure_script.c_str());
519 lyxerr << "LyX: " << _("Done!") << endl;
524 first_start = !explicit_userdir;
526 lyxerr << bformat(_("LyX: Creating directory %1$s"
527 " and running configure..."), user_lyxdir()) << endl;
529 if (!createDirectory(user_lyxdir(), 0755)) {
530 // Failed, let's use $HOME instead.
531 user_lyxdir(GetEnvPath("HOME"));
532 lyxerr << bformat(_("Failed. Will use %1$s instead."),
533 user_lyxdir()) << endl;
537 // Run configure in user lyx directory
538 Path p(user_lyxdir());
539 ::system(configure_script.c_str());
540 lyxerr << "LyX: " << _("Done!") << endl;
544 void LyX::readRcFile(string const & name)
546 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
548 string const lyxrc_path = LibFileSearch(string(), name);
549 if (!lyxrc_path.empty()) {
551 lyxerr[Debug::INIT] << "Found " << name
552 << " in " << lyxrc_path << endl;
554 if (lyxrc.read(lyxrc_path) >= 0)
562 // Read the ui file `name'
563 void LyX::readUIFile(string const & name)
573 struct keyword_item uitags[ui_last - 1] = {
574 { "include", ui_include },
575 { "menuset", ui_menuset },
576 { "toolbar", ui_toolbar },
577 { "toolbars", ui_toolbars }
580 // Ensure that a file is read only once (prevents include loops)
581 static std::list<string> uifiles;
582 std::list<string>::const_iterator it = uifiles.begin();
583 std::list<string>::const_iterator end = uifiles.end();
584 it = std::find(it, end, name);
586 lyxerr[Debug::INIT] << "UI file '" << name
587 << "' has been read already. "
588 << "Is this an include loop?"
593 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
595 string const ui_path = LibFileSearch("ui", name, "ui");
597 if (ui_path.empty()) {
598 lyxerr[Debug::INIT] << "Could not find " << name << endl;
602 uifiles.push_back(name);
604 lyxerr[Debug::INIT] << "Found " << name
605 << " in " << ui_path << endl;
606 LyXLex lex(uitags, ui_last - 1);
607 lex.setFile(ui_path);
609 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
613 if (lyxerr.debugging(Debug::PARSER))
614 lex.printTable(lyxerr);
620 string const file = lex.getString();
625 menubackend.read(lex);
629 toolbarbackend.read(lex);
633 toolbarbackend.readToolbars(lex);
637 if (!rtrim(lex.getString()).empty())
638 lex.printError("LyX::ReadUIFile: "
639 "Unknown menu tag: `$$Token'");
646 // Read the languages file `name'
647 void LyX::readLanguagesFile(string const & name)
649 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
651 string const lang_path = LibFileSearch(string(), name);
652 if (lang_path.empty()) {
656 languages.read(lang_path);
660 // Read the encodings file `name'
661 void LyX::readEncodingsFile(string const & name)
663 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
665 string const enc_path = LibFileSearch(string(), name);
666 if (enc_path.empty()) {
670 encodings.read(enc_path);
679 /// return the the number of arguments consumed
680 typedef boost::function<int(string const &, string const &)> cmd_helper;
682 int parse_dbg(string const & arg, string const &)
685 lyxerr << _("List of supported debug flags:") << endl;
686 Debug::showTags(lyxerr);
689 lyxerr << bformat(_("Setting debug level to %1$s"), arg) << endl;
691 lyxerr.level(Debug::value(arg));
692 Debug::showLevel(lyxerr, lyxerr.level());
697 int parse_help(string const &, string const &)
700 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
701 "Command line switches (case sensitive):\n"
702 "\t-help summarize LyX usage\n"
703 "\t-userdir dir try to set user directory to dir\n"
704 "\t-sysdir dir try to set system directory to dir\n"
705 "\t-geometry WxH+X+Y set geometry of the main window\n"
706 "\t-dbg feature[,feature]...\n"
707 " select the features to debug.\n"
708 " Type `lyx -dbg' to see the list of features\n"
709 "\t-x [--execute] command\n"
710 " where command is a lyx command.\n"
711 "\t-e [--export] fmt\n"
712 " where fmt is the export format of choice.\n"
713 "\t-i [--import] fmt file.xxx\n"
714 " where fmt is the import format of choice\n"
715 " and file.xxx is the file to be imported.\n"
716 "\t-version summarize version and build info\n"
717 "Check the LyX man page for more details.") << endl;
722 int parse_version(string const &, string const &)
724 lyxerr << "LyX " << lyx_version
725 << " of " << lyx_release_date << endl;
726 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
728 lyxerr << lyx_version_info << endl;
733 int parse_sysdir(string const & arg, string const &)
736 lyxerr << _("Missing directory for -sysdir switch") << endl;
743 int parse_userdir(string const & arg, string const &)
746 lyxerr << _("Missing directory for -userdir switch") << endl;
753 int parse_execute(string const & arg, string const &)
756 lyxerr << _("Missing command string after --execute switch") << endl;
760 // Argh. Setting gui to false segfaults..
761 // FIXME: when ? how ?
766 int parse_export(string const & type, string const &)
769 lyxerr << _("Missing file type [eg latex, ps...] after "
770 "--export switch") << endl;
773 batch = "buffer-export " + type;
778 int parse_import(string const & type, string const & file)
781 lyxerr << _("Missing file type [eg latex, ps...] after "
782 "--import switch") << endl;
786 lyxerr << _("Missing filename for --import") << endl;
790 batch = "buffer-import " + type + ' ' + file;
797 bool LyX::easyParse(int & argc, char * argv[])
799 std::map<string, cmd_helper> cmdmap;
801 cmdmap["-dbg"] = parse_dbg;
802 cmdmap["-help"] = parse_help;
803 cmdmap["--help"] = parse_help;
804 cmdmap["-version"] = parse_version;
805 cmdmap["--version"] = parse_version;
806 cmdmap["-sysdir"] = parse_sysdir;
807 cmdmap["-userdir"] = parse_userdir;
808 cmdmap["-x"] = parse_execute;
809 cmdmap["--execute"] = parse_execute;
810 cmdmap["-e"] = parse_export;
811 cmdmap["--export"] = parse_export;
812 cmdmap["-i"] = parse_import;
813 cmdmap["--import"] = parse_import;
815 for (int i = 1; i < argc; ++i) {
816 std::map<string, cmd_helper>::const_iterator it
817 = cmdmap.find(argv[i]);
819 // don't complain if not found - may be parsed later
820 if (it == cmdmap.end())
823 string arg((i + 1 < argc) ? argv[i + 1] : "");
824 string arg2((i + 2 < argc) ? argv[i + 2] : "");
826 int const remove = 1 + it->second(arg, arg2);
828 // Now, remove used arguments by shifting
829 // the following ones remove places down.
831 for (int j = i; j < argc; ++j)
832 argv[j] = argv[j + remove];
836 batch_command = batch;