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.
20 #include "AppleSpellChecker.h"
21 #include "AspellChecker.h"
23 #include "BufferList.h"
26 #include "ConverterCache.h"
27 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "EnchantChecker.h"
31 #include "ErrorList.h"
33 #include "FuncStatus.h"
34 #include "HunspellChecker.h"
37 #include "LaTeXFonts.h"
38 #include "LayoutFile.h"
41 #include "LyXAction.h"
43 #include "ModuleList.h"
46 #include "ServerSocket.h"
50 #include "frontends/alert.h"
51 #include "frontends/Application.h"
53 #include "support/ConsoleApplication.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/environment.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/filetools.h"
59 #include "support/gettext.h"
60 #include "support/lstrings.h"
61 #include "support/Messages.h"
62 #include "support/os.h"
63 #include "support/Package.h"
65 #include "support/bind.h"
66 #include <boost/scoped_ptr.hpp>
77 using namespace lyx::support;
79 #if defined (USE_MACOSX_PACKAGING)
80 #include <crt_externs.h>
85 namespace Alert = frontend::Alert;
86 namespace os = support::os;
90 // Are we using the GUI at all? We default to true and this is changed
91 // to false when the export feature is used.
96 // We default to open documents in an already running instance, provided that
97 // the lyxpipe has been setup. This can be overridden either on the command
98 // line or through preference settings.
100 RunMode run_mode = PREFERRED;
103 // Tell what files can be silently overwritten during batch export.
104 // Possible values are: NO_FILES, MAIN_FILE, ALL_FILES, UNSPECIFIED.
105 // Unless specified on command line (through the -f switch) or through the
106 // environment variable LYX_FORCE_OVERWRITE, the default will be MAIN_FILE.
108 OverwriteFiles force_overwrite = UNSPECIFIED;
113 // Filled with the command line arguments "foo" of "-sysdir foo" or
115 string cl_system_support;
116 string cl_user_support;
120 LyX * singleton_ = 0;
122 void showFileError(string const & error)
124 Alert::warning(_("Could not read configuration file"),
125 bformat(_("Error while reading the configuration file\n%1$s.\n"
126 "Please check your installation."), from_utf8(error)));
131 /// The main application class private implementation.
134 : latexfonts_(0), spell_checker_(0), apple_spell_checker_(0), aspell_checker_(0), enchant_checker_(0), hunspell_checker_(0)
140 delete apple_spell_checker_;
141 delete aspell_checker_;
142 delete enchant_checker_;
143 delete hunspell_checker_;
147 BufferList buffer_list_;
149 KeyMap toplevel_keymap_;
151 CmdDef toplevel_cmddef_;
153 boost::scoped_ptr<Server> lyx_server_;
155 boost::scoped_ptr<ServerSocket> lyx_socket_;
157 boost::scoped_ptr<frontend::Application> application_;
158 /// lyx session, containing lastfiles, lastfilepos, and lastopened
159 boost::scoped_ptr<Session> session_;
161 /// Files to load at start.
162 vector<string> files_to_load_;
164 /// The messages translators.
165 map<string, Messages> messages_;
167 /// The file converters.
168 Converters converters_;
170 // The system converters copy after reading lyxrc.defaults.
171 Converters system_converters_;
176 Movers system_movers_;
178 /// has this user started lyx for the first time?
180 /// the parsed command line batch command if any
181 vector<string> batch_commands;
184 LaTeXFonts * latexfonts_;
187 SpellChecker * spell_checker_;
189 SpellChecker * apple_spell_checker_;
191 SpellChecker * aspell_checker_;
193 SpellChecker * enchant_checker_;
195 SpellChecker * hunspell_checker_;
199 /// The main application class for console mode
200 class LyXConsoleApp : public ConsoleApplication
203 LyXConsoleApp(LyX * lyx, int & argc, char * argv[])
204 : ConsoleApplication(lyx_package, argc, argv), lyx_(lyx),
205 argc_(argc), argv_(argv)
210 int const exit_status = lyx_->execWithoutGui(argc_, argv_);
221 frontend::Application * theApp()
224 return singleton_->pimpl_->application_.get();
234 WordList::cleanupWordLists();
238 void lyx_exit(int exit_code)
241 // Something wrong happened so better save everything, just in
246 // Properly crash in debug mode in order to get a useful backtrace.
250 // In release mode, try to exit gracefully.
252 theApp()->exit(exit_code);
266 Messages & LyX::messages(string const & language)
268 map<string, Messages>::iterator it = pimpl_->messages_.find(language);
270 if (it != pimpl_->messages_.end())
273 pair<map<string, Messages>::iterator, bool> result =
274 pimpl_->messages_.insert(make_pair(language, Messages(language)));
276 LATTEST(result.second);
277 return result.first->second;
281 int LyX::exec(int & argc, char * argv[])
283 // Minimal setting of locale before parsing command line
285 init_package(os::utf8_argv(0), string(), string());
286 // we do not get to this point when init_package throws an exception
288 } catch (ExceptionMessage const & message) {
289 LYXERR(Debug::LOCALE, message.title_ + ", " + message.details_);
292 // Here we need to parse the command line. At least
293 // we need to parse for "-dbg" and "-help"
294 easyParse(argc, argv);
297 init_package(os::utf8_argv(0), cl_system_support, cl_user_support);
298 } catch (ExceptionMessage const & message) {
299 if (message.type_ == ErrorException) {
300 Alert::error(message.title_, message.details_);
302 } else if (message.type_ == WarningException) {
303 Alert::warning(message.title_, message.details_);
307 // Reinit the messages machinery in case package() knows
308 // something interesting about the locale directory.
312 LyXConsoleApp app(this, argc, argv);
314 // Reestablish our defaults, as Qt overwrites them
315 // after creating app
321 // Let the frontend parse and remove all arguments that it knows
322 pimpl_->application_.reset(createApplication(argc, argv));
324 // Reestablish our defaults, as Qt overwrites them
325 // after createApplication()
328 // Parse and remove all known arguments in the LyX singleton
329 // Give an error for all remaining ones.
330 int exit_status = init(argc, argv);
332 // Kill the application object before exiting.
333 pimpl_->application_.reset();
339 // If not otherwise specified by a command line option or
340 // by preferences, we default to reuse a running instance.
341 if (run_mode == PREFERRED)
342 run_mode = USE_REMOTE;
345 /* Create a CoreApplication class that will provide the main event loop
346 * and the socket callback registering. With Qt, only QtCore
347 * library would be needed.
348 * When this is done, a server_mode could be created and the following two
349 * line would be moved out from here.
350 * However, note that the first of the two lines below triggers the
351 * "single instance" behavior, which should occur right at this point.
353 // Note: socket callback must be registered after init(argc, argv)
354 // such that package().temp_dir() is properly initialized.
355 pimpl_->lyx_server_.reset(new Server(lyxrc.lyxpipes));
356 pimpl_->lyx_socket_.reset(new ServerSocket(
357 FileName(package().temp_dir().absFileName() + "/lyxsocket")));
359 // Start the real execution loop.
360 if (!theServer().deferredLoadingToOtherInstance())
361 exit_status = pimpl_->application_->exec();
362 else if (!pimpl_->files_to_load_.empty()) {
363 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
364 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
365 lyxerr << _("The following files could not be loaded:") << endl;
366 for (; it != end; ++it)
367 lyxerr << *it << endl;
376 void LyX::prepareExit()
378 // Clear the clipboard and selection stack:
379 cap::clearCutStack();
380 cap::clearSelection();
382 // Write the index file of the converter cache
383 ConverterCache::get().writeIndex();
385 // close buffers first
386 pimpl_->buffer_list_.closeAll();
388 // register session changes and shutdown server and socket
390 if (pimpl_->session_)
391 pimpl_->session_->writeFile();
392 pimpl_->session_.reset();
393 pimpl_->lyx_server_.reset();
394 pimpl_->lyx_socket_.reset();
397 // do any other cleanup procedures now
398 if (package().temp_dir() != package().system_temp_dir()) {
399 string const abs_tmpdir = package().temp_dir().absFileName();
400 if (!contains(package().temp_dir().absFileName(), "lyx_tmpdir")) {
401 docstring const msg =
402 bformat(_("%1$s does not appear like a LyX created temporary directory."),
403 from_utf8(abs_tmpdir));
404 Alert::warning(_("Cannot remove temporary directory"), msg);
406 LYXERR(Debug::INFO, "Deleting tmp dir "
407 << package().temp_dir().absFileName());
408 if (!package().temp_dir().destroyDirectory()) {
409 docstring const msg =
410 bformat(_("Unable to remove the temporary directory %1$s"),
411 from_utf8(package().temp_dir().absFileName()));
412 Alert::warning(_("Unable to remove temporary directory"), msg);
417 // Kill the application object before exiting. This avoids crashes
418 // when exiting on Linux.
419 pimpl_->application_.reset();
423 void LyX::earlyExit(int status)
425 LATTEST(pimpl_->application_.get());
426 // LyX::pimpl_::application_ is not initialised at this
427 // point so it's safe to just exit after some cleanup.
433 int LyX::init(int & argc, char * argv[])
435 // check for any spurious extra arguments
436 // other than documents
437 for (int argi = 1; argi < argc ; ++argi) {
438 if (argv[argi][0] == '-') {
440 bformat(_("Wrong command line option `%1$s'. Exiting."),
441 from_utf8(os::utf8_argv(argi)))) << endl;
446 // Initialization of LyX (reads lyxrc and more)
447 LYXERR(Debug::INIT, "Initializing LyX::init...");
448 bool success = init();
449 LYXERR(Debug::INIT, "Initializing LyX::init...done");
453 // Remaining arguments are assumed to be files to load.
454 for (int argi = 1; argi < argc; ++argi)
455 pimpl_->files_to_load_.push_back(os::utf8_argv(argi));
457 if (!use_gui && pimpl_->files_to_load_.empty()) {
458 lyxerr << to_utf8(_("Missing filename for this operation.")) << endl;
463 pimpl_->files_to_load_.push_back(
464 i18nLibFileSearch("examples", "splash.lyx").absFileName());
471 int LyX::execWithoutGui(int & argc, char * argv[])
473 int exit_status = init(argc, argv);
479 // this is correct, since return values are inverted.
480 exit_status = !loadFiles();
482 if (pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
487 BufferList::iterator begin = pimpl_->buffer_list_.begin();
489 bool final_success = false;
490 for (BufferList::iterator I = begin; I != pimpl_->buffer_list_.end(); ++I) {
492 if (buf != buf->masterBuffer())
494 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
495 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
497 for (; bcit != bcend; ++bcit) {
498 LYXERR(Debug::ACTION, "Buffer::dispatch: cmd: " << *bcit);
499 buf->dispatch(*bcit, dr);
500 final_success |= !dr.error();
504 return !final_success;
508 bool LyX::loadFiles()
512 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
513 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
515 for (; it != end; ++it) {
516 // get absolute path of file and add ".lyx" to
517 // the filename if necessary
518 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
524 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFileName());
525 if (buf->loadLyXFile() == Buffer::ReadSuccess) {
526 ErrorList const & el = buf->errorList("Parse");
528 for_each(el.begin(), el.end(),
529 bind(&LyX::printError, this, _1));
532 pimpl_->buffer_list_.release(buf);
533 docstring const error_message =
534 bformat(_("LyX failed to load the following file: %1$s"),
535 from_utf8(fname.absFileName()));
536 lyxerr << to_utf8(error_message) << endl;
544 void execBatchCommands()
547 singleton_->execCommands();
551 void LyX::execCommands()
553 // The advantage of doing this here is that the event loop
554 // is already started. So any need for interaction will be
557 // if reconfiguration is needed.
558 if (LayoutFileList::get().empty()) {
559 switch (Alert::prompt(
560 _("No textclass is found"),
561 _("LyX will only have minimal functionality because no textclasses "
562 "have been found. You can either try to reconfigure LyX normally, "
563 "try to reconfigure without checking your LaTeX installation, or continue."),
570 // regular reconfigure
571 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
574 // reconfigure --without-latex-config
575 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE,
576 " --without-latex-config"));
583 // create the first main window
584 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
586 if (!pimpl_->files_to_load_.empty()) {
587 // if some files were specified at command-line we assume that the
588 // user wants to edit *these* files and not to restore the session.
589 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
591 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
593 // clear this list to save a few bytes of RAM
594 pimpl_->files_to_load_.clear();
596 pimpl_->application_->restoreGuiSession();
598 // Execute batch commands if available
599 if (pimpl_->batch_commands.empty())
602 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
603 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
604 for (; bcit != bcend; ++bcit) {
605 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
606 lyx::dispatch(lyxaction.lookupFunc(*bcit));
614 The SIGHUP signal does not exist on Windows and does not need to be handled.
616 Windows handles SIGFPE and SIGSEGV signals as expected.
618 Ctrl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
619 cause a new thread to be spawned. This may well result in unexpected
620 behaviour by the single-threaded LyX.
622 SIGTERM signals will come only from another process actually sending
623 that signal using 'raise' in Windows' POSIX compatability layer. It will
624 not come from the general "terminate process" methods that everyone
625 actually uses (and which can't be trapped). Killing an app 'politely' on
626 Windows involves first sending a WM_CLOSE message, something that is
627 caught already by the Qt frontend.
629 For more information see:
631 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
632 ...signals are mostly useless on Windows for a variety of reasons that are
635 'UNIX Application Migration Guide, Chapter 9'
636 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
638 'How To Terminate an Application "Cleanly" in Win32'
639 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
643 static void error_handler(int err_sig)
645 // Throw away any signals other than the first one received.
646 static sig_atomic_t handling_error = false;
649 handling_error = true;
651 // We have received a signal indicating a fatal error, so
652 // try and save the data ASAP.
655 // These lyxerr calls may or may not work:
657 // Signals are asynchronous, so the main program may be in a very
658 // fragile state when a signal is processed and thus while a signal
659 // handler function executes.
660 // In general, therefore, we should avoid performing any
661 // I/O operations or calling most library and system functions from
664 // This shouldn't matter here, however, as we've already invoked
670 msg = _("SIGHUP signal caught!\nBye.");
674 msg = _("SIGFPE signal caught!\nBye.");
677 msg = _("SIGSEGV signal caught!\n"
678 "Sorry, you have found a bug in LyX, "
679 "hope you have not lost any data.\n"
680 "Please read the bug-reporting instructions "
681 "in 'Help->Introduction' and send us a bug report, "
682 "if necessary. Thanks!\nBye.");
691 lyxerr << "\nlyx: " << msg << endl;
692 // try to make a GUI message
693 Alert::error(_("LyX crashed!"), msg, true);
696 // Deinstall the signal handlers
698 signal(SIGHUP, SIG_DFL);
700 signal(SIGINT, SIG_DFL);
701 signal(SIGFPE, SIG_DFL);
702 signal(SIGSEGV, SIG_DFL);
703 signal(SIGTERM, SIG_DFL);
706 if (err_sig == SIGSEGV ||
707 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty())) {
709 if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty()) {
712 // with abort() it crashes again.
725 void LyX::printError(ErrorItem const & ei)
727 docstring tmp = _("LyX: ") + ei.error + char_type(':')
729 cerr << to_utf8(tmp) << endl;
732 #if defined (USE_MACOSX_PACKAGING)
734 // Unexposed--extract an environment variable name from its NAME=VALUE
736 std::string varname(const char* line)
738 size_t nameLen = strcspn(line, "=");
739 if (nameLen == strlen(line)) {
740 return std::string();
742 return std::string(line, nameLen);
747 void cleanDuplicateEnvVars()
749 std::set<std::string> seen;
750 std::set<std::string> dupes;
752 // Create a list of the environment variables that appear more than once
753 for (char **read = *_NSGetEnviron(); *read; read++) {
754 std::string name = varname(*read);
755 if (name.size() == 0) {
758 if (seen.find(name) != seen.end()) {
765 // Loop over the list of duplicated variables
766 std::set<std::string>::iterator dupe = dupes.begin();
767 std::set<std::string>::iterator const dend = dupes.end();
768 for (; dupe != dend; ++dupe) {
769 const char *name = (*dupe).c_str();
770 char *val = getenv(name);
772 LYXERR(Debug::INIT, "Duplicate environment variable: " << name);
773 // unsetenv removes *all* instances of the variable from the environment
776 // replace with the value from getenv (in practice appears to be the
777 // first value in the list)
778 setenv(name, val, 0);
787 signal(SIGHUP, error_handler);
789 signal(SIGFPE, error_handler);
790 signal(SIGSEGV, error_handler);
791 signal(SIGINT, error_handler);
792 signal(SIGTERM, error_handler);
793 // SIGPIPE can be safely ignored.
795 #if defined (USE_MACOSX_PACKAGING)
796 cleanDuplicateEnvVars();
799 lyxrc.tempdir_path = package().temp_dir().absFileName();
800 lyxrc.document_path = package().document_dir().absFileName();
802 if (lyxrc.example_path.empty()) {
803 lyxrc.example_path = addPath(package().system_support().absFileName(),
806 if (lyxrc.template_path.empty()) {
807 lyxrc.template_path = addPath(package().system_support().absFileName(),
811 // init LyXDir environment variable
812 string const lyx_dir = package().lyx_dir().absFileName();
813 LYXERR(Debug::INIT, "Setting LyXDir... to \"" << lyx_dir << "\"");
814 if (!setEnv("LyXDir", lyx_dir))
815 LYXERR(Debug::INIT, "\t... failed!");
817 if (package().explicit_user_support() && getEnv(LYX_USERDIR_VER).empty()) {
818 // -userdir was given on the command line.
819 // Make it available to child processes, otherwise tex2lyx
820 // would not find all layout files, and other converters might
822 string const user_dir = package().user_support().absFileName();
823 LYXERR(Debug::INIT, "Setting " LYX_USERDIR_VER "... to \""
825 if (!setEnv(LYX_USERDIR_VER, user_dir))
826 LYXERR(Debug::INIT, "\t... failed!");
830 // Read configuration files
833 // This one may have been distributed along with LyX.
834 if (!readRcFile("lyxrc.dist"))
837 // Set the PATH correctly.
838 #if !defined (USE_POSIX_PACKAGING)
839 // Add the directory containing the LyX executable to the path
840 // so that LyX can find things like tex2lyx.
841 if (package().build_support().empty())
842 prependEnvPath("PATH", package().binary_dir().absFileName());
844 if (!lyxrc.path_prefix.empty())
845 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
847 // Check that user LyX directory is ok.
849 string const lock_file = package().getConfigureLockName();
850 int fd = fileLock(lock_file.c_str());
852 if (queryUserLyXDir(package().explicit_user_support())) {
853 package().reconfigureUserLyXDir("");
855 fileUnlock(fd, lock_file.c_str());
859 // No need for a splash when there is no GUI
861 // Default is to overwrite the main file during export, unless
862 // the -f switch was specified or LYX_FORCE_OVERWRITE was set
863 if (force_overwrite == UNSPECIFIED) {
864 string const what = getEnv("LYX_FORCE_OVERWRITE");
866 force_overwrite = ALL_FILES;
867 else if (what == "none")
868 force_overwrite = NO_FILES;
870 force_overwrite = MAIN_FILE;
874 // This one is generated in user_support directory by lib/configure.py.
875 if (!readRcFile("lyxrc.defaults"))
878 // Query the OS to know what formats are viewed natively
879 formats.setAutoOpen();
881 // Read lyxrc.dist again to be able to override viewer auto-detection.
882 readRcFile("lyxrc.dist");
884 system_lyxrc = lyxrc;
885 system_formats = formats;
886 pimpl_->system_converters_ = pimpl_->converters_;
887 pimpl_->system_movers_ = pimpl_->movers_;
888 system_lcolor = lcolor;
890 // This one is edited through the preferences dialog.
891 if (!readRcFile("preferences", true))
894 // The language may have been set to someting useful through prefs
897 if (!readEncodingsFile("encodings", "unicodesymbols"))
899 if (!readLanguagesFile("languages"))
902 LYXERR(Debug::INIT, "Reading layouts...");
904 LayoutFileList::get().read();
906 theModuleList.read();
908 // read keymap and ui files in batch mode as well
909 // because InsetInfo needs to know these to produce
910 // the correct output
912 // Set up command definitions
913 pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
917 pimpl_->toplevel_keymap_.read("site");
918 pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
919 // load user bind file user.bind
920 pimpl_->toplevel_keymap_.read("user", 0, KeyMap::MissingOK);
922 if (lyxerr.debugging(Debug::LYXRC))
925 os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
926 // Prepend path prefix a second time to take the user preferences into a account
927 if (!lyxrc.path_prefix.empty())
928 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
930 FileName const document_path(lyxrc.document_path);
931 if (document_path.exists() && document_path.isDirectory())
932 package().document_dir() = document_path;
934 package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
935 if (package().temp_dir().empty()) {
936 Alert::error(_("Could not create temporary directory"),
937 bformat(_("Could not create a temporary directory in\n"
939 "Make sure that this path exists and is writable and try again."),
940 from_utf8(lyxrc.tempdir_path)));
941 // createLyXTmpDir() tries sufficiently hard to create a
942 // usable temp dir, so the probability to come here is
943 // close to zero. We therefore don't try to overcome this
944 // problem with e.g. asking the user for a new path and
945 // trying again but simply exit.
949 LYXERR(Debug::INIT, "LyX tmp dir: `"
950 << package().temp_dir().absFileName() << '\'');
952 LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
953 pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
955 // This must happen after package initialization and after lyxrc is
956 // read, therefore it can't be done by a static object.
957 ConverterCache::init();
963 void emergencyCleanup()
965 // what to do about tmpfiles is non-obvious. we would
966 // like to delete any we find, but our lyxdir might
967 // contain documents etc. which might be helpful on
970 singleton_->pimpl_->buffer_list_.emergencyWriteAll();
972 if (singleton_->pimpl_->lyx_server_)
973 singleton_->pimpl_->lyx_server_->emergencyCleanup();
974 singleton_->pimpl_->lyx_server_.reset();
975 singleton_->pimpl_->lyx_socket_.reset();
980 bool LyX::queryUserLyXDir(bool explicit_userdir)
982 // Does user directory exist?
983 FileName const sup = package().user_support();
984 if (sup.exists() && sup.isDirectory()) {
987 return configFileNeedsUpdate("lyxrc.defaults")
988 || configFileNeedsUpdate("lyxmodules.lst")
989 || configFileNeedsUpdate("textclass.lst")
990 || configFileNeedsUpdate("packages.lst");
993 first_start = !explicit_userdir;
995 // If the user specified explicitly a directory, ask whether
996 // to create it. If the user says "no", then exit.
997 if (explicit_userdir &&
999 _("Missing user LyX directory"),
1000 bformat(_("You have specified a non-existent user "
1001 "LyX directory, %1$s.\n"
1002 "It is needed to keep your own configuration."),
1003 from_utf8(package().user_support().absFileName())),
1005 _("&Create directory"),
1007 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
1008 earlyExit(EXIT_FAILURE);
1011 lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
1012 from_utf8(sup.absFileName()))) << endl;
1014 if (!sup.createDirectory(0755)) {
1015 // Failed, so let's exit.
1016 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
1018 earlyExit(EXIT_FAILURE);
1025 bool LyX::readRcFile(string const & name, bool check_format)
1027 LYXERR(Debug::INIT, "About to read " << name << "... ");
1029 FileName const lyxrc_path = libFileSearch(string(), name);
1030 if (lyxrc_path.empty()) {
1031 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
1033 // This was the previous logic, but can it be right??
1036 LYXERR(Debug::INIT, "Found in " << lyxrc_path);
1037 bool const success = lyxrc.read(lyxrc_path, check_format);
1039 showFileError(name);
1043 // Read the languages file `name'
1044 bool LyX::readLanguagesFile(string const & name)
1046 LYXERR(Debug::INIT, "About to read " << name << "...");
1048 FileName const lang_path = libFileSearch(string(), name);
1049 if (lang_path.empty()) {
1050 showFileError(name);
1053 languages.read(lang_path);
1058 // Read the encodings file `name'
1059 bool LyX::readEncodingsFile(string const & enc_name,
1060 string const & symbols_name)
1062 LYXERR(Debug::INIT, "About to read " << enc_name << " and "
1063 << symbols_name << "...");
1065 FileName const symbols_path = libFileSearch(string(), symbols_name);
1066 if (symbols_path.empty()) {
1067 showFileError(symbols_name);
1071 FileName const enc_path = libFileSearch(string(), enc_name);
1072 if (enc_path.empty()) {
1073 showFileError(enc_name);
1076 encodings.read(enc_path, symbols_path);
1083 /// return the the number of arguments consumed
1084 typedef boost::function<int(string const &, string const &, string &)> cmd_helper;
1086 int parse_dbg(string const & arg, string const &, string &)
1089 cout << to_utf8(_("List of supported debug flags:")) << endl;
1090 Debug::showTags(cout);
1093 lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1095 lyxerr.setLevel(Debug::value(arg));
1096 Debug::showLevel(lyxerr, lyxerr.level());
1101 int parse_help(string const &, string const &, string &)
1104 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1105 "Command line switches (case sensitive):\n"
1106 "\t-help summarize LyX usage\n"
1107 "\t-userdir dir set user directory to dir\n"
1108 "\t-sysdir dir set system directory to dir\n"
1109 "\t-geometry WxH+X+Y set geometry of the main window\n"
1110 "\t-dbg feature[,feature]...\n"
1111 " select the features to debug.\n"
1112 " Type `lyx -dbg' to see the list of features\n"
1113 "\t-x [--execute] command\n"
1114 " where command is a lyx command.\n"
1115 "\t-e [--export] fmt\n"
1116 " where fmt is the export format of choice. Look in\n"
1117 " Tools->Preferences->File Handling->File Formats->Short Name\n"
1118 " to see which parameter (which differs from the format name\n"
1119 " in the File->Export menu) should be passed.\n"
1120 " Note that the order of -e and -x switches matters.\n"
1121 "\t-E [--export-to] fmt filename\n"
1122 " where fmt is the export format of choice (see --export),\n"
1123 " and filename is the destination filename.\n"
1124 "\t-i [--import] fmt file.xxx\n"
1125 " where fmt is the import format of choice\n"
1126 " and file.xxx is the file to be imported.\n"
1127 "\t-f [--force-overwrite] what\n"
1128 " where what is either `all', `main' or `none',\n"
1129 " specifying whether all files, main file only, or no files,\n"
1130 " respectively, are to be overwritten during a batch export.\n"
1131 " Anything else is equivalent to `all', but is not consumed.\n"
1132 "\t-n [--no-remote]\n"
1133 " open documents in a new instance\n"
1135 " open documents in an already running instance\n"
1136 " (a working lyxpipe is needed)\n"
1137 "\t-batch execute commands without launching GUI and exit.\n"
1138 "\t-version summarize version and build info\n"
1139 "Check the LyX man page for more details.")) << endl;
1145 int parse_version(string const &, string const &, string &)
1147 cout << "LyX " << lyx_version
1148 << " (" << lyx_release_date << ")" << endl;
1149 if (string(lyx_git_commit_hash) != "none")
1150 cout << to_utf8(_(" Git commit hash "))
1151 << string(lyx_git_commit_hash).substr(0,8) << endl;
1152 cout << to_utf8(bformat(_("Built on %1$s[[date]], %2$s[[time]]"),
1153 from_ascii(lyx_build_date), from_ascii(lyx_build_time))) << endl;
1154 cout << lyx_version_info << endl;
1160 int parse_sysdir(string const & arg, string const &, string &)
1163 Alert::error(_("No system directory"),
1164 _("Missing directory for -sysdir switch"));
1167 cl_system_support = arg;
1172 int parse_userdir(string const & arg, string const &, string &)
1175 Alert::error(_("No user directory"),
1176 _("Missing directory for -userdir switch"));
1179 cl_user_support = arg;
1184 int parse_execute(string const & arg, string const &, string & batch)
1187 Alert::error(_("Incomplete command"),
1188 _("Missing command string after --execute switch"));
1196 int parse_export_to(string const & type, string const & output_file, string & batch)
1199 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1200 "--export-to switch")) << endl;
1203 if (output_file.empty()) {
1204 lyxerr << to_utf8(_("Missing destination filename after "
1205 "--export-to switch")) << endl;
1208 batch = "buffer-export " + type + " " + output_file;
1214 int parse_export(string const & type, string const &, string & batch)
1217 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1218 "--export switch")) << endl;
1221 batch = "buffer-export " + type;
1227 int parse_import(string const & type, string const & file, string & batch)
1230 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1231 "--import switch")) << endl;
1235 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1238 batch = "buffer-import " + type + ' ' + file;
1243 int parse_geometry(string const & arg1, string const &, string &)
1246 // don't remove "-geometry", it will be pruned out later in the
1247 // frontend if need be.
1252 int parse_batch(string const &, string const &, string &)
1259 int parse_noremote(string const &, string const &, string &)
1261 run_mode = NEW_INSTANCE;
1266 int parse_remote(string const &, string const &, string &)
1268 run_mode = USE_REMOTE;
1273 int parse_force(string const & arg, string const &, string &)
1276 force_overwrite = ALL_FILES;
1278 } else if (arg == "main") {
1279 force_overwrite = MAIN_FILE;
1281 } else if (arg == "none") {
1282 force_overwrite = NO_FILES;
1285 force_overwrite = ALL_FILES;
1293 void LyX::easyParse(int & argc, char * argv[])
1295 map<string, cmd_helper> cmdmap;
1297 cmdmap["-dbg"] = parse_dbg;
1298 cmdmap["-help"] = parse_help;
1299 cmdmap["--help"] = parse_help;
1300 cmdmap["-version"] = parse_version;
1301 cmdmap["--version"] = parse_version;
1302 cmdmap["-sysdir"] = parse_sysdir;
1303 cmdmap["-userdir"] = parse_userdir;
1304 cmdmap["-x"] = parse_execute;
1305 cmdmap["--execute"] = parse_execute;
1306 cmdmap["-e"] = parse_export;
1307 cmdmap["--export"] = parse_export;
1308 cmdmap["-E"] = parse_export_to;
1309 cmdmap["--export-to"] = parse_export_to;
1310 cmdmap["-i"] = parse_import;
1311 cmdmap["--import"] = parse_import;
1312 cmdmap["-geometry"] = parse_geometry;
1313 cmdmap["-batch"] = parse_batch;
1314 cmdmap["-f"] = parse_force;
1315 cmdmap["--force-overwrite"] = parse_force;
1316 cmdmap["-n"] = parse_noremote;
1317 cmdmap["--no-remote"] = parse_noremote;
1318 cmdmap["-r"] = parse_remote;
1319 cmdmap["--remote"] = parse_remote;
1321 for (int i = 1; i < argc; ++i) {
1322 map<string, cmd_helper>::const_iterator it
1323 = cmdmap.find(argv[i]);
1325 // don't complain if not found - may be parsed later
1326 if (it == cmdmap.end())
1330 (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
1332 (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
1335 int const remove = 1 + it->second(arg, arg2, batch);
1337 pimpl_->batch_commands.push_back(batch);
1339 // Now, remove used arguments by shifting
1340 // the following ones remove places down.
1342 os::remove_internal_args(i, remove);
1344 for (int j = i; j < argc; ++j)
1345 argv[j] = argv[j + remove];
1352 FuncStatus getStatus(FuncRequest const & action)
1355 return theApp()->getStatus(action);
1359 void dispatch(FuncRequest const & action)
1362 return theApp()->dispatch(action);
1366 void dispatch(FuncRequest const & action, DispatchResult & dr)
1369 return theApp()->dispatch(action, dr);
1373 vector<string> & theFilesToLoad()
1375 LAPPERR(singleton_);
1376 return singleton_->pimpl_->files_to_load_;
1380 BufferList & theBufferList()
1382 LAPPERR(singleton_);
1383 return singleton_->pimpl_->buffer_list_;
1387 Server & theServer()
1389 // FIXME: this should not be use_gui dependent
1391 LAPPERR(singleton_);
1392 return *singleton_->pimpl_->lyx_server_.get();
1396 ServerSocket & theServerSocket()
1398 // FIXME: this should not be use_gui dependent
1400 LAPPERR(singleton_);
1401 return *singleton_->pimpl_->lyx_socket_.get();
1405 KeyMap & theTopLevelKeymap()
1407 LAPPERR(singleton_);
1408 return singleton_->pimpl_->toplevel_keymap_;
1412 Converters & theConverters()
1414 LAPPERR(singleton_);
1415 return singleton_->pimpl_->converters_;
1419 Converters & theSystemConverters()
1421 LAPPERR(singleton_);
1422 return singleton_->pimpl_->system_converters_;
1426 Movers & theMovers()
1428 LAPPERR(singleton_);
1429 return singleton_->pimpl_->movers_;
1433 Mover const & getMover(string const & fmt)
1435 LAPPERR(singleton_);
1436 return singleton_->pimpl_->movers_(fmt);
1440 void setMover(string const & fmt, string const & command)
1442 LAPPERR(singleton_);
1443 singleton_->pimpl_->movers_.set(fmt, command);
1447 Movers & theSystemMovers()
1449 LAPPERR(singleton_);
1450 return singleton_->pimpl_->system_movers_;
1454 Messages const & getMessages(string const & language)
1456 LAPPERR(singleton_);
1457 return singleton_->messages(language);
1461 Messages const & getGuiMessages()
1463 LAPPERR(singleton_);
1464 return singleton_->messages(Messages::guiLanguage());
1468 Session & theSession()
1470 LAPPERR(singleton_);
1471 return *singleton_->pimpl_->session_.get();
1475 LaTeXFonts & theLaTeXFonts()
1477 LAPPERR(singleton_);
1478 if (!singleton_->pimpl_->latexfonts_)
1479 singleton_->pimpl_->latexfonts_ = new LaTeXFonts;
1480 return *singleton_->pimpl_->latexfonts_;
1484 CmdDef & theTopLevelCmdDef()
1486 LAPPERR(singleton_);
1487 return singleton_->pimpl_->toplevel_cmddef_;
1491 SpellChecker * theSpellChecker()
1493 if (!singleton_->pimpl_->spell_checker_)
1495 return singleton_->pimpl_->spell_checker_;
1499 void setSpellChecker()
1501 SpellChecker::ChangeNumber speller_change_number =singleton_->pimpl_->spell_checker_ ?
1502 singleton_->pimpl_->spell_checker_->changeNumber() : 0;
1504 if (lyxrc.spellchecker == "native") {
1505 #if defined(USE_MACOSX_PACKAGING)
1506 if (!singleton_->pimpl_->apple_spell_checker_)
1507 singleton_->pimpl_->apple_spell_checker_ = new AppleSpellChecker;
1508 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->apple_spell_checker_;
1510 singleton_->pimpl_->spell_checker_ = 0;
1512 } else if (lyxrc.spellchecker == "aspell") {
1513 #if defined(USE_ASPELL)
1514 if (!singleton_->pimpl_->aspell_checker_)
1515 singleton_->pimpl_->aspell_checker_ = new AspellChecker;
1516 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->aspell_checker_;
1518 singleton_->pimpl_->spell_checker_ = 0;
1520 } else if (lyxrc.spellchecker == "enchant") {
1521 #if defined(USE_ENCHANT)
1522 if (!singleton_->pimpl_->enchant_checker_)
1523 singleton_->pimpl_->enchant_checker_ = new EnchantChecker;
1524 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->enchant_checker_;
1526 singleton_->pimpl_->spell_checker_ = 0;
1528 } else if (lyxrc.spellchecker == "hunspell") {
1529 #if defined(USE_HUNSPELL)
1530 if (!singleton_->pimpl_->hunspell_checker_)
1531 singleton_->pimpl_->hunspell_checker_ = new HunspellChecker;
1532 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->hunspell_checker_;
1534 singleton_->pimpl_->spell_checker_ = 0;
1537 singleton_->pimpl_->spell_checker_ = 0;
1539 if (singleton_->pimpl_->spell_checker_) {
1540 singleton_->pimpl_->spell_checker_->changeNumber(speller_change_number);
1541 singleton_->pimpl_->spell_checker_->advanceChangeNumber();