3 * Copyright 1995-2002 the LyX Team
4 * Read the file COPYING
13 #pragma implementation
18 #include "support/filetools.h"
19 #include "support/lyxlib.h"
20 #include "support/os.h"
21 #include "support/FileInfo.h"
22 #include "support/path.h"
27 #include "bufferlist.h"
29 #include "lyxserver.h"
32 #include "ToolbarDefaults.h"
33 #include "MenuBackend.h"
35 #include "lastfiles.h"
37 #include "converter.h"
38 #include "lyxtextclasslist.h"
40 #include "frontends/Alert.h"
41 #include "frontends/lyx_gui.h"
43 #include <boost/function.hpp>
51 #ifndef CXX_GLOBAL_CSTD
57 extern void LoadLyXFile(string const &);
58 extern void QuitLyX();
60 extern LyXServer * lyxserver;
64 string system_tempdir;
69 boost::scoped_ptr<LastFiles> lastfiles;
71 // This is the global bufferlist object
72 BufferList bufferlist;
74 // convenient to have it here.
75 boost::scoped_ptr<kb_keymap> toplevel_keymap;
78 LyX::LyX(int & argc, char * argv[])
80 // Here we need to parse the command line. At least
81 // we need to parse for "-dbg" and "-help"
82 bool const want_gui = easyParse(argc, argv);
84 // Global bindings (this must be done as early as possible.) (Lgb)
85 toplevel_keymap.reset(new kb_keymap);
86 defaultKeyBindings(toplevel_keymap.get());
89 lyx_gui::parse_init(argc, argv);
92 // check for any spurious extra arguments
93 // other than documents
94 for (int argi = 1; argi < argc ; ++argi) {
95 if (argv[argi][0] == '-') {
96 lyxerr << _("Wrong command line option `")
98 << _("'. Exiting.") << endl;
103 // Initialization of LyX (reads lyxrc and more)
104 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
106 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
109 lyx_gui::parse_lyxrc();
112 vector<string> files;
114 for (int argi = argc - 1; argi >= 1; --argi) {
115 files.push_back(argv[argi]);
119 files.push_back(i18nLibFileSearch("examples", "splash.lyx"));
122 // Execute batch commands if available
123 if (!batch_command.empty()) {
124 lyxerr[Debug::INIT] << "About to handle -x '"
125 << batch_command << "'" << endl;
127 Buffer * last_loaded = 0;
129 vector<string>::iterator it = files.begin();
130 vector<string>::iterator end = files.end();
131 for (; it != end; ++it) {
132 last_loaded = bufferlist.loadLyXFile(*it);
137 // no buffer loaded, create one
139 last_loaded = bufferlist.newFile("tmpfile", string());
141 bool success = false;
143 // try to dispatch to last loaded buffer first
144 bool const dispatched = last_loaded->dispatch(batch_command, &success);
152 lyx_gui::start(batch_command, files);
158 static void error_handler(int err_sig)
162 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
168 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
171 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
173 "Sorry, you have found a bug in LyX. "
174 "Please read the bug-reporting instructions "
175 "in Help->Introduction and send us a bug report, "
176 "if necessary. Thanks !" << endl;
183 // Deinstall the signal handlers
184 signal(SIGHUP, SIG_DFL);
185 signal(SIGINT, SIG_DFL);
186 signal(SIGFPE, SIG_DFL);
187 signal(SIGSEGV, SIG_DFL);
188 signal(SIGTERM, SIG_DFL);
190 LyX::emergencyCleanup();
192 lyxerr << "Bye." << endl;
193 if (err_sig!= SIGHUP &&
194 (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
202 void LyX::init(bool gui)
204 signal(SIGHUP, error_handler);
205 signal(SIGFPE, error_handler);
206 signal(SIGSEGV, error_handler);
207 signal(SIGINT, error_handler);
208 signal(SIGTERM, error_handler);
211 // Determine path of binary
214 string binpath = os::binpath();
215 string binname = os::binname();
216 string fullbinname = MakeAbsPath(binname, binpath);
218 if (binpath.empty()) {
219 lyxerr << _("Warning: could not determine path of binary.")
221 << _("If you have problems, try starting LyX with an absolute path.")
224 lyxerr[Debug::INIT] << "Name of binary: " << binname << endl;
225 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
228 // Determine system directory.
231 // Directories are searched in this order:
232 // 1) -sysdir command line parameter
233 // 2) LYX_DIR_13x environment variable
234 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
235 // 4) <path of binary>/../share/<name of binary>/
236 // 4a) repeat 4 after following the Symlink if <path of
237 // binary> is a symbolic link.
238 // 5) hardcoded lyx_dir
239 // The directory is checked for the presence of the file
240 // "chkconfig.ltx", and if that is present, the directory
241 // is accepted as the system directory.
242 // If no chkconfig.ltx file is found, a warning is given,
243 // and the hardcoded lyx_dir is used.
245 // If we had a command line switch, system_lyxdir is already set
247 if (!system_lyxdir.empty())
248 searchpath = MakeAbsPath(system_lyxdir) + ';';
250 string const lyxdir = GetEnvPath("LYX_DIR_13x");
252 if (!lyxdir.empty()) {
253 lyxerr[Debug::INIT] << "LYX_DIR_13x: " << lyxdir << endl;
254 searchpath += lyxdir + ';';
257 string fullbinpath = binpath;
258 FileInfo file(fullbinname, true);
260 lyxerr[Debug::INIT] << "binary is a link" << endl;
262 if (LyXReadLink(fullbinname, link, true)) {
263 // Path of binary/../share/name of binary/
264 searchpath += NormalizePath(AddPath(binpath,
266 + OnlyFilename(binname));
269 binpath = MakeAbsPath(OnlyPath(fullbinpath));
275 // Path of binary/../share/name of binary/
276 searchpath += NormalizePath(AddPath(binpath, "../share/") +
277 OnlyFilename(binname)) + ';';
280 FileInfo file(fullbinpath, true);
281 followlink = file.isLink();
283 lyxerr << " directory " << fullbinpath
284 << " is a link" << endl;
286 if (LyXReadLink(fullbinpath, link, true)) {
288 binpath = MakeAbsPath(OnlyPath(fullbinpath));
294 } while (followlink);
296 // <path of binary>/TOP_SRCDIR/lib
297 build_lyxdir = MakeAbsPath("../lib", binpath);
298 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
299 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
301 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
302 "place... yes" << endl;
305 << "Checking whether LyX is run in place... no"
307 build_lyxdir.erase();
311 searchpath += LYX_DIR;
313 lyxerr[Debug::INIT] << "System directory search path: "
314 << searchpath << endl;
316 string const filename = "chkconfig.ltx";
317 string const temp = FileOpenSearch(searchpath, filename, string());
318 system_lyxdir = OnlyPath(temp);
320 // Reduce "path/../path" stuff out of system directory
321 system_lyxdir = NormalizePath(system_lyxdir);
323 bool path_shown = false;
325 // Warn if environment variable is set, but unusable
326 if (!lyxdir.empty()) {
327 if (system_lyxdir != NormalizePath(lyxdir)) {
328 lyxerr <<_("LYX_DIR_13x environment variable no good.")
330 << _("System directory set to: ")
331 << system_lyxdir << endl;
336 // Warn the user if we couldn't find "chkconfig.ltx"
337 if (system_lyxdir == "./") {
338 lyxerr <<_("LyX Warning! Couldn't determine system directory. ")
339 <<_("Try the '-sysdir' command line parameter or ")
340 <<_("set the environment variable LYX_DIR_13x to the "
341 "LyX system directory ")
342 << _("containing the file `chkconfig.ltx'.") << endl;
344 FileInfo fi(LYX_DIR);
346 lyxerr << "Couldn't even find the default LYX_DIR." << endl
347 << "Giving up." << endl;
350 lyxerr << _("Using built-in default ")
351 << LYX_DIR << _(" but expect problems.")
354 lyxerr << _("Expect problems.") << endl;
356 system_lyxdir = LYX_DIR;
361 lyxerr[Debug::INIT] << "System directory: '"
362 << system_lyxdir << '\'' << endl;
365 // Determine user lyx-dir
368 // Directories are searched in this order:
369 // 1) -userdir command line parameter
370 // 2) LYX_USERDIR_13x environment variable
371 // 3) $HOME/.<name of binary>
373 // If we had a command line switch, user_lyxdir is already set
374 bool explicit_userdir = true;
375 if (user_lyxdir.empty()) {
377 // LYX_USERDIR_13x environment variable
378 user_lyxdir = GetEnvPath("LYX_USERDIR_13x");
381 if (user_lyxdir.empty())
382 user_lyxdir = AddPath(GetEnvPath("HOME"),
383 string(".") + PACKAGE);
384 explicit_userdir = false;
387 lyxerr[Debug::INIT] << "User LyX directory: '"
388 << user_lyxdir << '\'' << endl;
390 // Check that user LyX directory is ok. We don't do that if
391 // running in batch mode.
393 queryUserLyXDir(explicit_userdir);
399 // Shine up lyxrc defaults
402 // Default template path: system_dir/templates
403 if (lyxrc.template_path.empty()) {
404 lyxrc.template_path = AddPath(system_lyxdir, "templates");
407 // Default lastfiles file: $HOME/.lyx/lastfiles
408 if (lyxrc.lastfiles.empty()) {
409 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
412 // Disable gui when either lyxrc or easyparse says so
414 lyxrc.use_gui = false;
417 // Read configuration files
420 readRcFile("lyxrc.defaults");
421 system_lyxrc = lyxrc;
422 system_formats = formats;
423 system_converters = converters;
424 system_lcolor = lcolor;
426 // If there is a preferences file we read that instead
427 // of the old lyxrc file.
428 if (!readRcFile("preferences"))
431 readEncodingsFile("encodings");
432 readLanguagesFile("languages");
435 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
438 // Ensure that we have really read a bind file, so that LyX is
440 lyxrc.readBindFileIfNeeded();
443 readUIFile(lyxrc.ui_file);
445 // Bind the X dead keys to the corresponding LyX functions if
447 if (lyxrc.override_x_deadkeys)
448 deadKeyBindings(toplevel_keymap.get());
450 if (lyxerr.debugging(Debug::LYXRC)) {
454 os::setTmpDir(CreateLyXTmpDir(lyxrc.tempdir_path));
455 system_tempdir = os::getTmpDir();
456 if (lyxerr.debugging(Debug::INIT)) {
457 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
460 lyxerr[Debug::INIT] << "Reading lastfiles `"
461 << lyxrc.lastfiles << "'..." << endl;
462 lastfiles.reset(new LastFiles(lyxrc.lastfiles,
463 lyxrc.check_lastfiles,
464 lyxrc.num_lastfiles));
468 void LyX::defaultKeyBindings(kb_keymap * kbmap)
470 kbmap->bind("Right", LFUN_RIGHT);
471 kbmap->bind("Left", LFUN_LEFT);
472 kbmap->bind("Up", LFUN_UP);
473 kbmap->bind("Down", LFUN_DOWN);
475 kbmap->bind("Tab", LFUN_TAB);
476 kbmap->bind("ISO_Left_Tab", LFUN_TAB); // jbl 2001-23-02
478 kbmap->bind("Home", LFUN_HOME);
479 kbmap->bind("End", LFUN_END);
480 kbmap->bind("Prior", LFUN_PRIOR);
481 kbmap->bind("Next", LFUN_NEXT);
483 kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
484 //kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
486 kbmap->bind("Delete", LFUN_DELETE);
487 kbmap->bind("BackSpace", LFUN_BACKSPACE);
489 // sub- and superscript -MV
490 kbmap->bind("~S-underscore", LFUN_SUBSCRIPT);
491 kbmap->bind("~S-asciicircum", LFUN_SUPERSCRIPT);
493 // kbmap->bindings to enable the use of the numeric keypad
495 //kbmap->bind("KP_0", LFUN_SELFINSERT);
496 //kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
497 kbmap->bind("KP_Enter", LFUN_BREAKPARAGRAPH);
498 //kbmap->bind("KP_1", LFUN_SELFINSERT);
499 //kbmap->bind("KP_2", LFUN_SELFINSERT);
500 //kbmap->bind("KP_3", LFUN_SELFINSERT);
501 //kbmap->bind("KP_4", LFUN_SELFINSERT);
502 //kbmap->bind("KP_5", LFUN_SELFINSERT);
503 //kbmap->bind("KP_6", LFUN_SELFINSERT);
504 //kbmap->bind("KP_Add", LFUN_SELFINSERT);
505 //kbmap->bind("KP_7", LFUN_SELFINSERT);
506 //kbmap->bind("KP_8", LFUN_SELFINSERT);
507 //kbmap->bind("KP_9", LFUN_SELFINSERT);
508 //kbmap->bind("KP_Divide", LFUN_SELFINSERT);
509 //kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
510 //kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
511 kbmap->bind("KP_Right", LFUN_RIGHT);
512 kbmap->bind("KP_Left", LFUN_LEFT);
513 kbmap->bind("KP_Up", LFUN_UP);
514 kbmap->bind("KP_Down", LFUN_DOWN);
515 kbmap->bind("KP_Home", LFUN_HOME);
516 kbmap->bind("KP_End", LFUN_END);
517 kbmap->bind("KP_Prior", LFUN_PRIOR);
518 kbmap->bind("KP_Next", LFUN_NEXT);
520 kbmap->bind("C-Tab", LFUN_TABINSERT); // ale970515
521 kbmap->bind("S-Tab", LFUN_SHIFT_TAB); // jug20000522
522 kbmap->bind("S-ISO_Left_Tab", LFUN_SHIFT_TAB); // jbl 2001-23-02
526 void LyX::emergencyCleanup()
528 // what to do about tmpfiles is non-obvious. we would
529 // like to delete any we find, but our lyxdir might
530 // contain documents etc. which might be helpful on
533 bufferlist.emergencyWriteAll();
535 lyxserver->emergencyCleanup();
539 void LyX::deadKeyBindings(kb_keymap * kbmap)
541 // bindKeyings for transparent handling of deadkeys
542 // The keysyms are gotten from XFree86 X11R6
543 kbmap->bind("~C-~S-~M-dead_acute", LFUN_ACUTE);
544 kbmap->bind("~C-~S-~M-dead_breve", LFUN_BREVE);
545 kbmap->bind("~C-~S-~M-dead_caron", LFUN_CARON);
546 kbmap->bind("~C-~S-~M-dead_cedilla", LFUN_CEDILLA);
547 kbmap->bind("~C-~S-~M-dead_abovering", LFUN_CIRCLE);
548 kbmap->bind("~C-~S-~M-dead_circumflex", LFUN_CIRCUMFLEX);
549 kbmap->bind("~C-~S-~M-dead_abovedot", LFUN_DOT);
550 kbmap->bind("~C-~S-~M-dead_grave", LFUN_GRAVE);
551 kbmap->bind("~C-~S-~M-dead_doubleacute", LFUN_HUNG_UMLAUT);
552 kbmap->bind("~C-~S-~M-dead_macron", LFUN_MACRON);
553 // nothing with this name
554 // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_SPECIAL_CARON);
555 kbmap->bind("~C-~S-~M-dead_tilde", LFUN_TILDE);
556 kbmap->bind("~C-~S-~M-dead_diaeresis", LFUN_UMLAUT);
557 // nothing with this name either...
558 //kbmap->bind("~C-~S-~M-dead_underbar", LFUN_UNDERBAR);
559 kbmap->bind("~C-~S-~M-dead_belowdot", LFUN_UNDERDOT);
560 kbmap->bind("~C-~S-~M-dead_tie", LFUN_TIE);
561 kbmap->bind("~C-~S-~M-dead_ogonek", LFUN_OGONEK);
565 void LyX::queryUserLyXDir(bool explicit_userdir)
567 // Does user directory exist?
568 FileInfo fileInfo(user_lyxdir);
569 if (fileInfo.isOK() && fileInfo.isDir()) {
574 first_start = !explicit_userdir;
576 // If the user specified explicitly a directory, ask whether
577 // to create it (otherwise, always create it)
578 if (explicit_userdir &&
579 !Alert::askQuestion(_("You have specified an invalid LyX directory."),
580 _("It is needed to keep your own configuration."),
581 _("Should I try to set it up for you (recommended)?"))) {
582 lyxerr << _("Running without personal LyX directory.") << endl;
583 // No, let's use $HOME instead.
584 user_lyxdir = GetEnvPath("HOME");
588 lyxerr << _("LyX: Creating directory ") << user_lyxdir
589 << _(" and running configure...") << endl;
591 if (!createDirectory(user_lyxdir, 0755)) {
592 // Failed, let's use $HOME instead.
593 user_lyxdir = GetEnvPath("HOME");
594 lyxerr << _("Failed. Will use ") << user_lyxdir
595 << _(" instead.") << endl;
599 // Run configure in user lyx directory
601 ::system(AddName(system_lyxdir, "configure").c_str());
602 lyxerr << "LyX: " << _("Done!") << endl;
606 bool LyX::readRcFile(string const & name)
608 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
610 string const lyxrc_path = LibFileSearch(string(), name);
611 if (!lyxrc_path.empty()) {
612 lyxerr[Debug::INIT] << "Found " << name
613 << " in " << lyxrc_path << endl;
614 if (lyxrc.read(lyxrc_path) < 0) {
615 Alert::alert(_("LyX Warning!"),
616 _("Error while reading ") + lyxrc_path + ".",
617 _("Using built-in defaults."));
622 lyxerr[Debug::INIT] << "Could not find " << name << endl;
629 // Read the ui file `name'
630 void LyX::readUIFile(string const & name)
638 struct keyword_item uitags[ui_last - 1] = {
639 { "menuset", ui_menuset },
640 { "toolbar", ui_toolbar }
643 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
645 string const ui_path = LibFileSearch("ui", name, "ui");
647 if (ui_path.empty()) {
648 lyxerr[Debug::INIT] << "Could not find " << name << endl;
649 menubackend.defaults();
653 lyxerr[Debug::INIT] << "Found " << name
654 << " in " << ui_path << endl;
655 LyXLex lex(uitags, ui_last - 1);
656 lex.setFile(ui_path);
658 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
662 if (lyxerr.debugging(Debug::PARSER))
663 lex.printTable(lyxerr);
668 menubackend.read(lex);
672 toolbardefaults.read(lex);
676 if (!rtrim(lex.getString()).empty())
677 lex.printError("LyX::ReadUIFile: "
678 "Unknown menu tag: `$$Token'");
685 // Read the languages file `name'
686 void LyX::readLanguagesFile(string const & name)
688 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
690 string const lang_path = LibFileSearch(string(), name);
691 if (lang_path.empty()) {
692 lyxerr[Debug::INIT] << "Could not find " << name << endl;
693 languages.setDefaults();
696 languages.read(lang_path);
700 // Read the encodings file `name'
701 void LyX::readEncodingsFile(string const & name)
703 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
705 string const enc_path = LibFileSearch(string(), name);
706 if (enc_path.empty()) {
707 lyxerr[Debug::INIT] << "Could not find " << name << endl;
710 encodings.read(enc_path);
719 /// return the the number of arguments consumed
720 typedef boost::function<int, string const &, string const &> cmd_helper;
722 int parse_dbg(string const & arg, string const &)
725 lyxerr << _("List of supported debug flags:") << endl;
726 Debug::showTags(lyxerr);
729 lyxerr << _("Setting debug level to ") << arg << endl;
730 lyxerr.level(Debug::value(arg));
731 Debug::showLevel(lyxerr, lyxerr.level());
735 int parse_help(string const &, string const &)
738 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
739 "Command line switches (case sensitive):\n"
740 "\t-help summarize LyX usage\n"
741 "\t-userdir dir try to set user directory to dir\n"
742 "\t-sysdir dir try to set system directory to dir\n"
743 "\t-geometry WxH+X+Y set geometry of the main window\n"
744 "\t-dbg feature[,feature]...\n"
745 " select the features to debug.\n"
746 " Type `lyx -dbg' to see the list of features\n"
747 "\t-x [--execute] command\n"
748 " where command is a lyx command.\n"
749 "\t-e [--export] fmt\n"
750 " where fmt is the export format of choice.\n"
751 "\t-i [--import] fmt file.xxx\n"
752 " where fmt is the import format of choice\n"
753 " and file.xxx is the file to be imported.\n"
754 "\t-version summarize version and build info\n"
755 "Check the LyX man page for more details.") << endl;
760 int parse_version(string const &, string const &)
762 lyxerr << "LyX " << lyx_version
763 << " of " << lyx_release_date << endl;
764 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
766 lyxerr << lyx_version_info << endl;
771 int parse_sysdir(string const & arg, string const &)
774 lyxerr << _("Missing directory for -sysdir switch") << endl;
781 int parse_userdir(string const & arg, string const &)
784 lyxerr << _("Missing directory for -userdir switch") << endl;
791 int parse_execute(string const & arg, string const &)
794 lyxerr << _("Missing command string after --execute switch") << endl;
798 // Argh. Setting gui to false segfaults..
799 // FIXME: when ? how ?
804 int parse_export(string const & type, string const &)
807 lyxerr << _("Missing file type [eg latex, ps...] after "
808 "--export switch") << endl;
811 batch = "buffer-export " + type;
816 int parse_import(string const & type, string const & file)
819 lyxerr << _("Missing file type [eg latex, ps...] after "
820 "--import switch") << endl;
824 lyxerr << _("Missing filename for --import") << endl;
828 batch = "buffer-import " + type + " " + file;
835 bool LyX::easyParse(int & argc, char * argv[])
837 std::map<string, cmd_helper> cmdmap;
839 cmdmap["-dbg"] = parse_dbg;
840 cmdmap["-help"] = parse_help;
841 cmdmap["--help"] = parse_help;
842 cmdmap["-version"] = parse_version;
843 cmdmap["--version"] = parse_version;
844 cmdmap["-sysdir"] = parse_sysdir;
845 cmdmap["-userdir"] = parse_userdir;
846 cmdmap["-x"] = parse_execute;
847 cmdmap["--execute"] = parse_execute;
848 cmdmap["-e"] = parse_export;
849 cmdmap["--export"] = parse_export;
850 cmdmap["-i"] = parse_import;
851 cmdmap["--import"] = parse_import;
853 for (int i = 1; i < argc; ++i) {
854 std::map<string, cmd_helper>::const_iterator it
855 = cmdmap.find(argv[i]);
857 // don't complain if not found - may be parsed later
858 if (it == cmdmap.end())
861 string arg((i + 1 < argc) ? argv[i + 1] : "");
862 string arg2((i + 2 < argc) ? argv[i + 2] : "");
864 int const remove = 1 + it->second(arg, arg2);
866 // Now, remove used arguments by shifting
867 // the following ones remove places down.
869 for (int j = i; j < argc; ++j)
870 argv[j] = argv[j + remove];
874 batch_command = batch;