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 /// the parsed command line batch command if any
179 vector<string> batch_commands;
182 LaTeXFonts * latexfonts_;
185 SpellChecker * spell_checker_;
187 SpellChecker * apple_spell_checker_;
189 SpellChecker * aspell_checker_;
191 SpellChecker * enchant_checker_;
193 SpellChecker * hunspell_checker_;
197 /// The main application class for console mode
198 class LyXConsoleApp : public ConsoleApplication
201 LyXConsoleApp(LyX * lyx, int & argc, char * argv[])
202 : ConsoleApplication(lyx_package, argc, argv), lyx_(lyx),
203 argc_(argc), argv_(argv)
208 int const exit_status = lyx_->execWithoutGui(argc_, argv_);
219 frontend::Application * theApp()
222 return singleton_->pimpl_->application_.get();
232 WordList::cleanupWordLists();
236 void lyx_exit(int exit_code)
239 // Something wrong happened so better save everything, just in
244 // Properly crash in debug mode in order to get a useful backtrace.
248 // In release mode, try to exit gracefully.
250 theApp()->exit(exit_code);
264 Messages & LyX::messages(string const & language)
266 map<string, Messages>::iterator it = pimpl_->messages_.find(language);
268 if (it != pimpl_->messages_.end())
271 pair<map<string, Messages>::iterator, bool> result =
272 pimpl_->messages_.insert(make_pair(language, Messages(language)));
274 LATTEST(result.second);
275 return result.first->second;
279 int LyX::exec(int & argc, char * argv[])
281 // Minimal setting of locale before parsing command line
283 init_package(os::utf8_argv(0), string(), string());
284 // we do not get to this point when init_package throws an exception
286 } catch (ExceptionMessage const & message) {
287 LYXERR(Debug::LOCALE, message.title_ + ", " + message.details_);
290 // Here we need to parse the command line. At least
291 // we need to parse for "-dbg" and "-help"
292 easyParse(argc, argv);
295 init_package(os::utf8_argv(0), cl_system_support, cl_user_support);
296 } catch (ExceptionMessage const & message) {
297 if (message.type_ == ErrorException) {
298 Alert::error(message.title_, message.details_);
300 } else if (message.type_ == WarningException) {
301 Alert::warning(message.title_, message.details_);
305 // Reinit the messages machinery in case package() knows
306 // something interesting about the locale directory.
310 LyXConsoleApp app(this, argc, argv);
312 // Reestablish our defaults, as Qt overwrites them
313 // after creating app
319 // Let the frontend parse and remove all arguments that it knows
320 pimpl_->application_.reset(createApplication(argc, argv));
322 // Reestablish our defaults, as Qt overwrites them
323 // after createApplication()
326 // Parse and remove all known arguments in the LyX singleton
327 // Give an error for all remaining ones.
328 int exit_status = init(argc, argv);
330 // Kill the application object before exiting.
331 pimpl_->application_.reset();
337 // If not otherwise specified by a command line option or
338 // by preferences, we default to reuse a running instance.
339 if (run_mode == PREFERRED)
340 run_mode = USE_REMOTE;
343 /* Create a CoreApplication class that will provide the main event loop
344 * and the socket callback registering. With Qt, only QtCore
345 * library would be needed.
346 * When this is done, a server_mode could be created and the following two
347 * line would be moved out from here.
348 * However, note that the first of the two lines below triggers the
349 * "single instance" behavior, which should occur right at this point.
351 // Note: socket callback must be registered after init(argc, argv)
352 // such that package().temp_dir() is properly initialized.
353 pimpl_->lyx_server_.reset(new Server(lyxrc.lyxpipes));
354 pimpl_->lyx_socket_.reset(new ServerSocket(
355 FileName(package().temp_dir().absFileName() + "/lyxsocket")));
357 // Start the real execution loop.
358 if (!theServer().deferredLoadingToOtherInstance())
359 exit_status = pimpl_->application_->exec();
360 else if (!pimpl_->files_to_load_.empty()) {
361 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
362 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
363 lyxerr << _("The following files could not be loaded:") << endl;
364 for (; it != end; ++it)
365 lyxerr << *it << endl;
374 void LyX::prepareExit()
376 // Clear the clipboard and selection stack:
377 cap::clearCutStack();
378 cap::clearSelection();
380 // Write the index file of the converter cache
381 ConverterCache::get().writeIndex();
383 // close buffers first
384 pimpl_->buffer_list_.closeAll();
386 // register session changes and shutdown server and socket
388 if (pimpl_->session_)
389 pimpl_->session_->writeFile();
390 pimpl_->session_.reset();
391 pimpl_->lyx_server_.reset();
392 pimpl_->lyx_socket_.reset();
395 // do any other cleanup procedures now
396 if (package().temp_dir() != package().system_temp_dir()) {
397 string const abs_tmpdir = package().temp_dir().absFileName();
398 if (!contains(package().temp_dir().absFileName(), "lyx_tmpdir")) {
399 docstring const msg =
400 bformat(_("%1$s does not appear like a LyX created temporary directory."),
401 from_utf8(abs_tmpdir));
402 Alert::warning(_("Cannot remove temporary directory"), msg);
404 LYXERR(Debug::INFO, "Deleting tmp dir "
405 << package().temp_dir().absFileName());
406 if (!package().temp_dir().destroyDirectory()) {
407 docstring const msg =
408 bformat(_("Unable to remove the temporary directory %1$s"),
409 from_utf8(package().temp_dir().absFileName()));
410 Alert::warning(_("Unable to remove temporary directory"), msg);
415 // Kill the application object before exiting. This avoids crashes
416 // when exiting on Linux.
417 pimpl_->application_.reset();
421 void LyX::earlyExit(int status)
423 LATTEST(pimpl_->application_.get());
424 // LyX::pimpl_::application_ is not initialised at this
425 // point so it's safe to just exit after some cleanup.
431 int LyX::init(int & argc, char * argv[])
433 // check for any spurious extra arguments
434 // other than documents
435 for (int argi = 1; argi < argc ; ++argi) {
436 if (argv[argi][0] == '-') {
438 bformat(_("Wrong command line option `%1$s'. Exiting."),
439 from_utf8(os::utf8_argv(argi)))) << endl;
444 // Initialization of LyX (reads lyxrc and more)
445 LYXERR(Debug::INIT, "Initializing LyX::init...");
446 bool success = init();
447 LYXERR(Debug::INIT, "Initializing LyX::init...done");
451 // Remaining arguments are assumed to be files to load.
452 for (int argi = 1; argi < argc; ++argi)
453 pimpl_->files_to_load_.push_back(os::utf8_argv(argi));
455 if (!use_gui && pimpl_->files_to_load_.empty()) {
456 lyxerr << to_utf8(_("Missing filename for this operation.")) << endl;
461 pimpl_->files_to_load_.push_back(
462 i18nLibFileSearch("examples", "splash.lyx").absFileName());
469 int LyX::execWithoutGui(int & argc, char * argv[])
471 int exit_status = init(argc, argv);
477 // this is correct, since return values are inverted.
478 exit_status = !loadFiles();
480 if (pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
485 BufferList::iterator begin = pimpl_->buffer_list_.begin();
487 bool final_success = false;
488 for (BufferList::iterator I = begin; I != pimpl_->buffer_list_.end(); ++I) {
490 if (buf != buf->masterBuffer())
492 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
493 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
495 for (; bcit != bcend; ++bcit) {
496 LYXERR(Debug::ACTION, "Buffer::dispatch: cmd: " << *bcit);
497 buf->dispatch(*bcit, dr);
498 final_success |= !dr.error();
502 return !final_success;
506 bool LyX::loadFiles()
510 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
511 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
513 for (; it != end; ++it) {
514 // get absolute path of file and add ".lyx" to
515 // the filename if necessary
516 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
522 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFileName());
523 if (buf->loadLyXFile() == Buffer::ReadSuccess) {
524 ErrorList const & el = buf->errorList("Parse");
526 for_each(el.begin(), el.end(),
527 bind(&LyX::printError, this, _1));
530 pimpl_->buffer_list_.release(buf);
531 docstring const error_message =
532 bformat(_("LyX failed to load the following file: %1$s"),
533 from_utf8(fname.absFileName()));
534 lyxerr << to_utf8(error_message) << endl;
542 void execBatchCommands()
545 singleton_->execCommands();
549 void LyX::execCommands()
551 // The advantage of doing this here is that the event loop
552 // is already started. So any need for interaction will be
555 // if reconfiguration is needed.
556 if (LayoutFileList::get().empty()) {
557 switch (Alert::prompt(
558 _("No textclass is found"),
559 _("LyX will only have minimal functionality because no textclasses "
560 "have been found. You can either try to reconfigure LyX normally, "
561 "try to reconfigure without checking your LaTeX installation, or continue."),
568 // regular reconfigure
569 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
572 // reconfigure --without-latex-config
573 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE,
574 " --without-latex-config"));
581 // create the first main window
582 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
584 if (!pimpl_->files_to_load_.empty()) {
585 // if some files were specified at command-line we assume that the
586 // user wants to edit *these* files and not to restore the session.
587 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
589 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
591 // clear this list to save a few bytes of RAM
592 pimpl_->files_to_load_.clear();
594 pimpl_->application_->restoreGuiSession();
596 // Execute batch commands if available
597 if (pimpl_->batch_commands.empty())
600 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
601 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
602 for (; bcit != bcend; ++bcit) {
603 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
604 lyx::dispatch(lyxaction.lookupFunc(*bcit));
612 The SIGHUP signal does not exist on Windows and does not need to be handled.
614 Windows handles SIGFPE and SIGSEGV signals as expected.
616 Ctrl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
617 cause a new thread to be spawned. This may well result in unexpected
618 behaviour by the single-threaded LyX.
620 SIGTERM signals will come only from another process actually sending
621 that signal using 'raise' in Windows' POSIX compatability layer. It will
622 not come from the general "terminate process" methods that everyone
623 actually uses (and which can't be trapped). Killing an app 'politely' on
624 Windows involves first sending a WM_CLOSE message, something that is
625 caught already by the Qt frontend.
627 For more information see:
629 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
630 ...signals are mostly useless on Windows for a variety of reasons that are
633 'UNIX Application Migration Guide, Chapter 9'
634 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
636 'How To Terminate an Application "Cleanly" in Win32'
637 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
641 static void error_handler(int err_sig)
643 // Throw away any signals other than the first one received.
644 static sig_atomic_t handling_error = false;
647 handling_error = true;
649 // We have received a signal indicating a fatal error, so
650 // try and save the data ASAP.
653 // These lyxerr calls may or may not work:
655 // Signals are asynchronous, so the main program may be in a very
656 // fragile state when a signal is processed and thus while a signal
657 // handler function executes.
658 // In general, therefore, we should avoid performing any
659 // I/O operations or calling most library and system functions from
662 // This shouldn't matter here, however, as we've already invoked
668 msg = _("SIGHUP signal caught!\nBye.");
672 msg = _("SIGFPE signal caught!\nBye.");
675 msg = _("SIGSEGV signal caught!\n"
676 "Sorry, you have found a bug in LyX, "
677 "hope you have not lost any data.\n"
678 "Please read the bug-reporting instructions "
679 "in 'Help->Introduction' and send us a bug report, "
680 "if necessary. Thanks!\nBye.");
689 lyxerr << "\nlyx: " << msg << endl;
690 // try to make a GUI message
691 Alert::error(_("LyX crashed!"), msg, true);
694 // Deinstall the signal handlers
696 signal(SIGHUP, SIG_DFL);
698 signal(SIGINT, SIG_DFL);
699 signal(SIGFPE, SIG_DFL);
700 signal(SIGSEGV, SIG_DFL);
701 signal(SIGTERM, SIG_DFL);
704 if (err_sig == SIGSEGV ||
705 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty())) {
707 if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty()) {
710 // with abort() it crashes again.
723 void LyX::printError(ErrorItem const & ei)
725 docstring tmp = _("LyX: ") + ei.error + char_type(':')
727 cerr << to_utf8(tmp) << endl;
730 #if defined (USE_MACOSX_PACKAGING)
732 // Unexposed--extract an environment variable name from its NAME=VALUE
734 std::string varname(const char* line)
736 size_t nameLen = strcspn(line, "=");
737 if (nameLen == strlen(line)) {
738 return std::string();
740 return std::string(line, nameLen);
745 void cleanDuplicateEnvVars()
747 std::set<std::string> seen;
748 std::set<std::string> dupes;
750 // Create a list of the environment variables that appear more than once
751 for (char **read = *_NSGetEnviron(); *read; read++) {
752 std::string name = varname(*read);
753 if (name.size() == 0) {
756 if (seen.find(name) != seen.end()) {
763 // Loop over the list of duplicated variables
764 std::set<std::string>::iterator dupe = dupes.begin();
765 std::set<std::string>::iterator const dend = dupes.end();
766 for (; dupe != dend; ++dupe) {
767 const char *name = (*dupe).c_str();
768 char *val = getenv(name);
770 LYXERR(Debug::INIT, "Duplicate environment variable: " << name);
771 // unsetenv removes *all* instances of the variable from the environment
774 // replace with the value from getenv (in practice appears to be the
775 // first value in the list)
776 setenv(name, val, 0);
785 signal(SIGHUP, error_handler);
787 signal(SIGFPE, error_handler);
788 signal(SIGSEGV, error_handler);
789 signal(SIGINT, error_handler);
790 signal(SIGTERM, error_handler);
791 // SIGPIPE can be safely ignored.
793 #if defined (USE_MACOSX_PACKAGING)
794 cleanDuplicateEnvVars();
797 lyxrc.tempdir_path = package().temp_dir().absFileName();
798 lyxrc.document_path = package().document_dir().absFileName();
800 if (lyxrc.example_path.empty()) {
801 lyxrc.example_path = addPath(package().system_support().absFileName(),
804 if (lyxrc.template_path.empty()) {
805 lyxrc.template_path = addPath(package().system_support().absFileName(),
809 // init LyXDir environment variable
810 string const lyx_dir = package().lyx_dir().absFileName();
811 LYXERR(Debug::INIT, "Setting LyXDir... to \"" << lyx_dir << "\"");
812 if (!setEnv("LyXDir", lyx_dir))
813 LYXERR(Debug::INIT, "\t... failed!");
815 if (package().explicit_user_support() && getEnv(LYX_USERDIR_VER).empty()) {
816 // -userdir was given on the command line.
817 // Make it available to child processes, otherwise tex2lyx
818 // would not find all layout files, and other converters might
820 string const user_dir = package().user_support().absFileName();
821 LYXERR(Debug::INIT, "Setting " LYX_USERDIR_VER "... to \""
823 if (!setEnv(LYX_USERDIR_VER, user_dir))
824 LYXERR(Debug::INIT, "\t... failed!");
828 // Read configuration files
831 // This one may have been distributed along with LyX.
832 if (!readRcFile("lyxrc.dist"))
835 // Set the PATH correctly.
836 #if !defined (USE_POSIX_PACKAGING)
837 // Add the directory containing the LyX executable to the path
838 // so that LyX can find things like tex2lyx.
839 if (package().build_support().empty())
840 prependEnvPath("PATH", package().binary_dir().absFileName());
842 if (!lyxrc.path_prefix.empty())
843 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
845 // Check that user LyX directory is ok.
847 string const lock_file = package().getConfigureLockName();
848 int fd = fileLock(lock_file.c_str());
850 if (queryUserLyXDir(package().explicit_user_support())) {
851 package().reconfigureUserLyXDir("");
853 fileUnlock(fd, lock_file.c_str());
857 // No need for a splash when there is no GUI
859 // Default is to overwrite the main file during export, unless
860 // the -f switch was specified or LYX_FORCE_OVERWRITE was set
861 if (force_overwrite == UNSPECIFIED) {
862 string const what = getEnv("LYX_FORCE_OVERWRITE");
864 force_overwrite = ALL_FILES;
865 else if (what == "none")
866 force_overwrite = NO_FILES;
868 force_overwrite = MAIN_FILE;
872 // This one is generated in user_support directory by lib/configure.py.
873 if (!readRcFile("lyxrc.defaults"))
876 // Query the OS to know what formats are viewed natively
877 formats.setAutoOpen();
879 // Read lyxrc.dist again to be able to override viewer auto-detection.
880 readRcFile("lyxrc.dist");
882 system_lyxrc = lyxrc;
883 system_formats = formats;
884 pimpl_->system_converters_ = pimpl_->converters_;
885 pimpl_->system_movers_ = pimpl_->movers_;
886 system_lcolor = lcolor;
888 // This one is edited through the preferences dialog.
889 if (!readRcFile("preferences", true))
892 // The language may have been set to someting useful through prefs
895 if (!readEncodingsFile("encodings", "unicodesymbols"))
897 if (!readLanguagesFile("languages"))
900 LYXERR(Debug::INIT, "Reading layouts...");
902 LayoutFileList::get().read();
904 theModuleList.read();
906 // read keymap and ui files in batch mode as well
907 // because InsetInfo needs to know these to produce
908 // the correct output
910 // Set up command definitions
911 pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
915 pimpl_->toplevel_keymap_.read("site");
916 pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
917 // load user bind file user.bind
918 pimpl_->toplevel_keymap_.read("user", 0, KeyMap::MissingOK);
920 if (lyxerr.debugging(Debug::LYXRC))
923 os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
924 // Prepend path prefix a second time to take the user preferences into a account
925 if (!lyxrc.path_prefix.empty())
926 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
928 FileName const document_path(lyxrc.document_path);
929 if (document_path.exists() && document_path.isDirectory())
930 package().document_dir() = document_path;
932 package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
933 if (package().temp_dir().empty()) {
934 Alert::error(_("Could not create temporary directory"),
935 bformat(_("Could not create a temporary directory in\n"
937 "Make sure that this path exists and is writable and try again."),
938 from_utf8(lyxrc.tempdir_path)));
939 // createLyXTmpDir() tries sufficiently hard to create a
940 // usable temp dir, so the probability to come here is
941 // close to zero. We therefore don't try to overcome this
942 // problem with e.g. asking the user for a new path and
943 // trying again but simply exit.
947 LYXERR(Debug::INIT, "LyX tmp dir: `"
948 << package().temp_dir().absFileName() << '\'');
950 LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
951 pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
953 // This must happen after package initialization and after lyxrc is
954 // read, therefore it can't be done by a static object.
955 ConverterCache::init();
961 void emergencyCleanup()
963 // what to do about tmpfiles is non-obvious. we would
964 // like to delete any we find, but our lyxdir might
965 // contain documents etc. which might be helpful on
968 singleton_->pimpl_->buffer_list_.emergencyWriteAll();
970 if (singleton_->pimpl_->lyx_server_)
971 singleton_->pimpl_->lyx_server_->emergencyCleanup();
972 singleton_->pimpl_->lyx_server_.reset();
973 singleton_->pimpl_->lyx_socket_.reset();
978 bool LyX::queryUserLyXDir(bool explicit_userdir)
980 // Does user directory exist?
981 FileName const sup = package().user_support();
982 if (sup.exists() && sup.isDirectory()) {
985 return configFileNeedsUpdate("lyxrc.defaults")
986 || configFileNeedsUpdate("lyxmodules.lst")
987 || configFileNeedsUpdate("textclass.lst")
988 || configFileNeedsUpdate("packages.lst");
991 first_start = !explicit_userdir;
993 // If the user specified explicitly a directory, ask whether
994 // to create it. If the user says "no", then exit.
995 if (explicit_userdir &&
997 _("Missing user LyX directory"),
998 bformat(_("You have specified a non-existent user "
999 "LyX directory, %1$s.\n"
1000 "It is needed to keep your own configuration."),
1001 from_utf8(package().user_support().absFileName())),
1003 _("&Create directory"),
1005 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
1006 earlyExit(EXIT_FAILURE);
1009 lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
1010 from_utf8(sup.absFileName()))) << endl;
1012 if (!sup.createDirectory(0755)) {
1013 // Failed, so let's exit.
1014 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
1016 earlyExit(EXIT_FAILURE);
1023 bool LyX::readRcFile(string const & name, bool check_format)
1025 LYXERR(Debug::INIT, "About to read " << name << "... ");
1027 FileName const lyxrc_path = libFileSearch(string(), name);
1028 if (lyxrc_path.empty()) {
1029 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
1031 // This was the previous logic, but can it be right??
1034 LYXERR(Debug::INIT, "Found in " << lyxrc_path);
1035 bool const success = lyxrc.read(lyxrc_path, check_format);
1037 showFileError(name);
1041 // Read the languages file `name'
1042 bool LyX::readLanguagesFile(string const & name)
1044 LYXERR(Debug::INIT, "About to read " << name << "...");
1046 FileName const lang_path = libFileSearch(string(), name);
1047 if (lang_path.empty()) {
1048 showFileError(name);
1051 languages.read(lang_path);
1056 // Read the encodings file `name'
1057 bool LyX::readEncodingsFile(string const & enc_name,
1058 string const & symbols_name)
1060 LYXERR(Debug::INIT, "About to read " << enc_name << " and "
1061 << symbols_name << "...");
1063 FileName const symbols_path = libFileSearch(string(), symbols_name);
1064 if (symbols_path.empty()) {
1065 showFileError(symbols_name);
1069 FileName const enc_path = libFileSearch(string(), enc_name);
1070 if (enc_path.empty()) {
1071 showFileError(enc_name);
1074 encodings.read(enc_path, symbols_path);
1081 /// return the the number of arguments consumed
1082 typedef boost::function<int(string const &, string const &, string &)> cmd_helper;
1084 int parse_dbg(string const & arg, string const &, string &)
1087 cout << to_utf8(_("List of supported debug flags:")) << endl;
1088 Debug::showTags(cout);
1091 lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1093 lyxerr.setLevel(Debug::value(arg));
1094 Debug::showLevel(lyxerr, lyxerr.level());
1099 int parse_help(string const &, string const &, string &)
1102 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1103 "Command line switches (case sensitive):\n"
1104 "\t-help summarize LyX usage\n"
1105 "\t-userdir dir set user directory to dir\n"
1106 "\t-sysdir dir set system directory to dir\n"
1107 "\t-geometry WxH+X+Y set geometry of the main window\n"
1108 "\t-dbg feature[,feature]...\n"
1109 " select the features to debug.\n"
1110 " Type `lyx -dbg' to see the list of features\n"
1111 "\t-x [--execute] command\n"
1112 " where command is a lyx command.\n"
1113 "\t-e [--export] fmt\n"
1114 " where fmt is the export format of choice. Look in\n"
1115 " Tools->Preferences->File Handling->File Formats->Short Name\n"
1116 " to see which parameter (which differs from the format name\n"
1117 " in the File->Export menu) should be passed.\n"
1118 " Note that the order of -e and -x switches matters.\n"
1119 "\t-E [--export-to] fmt filename\n"
1120 " where fmt is the export format of choice (see --export),\n"
1121 " and filename is the destination filename.\n"
1122 "\t-i [--import] fmt file.xxx\n"
1123 " where fmt is the import format of choice\n"
1124 " and file.xxx is the file to be imported.\n"
1125 "\t-f [--force-overwrite] what\n"
1126 " where what is either `all', `main' or `none',\n"
1127 " specifying whether all files, main file only, or no files,\n"
1128 " respectively, are to be overwritten during a batch export.\n"
1129 " Anything else is equivalent to `all', but is not consumed.\n"
1130 "\t-n [--no-remote]\n"
1131 " open documents in a new instance\n"
1133 " open documents in an already running instance\n"
1134 " (a working lyxpipe is needed)\n"
1135 "\t-batch execute commands without launching GUI and exit.\n"
1136 "\t-version summarize version and build info\n"
1137 "Check the LyX man page for more details.")) << endl;
1143 int parse_version(string const &, string const &, string &)
1145 cout << "LyX " << lyx_version
1146 << " (" << lyx_release_date << ")" << endl;
1147 if (string(lyx_git_commit_hash) != "none")
1148 cout << to_utf8(_(" Git commit hash "))
1149 << string(lyx_git_commit_hash).substr(0,8) << endl;
1150 cout << lyx_version_info << endl;
1156 int parse_sysdir(string const & arg, string const &, string &)
1159 Alert::error(_("No system directory"),
1160 _("Missing directory for -sysdir switch"));
1163 cl_system_support = arg;
1168 int parse_userdir(string const & arg, string const &, string &)
1171 Alert::error(_("No user directory"),
1172 _("Missing directory for -userdir switch"));
1175 cl_user_support = arg;
1180 int parse_execute(string const & arg, string const &, string & batch)
1183 Alert::error(_("Incomplete command"),
1184 _("Missing command string after --execute switch"));
1192 int parse_export_to(string const & type, string const & output_file, string & batch)
1195 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1196 "--export-to switch")) << endl;
1199 if (output_file.empty()) {
1200 lyxerr << to_utf8(_("Missing destination filename after "
1201 "--export-to switch")) << endl;
1204 batch = "buffer-export " + type + " " + output_file;
1210 int parse_export(string const & type, string const &, string & batch)
1213 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1214 "--export switch")) << endl;
1217 batch = "buffer-export " + type;
1223 int parse_import(string const & type, string const & file, string & batch)
1226 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1227 "--import switch")) << endl;
1231 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1234 batch = "buffer-import " + type + ' ' + file;
1239 int parse_geometry(string const & arg1, string const &, string &)
1242 // don't remove "-geometry", it will be pruned out later in the
1243 // frontend if need be.
1248 int parse_batch(string const &, string const &, string &)
1255 int parse_noremote(string const &, string const &, string &)
1257 run_mode = NEW_INSTANCE;
1262 int parse_remote(string const &, string const &, string &)
1264 run_mode = USE_REMOTE;
1269 int parse_force(string const & arg, string const &, string &)
1272 force_overwrite = ALL_FILES;
1274 } else if (arg == "main") {
1275 force_overwrite = MAIN_FILE;
1277 } else if (arg == "none") {
1278 force_overwrite = NO_FILES;
1281 force_overwrite = ALL_FILES;
1289 void LyX::easyParse(int & argc, char * argv[])
1291 map<string, cmd_helper> cmdmap;
1293 cmdmap["-dbg"] = parse_dbg;
1294 cmdmap["-help"] = parse_help;
1295 cmdmap["--help"] = parse_help;
1296 cmdmap["-version"] = parse_version;
1297 cmdmap["--version"] = parse_version;
1298 cmdmap["-sysdir"] = parse_sysdir;
1299 cmdmap["-userdir"] = parse_userdir;
1300 cmdmap["-x"] = parse_execute;
1301 cmdmap["--execute"] = parse_execute;
1302 cmdmap["-e"] = parse_export;
1303 cmdmap["--export"] = parse_export;
1304 cmdmap["-E"] = parse_export_to;
1305 cmdmap["--export-to"] = parse_export_to;
1306 cmdmap["-i"] = parse_import;
1307 cmdmap["--import"] = parse_import;
1308 cmdmap["-geometry"] = parse_geometry;
1309 cmdmap["-batch"] = parse_batch;
1310 cmdmap["-f"] = parse_force;
1311 cmdmap["--force-overwrite"] = parse_force;
1312 cmdmap["-n"] = parse_noremote;
1313 cmdmap["--no-remote"] = parse_noremote;
1314 cmdmap["-r"] = parse_remote;
1315 cmdmap["--remote"] = parse_remote;
1317 for (int i = 1; i < argc; ++i) {
1318 map<string, cmd_helper>::const_iterator it
1319 = cmdmap.find(argv[i]);
1321 // don't complain if not found - may be parsed later
1322 if (it == cmdmap.end())
1326 (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
1328 (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
1331 int const remove = 1 + it->second(arg, arg2, batch);
1333 pimpl_->batch_commands.push_back(batch);
1335 // Now, remove used arguments by shifting
1336 // the following ones remove places down.
1338 os::remove_internal_args(i, remove);
1340 for (int j = i; j < argc; ++j)
1341 argv[j] = argv[j + remove];
1348 FuncStatus getStatus(FuncRequest const & action)
1351 return theApp()->getStatus(action);
1355 void dispatch(FuncRequest const & action)
1358 return theApp()->dispatch(action);
1362 void dispatch(FuncRequest const & action, DispatchResult & dr)
1365 return theApp()->dispatch(action, dr);
1369 vector<string> & theFilesToLoad()
1371 LAPPERR(singleton_);
1372 return singleton_->pimpl_->files_to_load_;
1376 BufferList & theBufferList()
1378 LAPPERR(singleton_);
1379 return singleton_->pimpl_->buffer_list_;
1383 Server & theServer()
1385 // FIXME: this should not be use_gui dependent
1387 LAPPERR(singleton_);
1388 return *singleton_->pimpl_->lyx_server_.get();
1392 ServerSocket & theServerSocket()
1394 // FIXME: this should not be use_gui dependent
1396 LAPPERR(singleton_);
1397 return *singleton_->pimpl_->lyx_socket_.get();
1401 KeyMap & theTopLevelKeymap()
1403 LAPPERR(singleton_);
1404 return singleton_->pimpl_->toplevel_keymap_;
1408 Converters & theConverters()
1410 LAPPERR(singleton_);
1411 return singleton_->pimpl_->converters_;
1415 Converters & theSystemConverters()
1417 LAPPERR(singleton_);
1418 return singleton_->pimpl_->system_converters_;
1422 Movers & theMovers()
1424 LAPPERR(singleton_);
1425 return singleton_->pimpl_->movers_;
1429 Mover const & getMover(string const & fmt)
1431 LAPPERR(singleton_);
1432 return singleton_->pimpl_->movers_(fmt);
1436 void setMover(string const & fmt, string const & command)
1438 LAPPERR(singleton_);
1439 singleton_->pimpl_->movers_.set(fmt, command);
1443 Movers & theSystemMovers()
1445 LAPPERR(singleton_);
1446 return singleton_->pimpl_->system_movers_;
1450 Messages const & getMessages(string const & language)
1452 LAPPERR(singleton_);
1453 return singleton_->messages(language);
1457 Messages const & getGuiMessages()
1459 LAPPERR(singleton_);
1460 return singleton_->messages(Messages::guiLanguage());
1464 Session & theSession()
1466 LAPPERR(singleton_);
1467 return *singleton_->pimpl_->session_.get();
1471 LaTeXFonts & theLaTeXFonts()
1473 LAPPERR(singleton_);
1474 if (!singleton_->pimpl_->latexfonts_)
1475 singleton_->pimpl_->latexfonts_ = new LaTeXFonts;
1476 return *singleton_->pimpl_->latexfonts_;
1480 CmdDef & theTopLevelCmdDef()
1482 LAPPERR(singleton_);
1483 return singleton_->pimpl_->toplevel_cmddef_;
1487 SpellChecker * theSpellChecker()
1489 if (!singleton_->pimpl_->spell_checker_)
1491 return singleton_->pimpl_->spell_checker_;
1495 void setSpellChecker()
1497 SpellChecker::ChangeNumber speller_change_number =singleton_->pimpl_->spell_checker_ ?
1498 singleton_->pimpl_->spell_checker_->changeNumber() : 0;
1500 if (lyxrc.spellchecker == "native") {
1501 #if defined(USE_MACOSX_PACKAGING)
1502 if (!singleton_->pimpl_->apple_spell_checker_)
1503 singleton_->pimpl_->apple_spell_checker_ = new AppleSpellChecker;
1504 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->apple_spell_checker_;
1506 singleton_->pimpl_->spell_checker_ = 0;
1508 } else if (lyxrc.spellchecker == "aspell") {
1509 #if defined(USE_ASPELL)
1510 if (!singleton_->pimpl_->aspell_checker_)
1511 singleton_->pimpl_->aspell_checker_ = new AspellChecker;
1512 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->aspell_checker_;
1514 singleton_->pimpl_->spell_checker_ = 0;
1516 } else if (lyxrc.spellchecker == "enchant") {
1517 #if defined(USE_ENCHANT)
1518 if (!singleton_->pimpl_->enchant_checker_)
1519 singleton_->pimpl_->enchant_checker_ = new EnchantChecker;
1520 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->enchant_checker_;
1522 singleton_->pimpl_->spell_checker_ = 0;
1524 } else if (lyxrc.spellchecker == "hunspell") {
1525 #if defined(USE_HUNSPELL)
1526 if (!singleton_->pimpl_->hunspell_checker_)
1527 singleton_->pimpl_->hunspell_checker_ = new HunspellChecker;
1528 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->hunspell_checker_;
1530 singleton_->pimpl_->spell_checker_ = 0;
1533 singleton_->pimpl_->spell_checker_ = 0;
1535 if (singleton_->pimpl_->spell_checker_) {
1536 singleton_->pimpl_->spell_checker_->changeNumber(speller_change_number);
1537 singleton_->pimpl_->spell_checker_->advanceChangeNumber();