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"
28 #include "lyxserver.h"
31 #include "ToolbarDefaults.h"
32 #include "MenuBackend.h"
34 #include "lastfiles.h"
36 #include "converter.h"
37 #include "lyxtextclasslist.h"
39 #include "frontends/Alert.h"
40 #include "frontends/lyx_gui.h"
48 #ifndef CXX_GLOBAL_CSTD
54 extern void LoadLyXFile(string const &);
55 extern void QuitLyX();
57 extern LyXServer * lyxserver;
61 string system_tempdir;
66 boost::scoped_ptr<LastFiles> lastfiles;
68 // This is the global bufferlist object
69 BufferList bufferlist;
71 // convenient to have it here.
72 boost::scoped_ptr<kb_keymap> toplevel_keymap;
75 LyX::LyX(int & argc, char * argv[])
77 // Here we need to parse the command line. At least
78 // we need to parse for "-dbg" and "-help"
79 bool const want_gui = easyParse(argc, argv);
81 // Global bindings (this must be done as early as possible.) (Lgb)
82 toplevel_keymap.reset(new kb_keymap);
83 defaultKeyBindings(toplevel_keymap.get());
86 lyx_gui::parse_init(argc, argv);
89 // check for any spurious extra arguments
90 // other than documents
91 for (int argi = 1; argi < argc ; ++argi) {
92 if (argv[argi][0] == '-') {
93 lyxerr << _("Wrong command line option `")
95 << _("'. Exiting.") << endl;
100 // Initialization of LyX (reads lyxrc and more)
101 lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
103 lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
106 lyx_gui::parse_lyxrc();
109 vector<string> files;
111 for (int argi = argc - 1; argi >= 1; --argi) {
112 files.push_back(argv[argi]);
116 files.push_back(i18nLibFileSearch("examples", "splash.lyx"));
120 // Execute batch commands if available
121 if (!batch_command.empty()) {
122 lyxerr[Debug::INIT] << "About to handle -x '"
123 << batch_command << "'" << endl;
125 // no buffer loaded, create one
127 last_loaded = bufferlist.newFile("tmpfile", string());
129 bool success = false;
131 // try to dispatch to last loaded buffer first
132 bool const dispatched = last_loaded->dispatch(batch_command, &success);
134 // if this was successful, finish
142 lyx_gui::start(batch_command, files);
149 void error_handler(int err_sig)
153 lyxerr << "\nlyx: SIGHUP signal caught" << endl;
159 lyxerr << "\nlyx: SIGFPE signal caught" << endl;
162 lyxerr << "\nlyx: SIGSEGV signal caught" << endl;
164 "Sorry, you have found a bug in LyX. "
165 "Please read the bug-reporting instructions "
166 "in Help->Introduction and send us a bug report, "
167 "if necessary. Thanks !" << endl;
174 // Deinstall the signal handlers
175 signal(SIGHUP, SIG_DFL);
176 signal(SIGINT, SIG_DFL);
177 signal(SIGFPE, SIG_DFL);
178 signal(SIGSEGV, SIG_DFL);
179 signal(SIGTERM, SIG_DFL);
181 LyX::emergencyCleanup();
183 lyxerr << "Bye." << endl;
184 if (err_sig!= SIGHUP &&
185 (!GetEnv("LYXDEBUG").empty() || err_sig == SIGSEGV))
193 void LyX::init(bool gui)
195 // Install the signal handlers
196 signal(SIGHUP, error_handler);
197 signal(SIGFPE, error_handler);
198 signal(SIGSEGV, error_handler);
199 signal(SIGINT, error_handler);
200 signal(SIGTERM, error_handler);
203 // Determine path of binary
206 string binpath = os::binpath();
207 string binname = os::binname();
208 string fullbinname = MakeAbsPath(binname, binpath);
210 if (binpath.empty()) {
211 lyxerr << _("Warning: could not determine path of binary.")
213 << _("If you have problems, try starting LyX with an absolute path.")
216 lyxerr[Debug::INIT] << "Name of binary: " << binname << endl;
217 lyxerr[Debug::INIT] << "Path of binary: " << binpath << endl;
220 // Determine system directory.
223 // Directories are searched in this order:
224 // 1) -sysdir command line parameter
225 // 2) LYX_DIR_13x environment variable
226 // 3) Maybe <path of binary>/TOP_SRCDIR/lib
227 // 4) <path of binary>/../share/<name of binary>/
228 // 4a) repeat 4 after following the Symlink if <path of
229 // binary> is a symbolic link.
230 // 5) hardcoded lyx_dir
231 // The directory is checked for the presence of the file
232 // "chkconfig.ltx", and if that is present, the directory
233 // is accepted as the system directory.
234 // If no chkconfig.ltx file is found, a warning is given,
235 // and the hardcoded lyx_dir is used.
237 // If we had a command line switch, system_lyxdir is already set
239 if (!system_lyxdir.empty())
240 searchpath = MakeAbsPath(system_lyxdir) + ';';
242 // LYX_DIR_13x environment variable
243 string const lyxdir = GetEnvPath("LYX_DIR_13x");
245 if (!lyxdir.empty()) {
246 lyxerr[Debug::INIT] << "LYX_DIR_13x: " << lyxdir << endl;
247 searchpath += lyxdir + ';';
250 string fullbinpath = binpath;
251 FileInfo file(fullbinname, true);
253 lyxerr[Debug::INIT] << "binary is a link" << endl;
255 if (LyXReadLink(fullbinname, link, true)) {
256 // Path of binary/../share/name of binary/
257 searchpath += NormalizePath(AddPath(binpath,
259 + OnlyFilename(binname));
262 binpath = MakeAbsPath(OnlyPath(fullbinpath));
268 // Path of binary/../share/name of binary/
269 searchpath += NormalizePath(AddPath(binpath, "../share/") +
270 OnlyFilename(binname)) + ';';
273 FileInfo file(fullbinpath, true);
274 followlink = file.isLink();
276 lyxerr << " directory " << fullbinpath
277 << " is a link" << endl;
279 if (LyXReadLink(fullbinpath, link, true)) {
281 binpath = MakeAbsPath(OnlyPath(fullbinpath));
287 } while (followlink);
289 // <path of binary>/TOP_SRCDIR/lib
290 build_lyxdir = MakeAbsPath("../lib", binpath);
291 if (!FileSearch(build_lyxdir, "lyxrc.defaults").empty()) {
292 searchpath += MakeAbsPath(AddPath(TOP_SRCDIR, "lib"),
294 lyxerr[Debug::INIT] << "Checking whether LyX is run in "
295 "place... yes" << endl;
298 << "Checking whether LyX is run in place... no"
300 build_lyxdir.erase();
304 searchpath += LYX_DIR;
306 // If debugging, show complete search path
307 lyxerr[Debug::INIT] << "System directory search path: "
308 << searchpath << endl;
310 string const filename = "chkconfig.ltx";
311 string const temp = FileOpenSearch(searchpath, filename, string());
312 system_lyxdir = OnlyPath(temp);
314 // Reduce "path/../path" stuff out of system directory
315 system_lyxdir = NormalizePath(system_lyxdir);
317 bool path_shown = false;
319 // Warn if environment variable is set, but unusable
320 if (!lyxdir.empty()) {
321 if (system_lyxdir != NormalizePath(lyxdir)) {
322 lyxerr <<_("LYX_DIR_13x environment variable no good.")
324 << _("System directory set to: ")
325 << system_lyxdir << endl;
330 // Warn the user if we couldn't find "chkconfig.ltx"
331 if (system_lyxdir == "./") {
332 lyxerr <<_("LyX Warning! Couldn't determine system directory. ")
333 <<_("Try the '-sysdir' command line parameter or ")
334 <<_("set the environment variable LYX_DIR_13x to the "
335 "LyX system directory ")
336 << _("containing the file `chkconfig.ltx'.") << endl;
338 FileInfo fi(LYX_DIR);
340 lyxerr << "Couldn't even find the default LYX_DIR." << endl
341 << "Giving up." << endl;
344 lyxerr << _("Using built-in default ")
345 << LYX_DIR << _(" but expect problems.")
348 lyxerr << _("Expect problems.") << endl;
350 system_lyxdir = LYX_DIR;
353 // Report the system directory if debugging is on
355 lyxerr[Debug::INIT] << "System directory: '"
356 << system_lyxdir << '\'' << endl;
359 // Determine user lyx-dir
362 // Directories are searched in this order:
363 // 1) -userdir command line parameter
364 // 2) LYX_USERDIR_13x environment variable
365 // 3) $HOME/.<name of binary>
367 // If we had a command line switch, user_lyxdir is already set
368 bool explicit_userdir = true;
369 if (user_lyxdir.empty()) {
371 // LYX_USERDIR_13x environment variable
372 user_lyxdir = GetEnvPath("LYX_USERDIR_13x");
375 if (user_lyxdir.empty())
376 user_lyxdir = AddPath(GetEnvPath("HOME"),
377 string(".") + PACKAGE);
378 explicit_userdir = false;
381 lyxerr[Debug::INIT] << "User LyX directory: '"
382 << user_lyxdir << '\'' << endl;
384 // Check that user LyX directory is ok. We don't do that if
385 // running in batch mode.
387 queryUserLyXDir(explicit_userdir);
393 // Shine up lyxrc defaults
396 // Default template path: system_dir/templates
397 if (lyxrc.template_path.empty()) {
398 lyxrc.template_path = AddPath(system_lyxdir, "templates");
401 // Default lastfiles file: $HOME/.lyx/lastfiles
402 if (lyxrc.lastfiles.empty()) {
403 lyxrc.lastfiles = AddName(user_lyxdir, "lastfiles");
406 // Disable gui when either lyxrc or easyparse says so
408 lyxrc.use_gui = false;
411 // Read configuration files
414 readRcFile("lyxrc.defaults");
415 system_lyxrc = lyxrc;
416 system_formats = formats;
417 system_converters = converters;
418 system_lcolor = lcolor;
420 // If there is a preferences file we read that instead
421 // of the old lyxrc file.
422 if (!readRcFile("preferences"))
426 readEncodingsFile("encodings");
428 readLanguagesFile("languages");
431 lyxerr[Debug::INIT] << "Reading layouts..." << endl;
434 // Ensure that we have really read a bind file, so that LyX is
436 lyxrc.readBindFileIfNeeded();
439 readUIFile(lyxrc.ui_file);
441 // Bind the X dead keys to the corresponding LyX functions if
443 if (lyxrc.override_x_deadkeys)
444 deadKeyBindings(toplevel_keymap.get());
446 if (lyxerr.debugging(Debug::LYXRC)) {
450 // Create temp directory
451 os::setTmpDir(CreateLyXTmpDir(lyxrc.tempdir_path));
452 system_tempdir = os::getTmpDir();
453 if (lyxerr.debugging(Debug::INIT)) {
454 lyxerr << "LyX tmp dir: `" << system_tempdir << '\'' << endl;
457 // load the lastfiles mini-database
458 lyxerr[Debug::INIT] << "Reading lastfiles `"
459 << lyxrc.lastfiles << "'..." << endl;
460 lastfiles.reset(new LastFiles(lyxrc.lastfiles,
461 lyxrc.check_lastfiles,
462 lyxrc.num_lastfiles));
466 // These are the default bindings known to LyX
467 void LyX::defaultKeyBindings(kb_keymap * kbmap)
469 kbmap->bind("Right", LFUN_RIGHT);
470 kbmap->bind("Left", LFUN_LEFT);
471 kbmap->bind("Up", LFUN_UP);
472 kbmap->bind("Down", LFUN_DOWN);
474 kbmap->bind("Tab", LFUN_TAB);
475 kbmap->bind("ISO_Left_Tab", LFUN_TAB); // jbl 2001-23-02
477 kbmap->bind("Home", LFUN_HOME);
478 kbmap->bind("End", LFUN_END);
479 kbmap->bind("Prior", LFUN_PRIOR);
480 kbmap->bind("Next", LFUN_NEXT);
482 kbmap->bind("Return", LFUN_BREAKPARAGRAPH);
483 //kbmap->bind("~C-~S-~M-nobreakspace", LFUN_PROTECTEDSPACE);
485 kbmap->bind("Delete", LFUN_DELETE);
486 kbmap->bind("BackSpace", LFUN_BACKSPACE);
488 // sub- and superscript -MV
489 kbmap->bind("~S-underscore", LFUN_SUBSCRIPT);
490 kbmap->bind("~S-asciicircum", LFUN_SUPERSCRIPT);
492 // kbmap->bindings to enable the use of the numeric keypad
494 //kbmap->bind("KP_0", LFUN_SELFINSERT);
495 //kbmap->bind("KP_Decimal", LFUN_SELFINSERT);
496 kbmap->bind("KP_Enter", LFUN_BREAKPARAGRAPH);
497 //kbmap->bind("KP_1", LFUN_SELFINSERT);
498 //kbmap->bind("KP_2", LFUN_SELFINSERT);
499 //kbmap->bind("KP_3", LFUN_SELFINSERT);
500 //kbmap->bind("KP_4", LFUN_SELFINSERT);
501 //kbmap->bind("KP_5", LFUN_SELFINSERT);
502 //kbmap->bind("KP_6", LFUN_SELFINSERT);
503 //kbmap->bind("KP_Add", LFUN_SELFINSERT);
504 //kbmap->bind("KP_7", LFUN_SELFINSERT);
505 //kbmap->bind("KP_8", LFUN_SELFINSERT);
506 //kbmap->bind("KP_9", LFUN_SELFINSERT);
507 //kbmap->bind("KP_Divide", LFUN_SELFINSERT);
508 //kbmap->bind("KP_Multiply", LFUN_SELFINSERT);
509 //kbmap->bind("KP_Subtract", LFUN_SELFINSERT);
510 kbmap->bind("KP_Right", LFUN_RIGHT);
511 kbmap->bind("KP_Left", LFUN_LEFT);
512 kbmap->bind("KP_Up", LFUN_UP);
513 kbmap->bind("KP_Down", LFUN_DOWN);
514 kbmap->bind("KP_Home", LFUN_HOME);
515 kbmap->bind("KP_End", LFUN_END);
516 kbmap->bind("KP_Prior", LFUN_PRIOR);
517 kbmap->bind("KP_Next", LFUN_NEXT);
519 kbmap->bind("C-Tab", LFUN_TABINSERT); // ale970515
520 kbmap->bind("S-Tab", LFUN_SHIFT_TAB); // jug20000522
521 kbmap->bind("S-ISO_Left_Tab", LFUN_SHIFT_TAB); // jbl 2001-23-02
525 void LyX::emergencyCleanup()
527 // what to do about tmpfiles is non-obvious. we would
528 // like to delete any we find, but our lyxdir might
529 // contain documents etc. which might be helpful on
532 bufferlist.emergencyWriteAll();
534 lyxserver->emergencyCleanup();
538 // LyX can optionally take over the handling of deadkeys
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 // This one is not allowed to use anything on the main form, since that
566 // one does not exist yet. (Asger)
567 void LyX::queryUserLyXDir(bool explicit_userdir)
569 // Does user directory exist?
570 FileInfo fileInfo(user_lyxdir);
571 if (fileInfo.isOK() && fileInfo.isDir()) {
575 first_start = !explicit_userdir;
578 // If the user specified explicitely a directory, ask whether
579 // to create it (otherwise, always create it)
580 if (explicit_userdir &&
581 !Alert::askQuestion(_("You have specified an invalid LyX directory."),
582 _("It is needed to keep your own configuration."),
583 _("Should I try to set it up for you (recommended)?"))) {
584 lyxerr << _("Running without personal LyX directory.") << endl;
585 // No, let's use $HOME instead.
586 user_lyxdir = GetEnvPath("HOME");
590 // Tell the user what is going on
591 lyxerr << _("LyX: Creating directory ") << user_lyxdir
592 << _(" and running configure...") << endl;
594 // Create directory structure
595 if (!createDirectory(user_lyxdir, 0755)) {
596 // Failed, let's use $HOME instead.
597 user_lyxdir = GetEnvPath("HOME");
598 lyxerr << _("Failed. Will use ") << user_lyxdir
599 << _(" instead.") << endl;
603 // Run configure in user lyx directory
605 ::system(AddName(system_lyxdir, "configure").c_str());
606 lyxerr << "LyX: " << _("Done!") << endl;
610 // Read the rc file `name'
611 bool LyX::readRcFile(string const & name)
613 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
615 string const lyxrc_path = LibFileSearch(string(), name);
616 if (!lyxrc_path.empty()) {
617 lyxerr[Debug::INIT] << "Found " << name
618 << " in " << lyxrc_path << endl;
619 if (lyxrc.read(lyxrc_path) < 0) {
620 Alert::alert(_("LyX Warning!"),
621 _("Error while reading ") + lyxrc_path + ".",
622 _("Using built-in defaults."));
627 lyxerr[Debug::INIT] << "Could not find " << name << endl;
634 // Read the ui file `name'
635 void LyX::readUIFile(string const & name)
643 struct keyword_item uitags[ui_last-1] = {
644 { "menuset", ui_menuset },
645 { "toolbar", ui_toolbar }
648 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
650 string const ui_path = LibFileSearch("ui", name, "ui");
652 if (ui_path.empty()) {
653 lyxerr[Debug::INIT] << "Could not find " << name << endl;
654 menubackend.defaults();
658 lyxerr[Debug::INIT] << "Found " << name
659 << " in " << ui_path << endl;
660 LyXLex lex(uitags, ui_last - 1);
661 lex.setFile(ui_path);
663 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
667 if (lyxerr.debugging(Debug::PARSER))
668 lex.printTable(lyxerr);
673 menubackend.read(lex);
677 toolbardefaults.read(lex);
681 if (!rtrim(lex.getString()).empty())
682 lex.printError("LyX::ReadUIFile: "
683 "Unknown menu tag: `$$Token'");
690 // Read the languages file `name'
691 void LyX::readLanguagesFile(string const & name)
693 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
695 string const lang_path = LibFileSearch(string(), name);
696 if (lang_path.empty()) {
697 lyxerr[Debug::INIT] << "Could not find " << name << endl;
698 languages.setDefaults();
701 languages.read(lang_path);
705 // Read the encodings file `name'
706 void LyX::readEncodingsFile(string const & name)
708 lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
710 string const enc_path = LibFileSearch(string(), name);
711 if (enc_path.empty()) {
712 lyxerr[Debug::INIT] << "Could not find " << name << endl;
715 encodings.read(enc_path);
721 // Set debugging level and report result to user
722 void setDebuggingLevel(string const & dbgLevel)
724 lyxerr << _("Setting debug level to ") << dbgLevel << endl;
725 lyxerr.level(Debug::value(dbgLevel));
726 Debug::showLevel(lyxerr, lyxerr.level());
730 // Give command line help
731 void commandLineHelp()
734 _("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
735 "Command line switches (case sensitive):\n"
736 "\t-help summarize LyX usage\n"
737 "\t-userdir dir try to set user directory to dir\n"
738 "\t-sysdir dir try to set system directory to dir\n"
739 "\t-geometry WxH+X+Y set geometry of the main window\n"
740 "\t-dbg feature[,feature]...\n"
741 " select the features to debug.\n"
742 " Type `lyx -dbg' to see the list of features\n"
743 "\t-x [--execute] command\n"
744 " where command is a lyx command.\n"
745 "\t-e [--export] fmt\n"
746 " where fmt is the export format of choice.\n"
747 "\t-i [--import] fmt file.xxx\n"
748 " where fmt is the import format of choice\n"
749 " and file.xxx is the file to be imported.\n"
750 "\t-version summarize version and build info\n"
751 "Check the LyX man page for more details.") << endl;
754 // Give command line version information
755 void commandLineVersionInfo()
757 lyxerr << "LyX " << lyx_version
758 << " of " << lyx_release_date << endl;
759 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
761 lyxerr << lyx_version_info << endl;
768 bool LyX::easyParse(int & argc, char * argv[])
771 int removeargs = 0; // used when options are read
772 for (int i = 1; i < argc; ++i) {
773 string arg = argv[i];
775 // Check for -dbg int
778 setDebuggingLevel(argv[i + 1]);
781 lyxerr << _("List of supported debug flags:")
783 Debug::showTags(lyxerr);
787 // Check for "-sysdir"
788 else if (arg == "-sysdir") {
790 system_lyxdir = argv[i + 1];
793 lyxerr << _("Missing directory for -sysdir switch!")
798 // Check for "-userdir"
799 else if (arg == "-userdir") {
801 user_lyxdir = argv[i + 1];
804 lyxerr << _("Missing directory for -userdir switch!")
809 // Check for --help or -help
810 else if (arg == "--help" || arg == "-help") {
814 // Check for --version or -version
815 else if (arg == "--version" || arg == "-version") {
816 commandLineVersionInfo();
819 // FIXME: why is this commented out ?
820 // Check for "-nw": No XWindows as for emacs this should
821 // give a LyX that could be used in a terminal window.
822 //else if (arg == "-nw") {
826 // Check for "-x": Execute commands
827 else if (arg == "-x" || arg == "--execute") {
829 batch_command = string(argv[i + 1]);
833 lyxerr << _("Missing command string after -x switch!") << endl;
835 // Argh. Setting gui to false segfaults..
836 // FIXME: when ? how ?
840 else if (arg == "-e" || arg == "--export") {
842 string type(argv[i+1]);
844 batch_command = "buffer-export " + type;
847 lyxerr << _("Missing file type [eg latex, "
849 << arg << _(" switch!") << endl;
853 else if (arg == "-i" || arg == "--import") {
856 lyxerr << _("Missing filename for --import") << endl;
860 string const file(argv[i+2]);
861 string const type(argv[i+1]);
864 batch_command = "buffer-import " + type + " " + file;
865 lyxerr << "batch_command: "
866 << batch_command << endl;
869 lyxerr << _("Missing type [eg latex, "
871 << arg << _(" switch!") << endl;
876 if (removeargs > 0) {
877 // Now, remove used arguments by shifting
878 // the following ones removeargs places down.
880 for (int j = i; j < argc; ++j)
881 argv[j] = argv[j + removeargs];
882 --i; // After shift, check this number again.