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 "LayoutFile.h"
40 #include "LyXAction.h"
42 #include "ModuleList.h"
45 #include "ServerSocket.h"
48 #include "frontends/alert.h"
49 #include "frontends/Application.h"
51 #include "graphics/Previews.h"
53 #include "support/lassert.h"
54 #include "support/debug.h"
55 #include "support/environment.h"
56 #include "support/ExceptionMessage.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60 #include "support/Messages.h"
61 #include "support/os.h"
62 #include "support/Package.h"
63 #include "support/Path.h"
64 #include "support/Systemcall.h"
66 #include "support/bind.h"
67 #include <boost/scoped_ptr.hpp>
78 using namespace lyx::support;
82 namespace Alert = frontend::Alert;
83 namespace os = support::os;
87 // Are we using the GUI at all? We default to true and this is changed
88 // to false when the export feature is used.
93 // We default to open documents in an already running instance, provided that
94 // the lyxpipe has been setup. This can be overridden either on the command
95 // line or through preference settings.
97 RunMode run_mode = PREFERRED;
100 // Tell what files can be silently overwritten during batch export.
101 // Possible values are: NO_FILES, MAIN_FILE, ALL_FILES, UNSPECIFIED.
102 // Unless specified on command line (through the -f switch) or through the
103 // environment variable LYX_FORCE_OVERWRITE, the default will be MAIN_FILE.
105 OverwriteFiles force_overwrite = UNSPECIFIED;
110 // Filled with the command line arguments "foo" of "-sysdir foo" or
112 string cl_system_support;
113 string cl_user_support;
117 LyX * singleton_ = 0;
119 void showFileError(string const & error)
121 Alert::warning(_("Could not read configuration file"),
122 bformat(_("Error while reading the configuration file\n%1$s.\n"
123 "Please check your installation."), from_utf8(error)));
127 void reconfigureUserLyXDir()
129 string const configure_command = package().configure_command();
131 lyxerr << to_utf8(_("LyX: reconfiguring user directory")) << endl;
132 PathChanger p(package().user_support());
134 one.startscript(Systemcall::Wait, configure_command);
135 lyxerr << "LyX: " << to_utf8(_("Done!")) << endl;
140 /// The main application class private implementation.
143 Impl() : spell_checker_(0), apple_spell_checker_(0), aspell_checker_(0), enchant_checker_(0), hunspell_checker_(0)
145 // Set the default User Interface language as soon as possible.
146 // The language used will be derived from the environment
148 messages_["GUI"] = Messages();
153 delete apple_spell_checker_;
154 delete aspell_checker_;
155 delete enchant_checker_;
156 delete hunspell_checker_;
160 BufferList buffer_list_;
162 KeyMap toplevel_keymap_;
164 CmdDef toplevel_cmddef_;
166 boost::scoped_ptr<Server> lyx_server_;
168 boost::scoped_ptr<ServerSocket> lyx_socket_;
170 boost::scoped_ptr<frontend::Application> application_;
171 /// lyx session, containing lastfiles, lastfilepos, and lastopened
172 boost::scoped_ptr<Session> session_;
174 /// Files to load at start.
175 vector<string> files_to_load_;
177 /// The messages translators.
178 map<string, Messages> messages_;
180 /// The file converters.
181 Converters converters_;
183 // The system converters copy after reading lyxrc.defaults.
184 Converters system_converters_;
189 Movers system_movers_;
191 /// has this user started lyx for the first time?
193 /// the parsed command line batch command if any
194 vector<string> batch_commands;
197 graphics::Previews preview_;
199 SpellChecker * spell_checker_;
201 SpellChecker * apple_spell_checker_;
203 SpellChecker * aspell_checker_;
205 SpellChecker * enchant_checker_;
207 SpellChecker * hunspell_checker_;
211 frontend::Application * theApp()
214 return singleton_->pimpl_->application_.get();
227 void lyx_exit(int exit_code)
230 // Something wrong happened so better save everything, just in
235 // Properly crash in debug mode in order to get a useful backtrace.
239 // In release mode, try to exit gracefully.
241 theApp()->exit(exit_code);
255 Messages & LyX::messages(string const & language)
257 map<string, Messages>::iterator it = pimpl_->messages_.find(language);
259 if (it != pimpl_->messages_.end())
262 pair<map<string, Messages>::iterator, bool> result =
263 pimpl_->messages_.insert(make_pair(language, Messages(language)));
265 LASSERT(result.second, /**/);
266 return result.first->second;
270 void setRcGuiLanguage()
272 LASSERT(singleton_, /**/);
273 if (lyxrc.gui_language == "auto")
275 Language const * language = languages.getLanguage(lyxrc.gui_language);
277 LYXERR(Debug::LOCALE, "Setting LANGUAGE to " << language->code());
278 if (!setEnv("LANGUAGE", language->code()))
279 LYXERR(Debug::LOCALE, "\t... failed!");
281 LYXERR(Debug::LOCALE, "Setting LC_ALL to en_US");
282 if (!setEnv("LC_ALL", "en_US"))
283 LYXERR(Debug::LOCALE, "\t... failed!");
285 singleton_->pimpl_->messages_["GUI"] = Messages();
289 int LyX::exec(int & argc, char * argv[])
291 // Minimal setting of locale before parsing command line
293 init_package(os::utf8_argv(0), string(), string(),
294 top_build_dir_is_one_level_up);
295 } catch (ExceptionMessage const & message) {
296 LYXERR(Debug::LOCALE, message.title_ + ", " + message.details_);
298 // FIXME: This breaks out of source build under Windows.
301 // Here we need to parse the command line. At least
302 // we need to parse for "-dbg" and "-help"
303 easyParse(argc, argv);
306 init_package(os::utf8_argv(0),
307 cl_system_support, cl_user_support,
308 top_build_dir_is_one_level_up);
309 } catch (ExceptionMessage const & message) {
310 if (message.type_ == ErrorException) {
311 Alert::error(message.title_, message.details_);
313 } else if (message.type_ == WarningException) {
314 Alert::warning(message.title_, message.details_);
318 // Reinit the messages machinery in case package() knows
319 // something interesting about the locale directory.
323 // FIXME: create a ConsoleApplication
324 int exit_status = init(argc, argv);
330 // this is correct, since return values are inverted.
331 exit_status = !loadFiles();
333 if (pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
338 BufferList::iterator begin = pimpl_->buffer_list_.begin();
340 bool final_success = false;
341 for (BufferList::iterator I = begin; I != pimpl_->buffer_list_.end(); ++I) {
343 if (buf != buf->masterBuffer())
345 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
346 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
348 for (; bcit != bcend; bcit++) {
349 LYXERR(Debug::ACTION, "Buffer::dispatch: cmd: " << *bcit);
350 buf->dispatch(*bcit, dr);
351 final_success |= !dr.error();
355 return !final_success;
358 // Let the frontend parse and remove all arguments that it knows
359 pimpl_->application_.reset(createApplication(argc, argv));
361 // Reestablish our defaults, as Qt overwrites them
362 // after createApplication()
365 // Parse and remove all known arguments in the LyX singleton
366 // Give an error for all remaining ones.
367 int exit_status = init(argc, argv);
369 // Kill the application object before exiting.
370 pimpl_->application_.reset();
376 // If not otherwise specified by a command line option or
377 // by preferences, we default to reuse a running instance.
378 if (run_mode == PREFERRED)
379 run_mode = USE_REMOTE;
382 /* Create a CoreApplication class that will provide the main event loop
383 * and the socket callback registering. With Qt4, only QtCore
384 * library would be needed.
385 * When this is done, a server_mode could be created and the following two
386 * line would be moved out from here.
387 * However, note that the first of the two lines below triggers the
388 * "single instance" behavior, which should occur right at this point.
390 // Note: socket callback must be registered after init(argc, argv)
391 // such that package().temp_dir() is properly initialized.
392 pimpl_->lyx_server_.reset(new Server(lyxrc.lyxpipes));
393 pimpl_->lyx_socket_.reset(new ServerSocket(
394 FileName(package().temp_dir().absFileName() + "/lyxsocket")));
396 // Start the real execution loop.
397 if (!theServer().deferredLoadingToOtherInstance())
398 exit_status = pimpl_->application_->exec();
399 else if (!pimpl_->files_to_load_.empty()) {
400 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
401 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
402 lyxerr << _("The following files could not be loaded:") << endl;
403 for (; it != end; ++it)
404 lyxerr << *it << endl;
413 void LyX::prepareExit()
415 // Clear the clipboard and selection stack:
416 cap::clearCutStack();
417 cap::clearSelection();
419 // Write the index file of the converter cache
420 ConverterCache::get().writeIndex();
422 // close buffers first
423 pimpl_->buffer_list_.closeAll();
425 // register session changes and shutdown server and socket
427 if (pimpl_->session_)
428 pimpl_->session_->writeFile();
429 pimpl_->session_.reset();
430 pimpl_->lyx_server_.reset();
431 pimpl_->lyx_socket_.reset();
434 // do any other cleanup procedures now
435 if (package().temp_dir() != package().system_temp_dir()) {
436 string const abs_tmpdir = package().temp_dir().absFileName();
437 if (!contains(package().temp_dir().absFileName(), "lyx_tmpdir")) {
438 docstring const msg =
439 bformat(_("%1$s does not appear like a LyX created temporary directory."),
440 from_utf8(abs_tmpdir));
441 Alert::warning(_("Cannot remove temporary directory"), msg);
443 LYXERR(Debug::INFO, "Deleting tmp dir "
444 << package().temp_dir().absFileName());
445 if (!package().temp_dir().destroyDirectory()) {
446 docstring const msg =
447 bformat(_("Unable to remove the temporary directory %1$s"),
448 from_utf8(package().temp_dir().absFileName()));
449 Alert::warning(_("Unable to remove temporary directory"), msg);
454 // Kill the application object before exiting. This avoids crashes
455 // when exiting on Linux.
456 if (pimpl_->application_)
457 pimpl_->application_.reset();
461 void LyX::earlyExit(int status)
463 LASSERT(pimpl_->application_.get(), /**/);
464 // LyX::pimpl_::application_ is not initialised at this
465 // point so it's safe to just exit after some cleanup.
471 int LyX::init(int & argc, char * argv[])
473 // check for any spurious extra arguments
474 // other than documents
475 for (int argi = 1; argi < argc ; ++argi) {
476 if (argv[argi][0] == '-') {
478 bformat(_("Wrong command line option `%1$s'. Exiting."),
479 from_utf8(os::utf8_argv(argi)))) << endl;
484 // Initialization of LyX (reads lyxrc and more)
485 LYXERR(Debug::INIT, "Initializing LyX::init...");
486 bool success = init();
487 LYXERR(Debug::INIT, "Initializing LyX::init...done");
491 // Remaining arguments are assumed to be files to load.
492 for (int argi = 1; argi < argc; ++argi)
493 pimpl_->files_to_load_.push_back(os::utf8_argv(argi));
496 pimpl_->files_to_load_.push_back(
497 i18nLibFileSearch("examples", "splash.lyx").absFileName());
504 bool LyX::loadFiles()
506 LASSERT(!use_gui, /**/);
508 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
509 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
511 for (; it != end; ++it) {
512 // get absolute path of file and add ".lyx" to
513 // the filename if necessary
514 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
520 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFileName(), false);
521 if (buf->loadLyXFile() == Buffer::ReadSuccess) {
522 ErrorList const & el = buf->errorList("Parse");
524 for_each(el.begin(), el.end(),
525 bind(&LyX::printError, this, _1));
528 pimpl_->buffer_list_.release(buf);
536 void execBatchCommands()
538 LASSERT(singleton_, /**/);
539 singleton_->execCommands();
543 void LyX::execCommands()
545 // The advantage of doing this here is that the event loop
546 // is already started. So any need for interaction will be
549 // if reconfiguration is needed.
550 if (LayoutFileList::get().empty()) {
551 switch (Alert::prompt(
552 _("No textclass is found"),
553 _("LyX will only have minimal functionality because no textclasses "
554 "have been found. You can either try to reconfigure LyX normally, "
555 "try to reconfigure without checking your LaTeX installation, or continue."),
562 // regular reconfigure
563 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
566 // reconfigure --without-latex-config
567 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE,
568 " --without-latex-config"));
575 // create the first main window
576 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
578 if (!pimpl_->files_to_load_.empty()) {
579 // if some files were specified at command-line we assume that the
580 // user wants to edit *these* files and not to restore the session.
581 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
583 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
585 // clear this list to save a few bytes of RAM
586 pimpl_->files_to_load_.clear();
588 pimpl_->application_->restoreGuiSession();
590 // Execute batch commands if available
591 if (pimpl_->batch_commands.empty())
594 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
595 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
596 for (; bcit != bcend; bcit++) {
597 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
598 lyx::dispatch(lyxaction.lookupFunc(*bcit));
606 The SIGHUP signal does not exist on Windows and does not need to be handled.
608 Windows handles SIGFPE and SIGSEGV signals as expected.
610 Ctrl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
611 cause a new thread to be spawned. This may well result in unexpected
612 behaviour by the single-threaded LyX.
614 SIGTERM signals will come only from another process actually sending
615 that signal using 'raise' in Windows' POSIX compatability layer. It will
616 not come from the general "terminate process" methods that everyone
617 actually uses (and which can't be trapped). Killing an app 'politely' on
618 Windows involves first sending a WM_CLOSE message, something that is
619 caught already by the Qt frontend.
621 For more information see:
623 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
624 ...signals are mostly useless on Windows for a variety of reasons that are
627 'UNIX Application Migration Guide, Chapter 9'
628 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
630 'How To Terminate an Application "Cleanly" in Win32'
631 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
635 static void error_handler(int err_sig)
637 // Throw away any signals other than the first one received.
638 static sig_atomic_t handling_error = false;
641 handling_error = true;
643 // We have received a signal indicating a fatal error, so
644 // try and save the data ASAP.
647 // These lyxerr calls may or may not work:
649 // Signals are asynchronous, so the main program may be in a very
650 // fragile state when a signal is processed and thus while a signal
651 // handler function executes.
652 // In general, therefore, we should avoid performing any
653 // I/O operations or calling most library and system functions from
656 // This shouldn't matter here, however, as we've already invoked
662 msg = _("SIGHUP signal caught!\nBye.");
666 msg = _("SIGFPE signal caught!\nBye.");
669 msg = _("SIGSEGV signal caught!\n"
670 "Sorry, you have found a bug in LyX, "
671 "hope you have not lost any data.\n"
672 "Please read the bug-reporting instructions "
673 "in 'Help->Introduction' and send us a bug report, "
674 "if necessary. Thanks !\nBye.");
683 lyxerr << "\nlyx: " << msg << endl;
684 // try to make a GUI message
685 Alert::error(_("LyX crashed!"), msg);
688 // Deinstall the signal handlers
690 signal(SIGHUP, SIG_DFL);
692 signal(SIGINT, SIG_DFL);
693 signal(SIGFPE, SIG_DFL);
694 signal(SIGSEGV, SIG_DFL);
695 signal(SIGTERM, SIG_DFL);
698 if (err_sig == SIGSEGV ||
699 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty())) {
701 if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty()) {
704 // with abort() it crashes again.
717 void LyX::printError(ErrorItem const & ei)
719 docstring tmp = _("LyX: ") + ei.error + char_type(':')
721 cerr << to_utf8(tmp) << endl;
728 signal(SIGHUP, error_handler);
730 signal(SIGFPE, error_handler);
731 signal(SIGSEGV, error_handler);
732 signal(SIGINT, error_handler);
733 signal(SIGTERM, error_handler);
734 // SIGPIPE can be safely ignored.
736 lyxrc.tempdir_path = package().temp_dir().absFileName();
737 lyxrc.document_path = package().document_dir().absFileName();
739 if (lyxrc.example_path.empty()) {
740 lyxrc.example_path = addPath(package().system_support().absFileName(),
743 if (lyxrc.template_path.empty()) {
744 lyxrc.template_path = addPath(package().system_support().absFileName(),
748 // init LyXDir environment variable
749 string const lyx_dir = package().lyx_dir().absFileName();
750 LYXERR(Debug::INIT, "Setting LyXDir... to \"" << lyx_dir << "\"");
751 if (!setEnv("LyXDir", lyx_dir))
752 LYXERR(Debug::INIT, "\t... failed!");
755 // Read configuration files
758 // This one may have been distributed along with LyX.
759 if (!readRcFile("lyxrc.dist"))
762 // Set the language defined by the distributor.
765 // Set the PATH correctly.
766 #if !defined (USE_POSIX_PACKAGING)
767 // Add the directory containing the LyX executable to the path
768 // so that LyX can find things like tex2lyx.
769 if (package().build_support().empty())
770 prependEnvPath("PATH", package().binary_dir().absFileName());
772 if (!lyxrc.path_prefix.empty())
773 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
775 // Check that user LyX directory is ok.
776 if (queryUserLyXDir(package().explicit_user_support()))
777 reconfigureUserLyXDir();
780 // No need for a splash when there is no GUI
782 // Default is to overwrite the main file during export, unless
783 // the -f switch was specified or LYX_FORCE_OVERWRITE was set
784 if (force_overwrite == UNSPECIFIED) {
785 string const what = getEnv("LYX_FORCE_OVERWRITE");
787 force_overwrite = ALL_FILES;
788 else if (what == "none")
789 force_overwrite = NO_FILES;
791 force_overwrite = MAIN_FILE;
795 // This one is generated in user_support directory by lib/configure.py.
796 if (!readRcFile("lyxrc.defaults"))
799 // Query the OS to know what formats are viewed natively
800 formats.setAutoOpen();
802 // Read lyxrc.dist again to be able to override viewer auto-detection.
803 readRcFile("lyxrc.dist");
805 // Set again the language defined by the distributor.
808 system_lyxrc = lyxrc;
809 system_formats = formats;
810 pimpl_->system_converters_ = pimpl_->converters_;
811 pimpl_->system_movers_ = pimpl_->movers_;
812 system_lcolor = lcolor;
814 // This one is edited through the preferences dialog.
815 if (!readRcFile("preferences", true))
818 if (!readEncodingsFile("encodings", "unicodesymbols"))
820 if (!readLanguagesFile("languages"))
823 // Set the language defined by the user.
826 LYXERR(Debug::INIT, "Reading layouts...");
828 LayoutFileList::get().read();
830 theModuleList.read();
832 // read keymap and ui files in batch mode as well
833 // because InsetInfo needs to know these to produce
834 // the correct output
836 // Set up command definitions
837 pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
841 pimpl_->toplevel_keymap_.read("site");
842 pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
843 // load user bind file user.bind
844 pimpl_->toplevel_keymap_.read("user", 0, KeyMap::MissingOK);
846 if (lyxerr.debugging(Debug::LYXRC))
849 os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
850 if (!lyxrc.path_prefix.empty())
851 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
853 FileName const document_path(lyxrc.document_path);
854 if (document_path.exists() && document_path.isDirectory())
855 package().document_dir() = document_path;
857 package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
858 if (package().temp_dir().empty()) {
859 Alert::error(_("Could not create temporary directory"),
860 bformat(_("Could not create a temporary directory in\n"
862 "Make sure that this path exists and is writable and try again."),
863 from_utf8(lyxrc.tempdir_path)));
864 // createLyXTmpDir() tries sufficiently hard to create a
865 // usable temp dir, so the probability to come here is
866 // close to zero. We therefore don't try to overcome this
867 // problem with e.g. asking the user for a new path and
868 // trying again but simply exit.
872 LYXERR(Debug::INIT, "LyX tmp dir: `"
873 << package().temp_dir().absFileName() << '\'');
875 LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
876 pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
878 // This must happen after package initialization and after lyxrc is
879 // read, therefore it can't be done by a static object.
880 ConverterCache::init();
886 void emergencyCleanup()
888 // what to do about tmpfiles is non-obvious. we would
889 // like to delete any we find, but our lyxdir might
890 // contain documents etc. which might be helpful on
893 singleton_->pimpl_->buffer_list_.emergencyWriteAll();
895 if (singleton_->pimpl_->lyx_server_)
896 singleton_->pimpl_->lyx_server_->emergencyCleanup();
897 singleton_->pimpl_->lyx_server_.reset();
898 singleton_->pimpl_->lyx_socket_.reset();
903 // return true if file does not exist or is older than configure.py.
904 static bool needsUpdate(string const & file)
906 // We cannot initialize configure_script directly because the package
907 // is not initialized yet when static objects are constructed.
908 static FileName configure_script;
909 static bool firstrun = true;
912 FileName(addName(package().system_support().absFileName(),
918 FileName(addName(package().user_support().absFileName(), file));
919 return !absfile.exists()
920 || configure_script.lastModified() > absfile.lastModified();
924 bool LyX::queryUserLyXDir(bool explicit_userdir)
926 // Does user directory exist?
927 FileName const sup = package().user_support();
928 if (sup.exists() && sup.isDirectory()) {
931 return needsUpdate("lyxrc.defaults")
932 || needsUpdate("lyxmodules.lst")
933 || needsUpdate("textclass.lst")
934 || needsUpdate("packages.lst");
937 first_start = !explicit_userdir;
939 // If the user specified explicitly a directory, ask whether
940 // to create it. If the user says "no", then exit.
941 if (explicit_userdir &&
943 _("Missing user LyX directory"),
944 bformat(_("You have specified a non-existent user "
945 "LyX directory, %1$s.\n"
946 "It is needed to keep your own configuration."),
947 from_utf8(package().user_support().absFileName())),
949 _("&Create directory"),
951 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
952 earlyExit(EXIT_FAILURE);
955 lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
956 from_utf8(sup.absFileName()))) << endl;
958 if (!sup.createDirectory(0755)) {
959 // Failed, so let's exit.
960 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
962 earlyExit(EXIT_FAILURE);
969 bool LyX::readRcFile(string const & name, bool check_format)
971 LYXERR(Debug::INIT, "About to read " << name << "... ");
973 FileName const lyxrc_path = libFileSearch(string(), name);
974 if (lyxrc_path.empty()) {
975 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
977 // This was the previous logic, but can it be right??
980 LYXERR(Debug::INIT, "Found in " << lyxrc_path);
981 bool const success = lyxrc.read(lyxrc_path, check_format);
987 // Read the languages file `name'
988 bool LyX::readLanguagesFile(string const & name)
990 LYXERR(Debug::INIT, "About to read " << name << "...");
992 FileName const lang_path = libFileSearch(string(), name);
993 if (lang_path.empty()) {
997 languages.read(lang_path);
1002 // Read the encodings file `name'
1003 bool LyX::readEncodingsFile(string const & enc_name,
1004 string const & symbols_name)
1006 LYXERR(Debug::INIT, "About to read " << enc_name << " and "
1007 << symbols_name << "...");
1009 FileName const symbols_path = libFileSearch(string(), symbols_name);
1010 if (symbols_path.empty()) {
1011 showFileError(symbols_name);
1015 FileName const enc_path = libFileSearch(string(), enc_name);
1016 if (enc_path.empty()) {
1017 showFileError(enc_name);
1020 encodings.read(enc_path, symbols_path);
1027 /// return the the number of arguments consumed
1028 typedef boost::function<int(string const &, string const &, string &)> cmd_helper;
1030 int parse_dbg(string const & arg, string const &, string &)
1033 lyxerr << to_utf8(_("List of supported debug flags:")) << endl;
1034 Debug::showTags(lyxerr);
1037 lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1039 lyxerr.setLevel(Debug::value(arg));
1040 Debug::showLevel(lyxerr, lyxerr.level());
1045 int parse_help(string const &, string const &, string &)
1048 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1049 "Command line switches (case sensitive):\n"
1050 "\t-help summarize LyX usage\n"
1051 "\t-userdir dir set user directory to dir\n"
1052 "\t-sysdir dir set system directory to dir\n"
1053 "\t-geometry WxH+X+Y set geometry of the main window\n"
1054 "\t-dbg feature[,feature]...\n"
1055 " select the features to debug.\n"
1056 " Type `lyx -dbg' to see the list of features\n"
1057 "\t-x [--execute] command\n"
1058 " where command is a lyx command.\n"
1059 "\t-e [--export] fmt\n"
1060 " where fmt is the export format of choice.\n"
1061 " Look on Tools->Preferences->File formats->Format\n"
1062 " to get an idea which parameters should be passed.\n"
1063 " Note that the order of -e and -x switches matters.\n"
1064 "\t-i [--import] fmt file.xxx\n"
1065 " where fmt is the import format of choice\n"
1066 " and file.xxx is the file to be imported.\n"
1067 "\t-f [--force-overwrite] what\n"
1068 " where what is either `all', `main' or `none',\n"
1069 " specifying whether all files, main file only, or no files,\n"
1070 " respectively, are to be overwritten during a batch export.\n"
1071 " Anything else is equivalent to `all', but is not consumed.\n"
1072 "\t-n [--no-remote]\n"
1073 " open documents in a new instance\n"
1075 " open documents in an already running instance\n"
1076 " (a working lyxpipe is needed)\n"
1077 "\t-batch execute commands without launching GUI and exit.\n"
1078 "\t-version summarize version and build info\n"
1079 "Check the LyX man page for more details.")) << endl;
1085 int parse_version(string const &, string const &, string &)
1087 lyxerr << "LyX " << lyx_version
1088 << " (" << lyx_release_date << ")" << endl;
1089 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
1091 lyxerr << lyx_version_info << endl;
1097 int parse_sysdir(string const & arg, string const &, string &)
1100 Alert::error(_("No system directory"),
1101 _("Missing directory for -sysdir switch"));
1104 cl_system_support = arg;
1109 int parse_userdir(string const & arg, string const &, string &)
1112 Alert::error(_("No user directory"),
1113 _("Missing directory for -userdir switch"));
1116 cl_user_support = arg;
1121 int parse_execute(string const & arg, string const &, string & batch)
1124 Alert::error(_("Incomplete command"),
1125 _("Missing command string after --execute switch"));
1133 int parse_export(string const & type, string const &, string & batch)
1136 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1137 "--export switch")) << endl;
1140 batch = "buffer-export " + type;
1146 int parse_import(string const & type, string const & file, string & batch)
1149 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1150 "--import switch")) << endl;
1154 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1158 batch = "buffer-import " + type + ' ' + file;
1163 int parse_geometry(string const & arg1, string const &, string &)
1166 // don't remove "-geometry", it will be pruned out later in the
1167 // frontend if need be.
1172 int parse_batch(string const &, string const &, string &)
1179 int parse_noremote(string const &, string const &, string &)
1181 run_mode = NEW_INSTANCE;
1186 int parse_remote(string const &, string const &, string &)
1188 run_mode = USE_REMOTE;
1193 int parse_force(string const & arg, string const &, string &)
1196 force_overwrite = ALL_FILES;
1198 } else if (arg == "main") {
1199 force_overwrite = MAIN_FILE;
1201 } else if (arg == "none") {
1202 force_overwrite = NO_FILES;
1205 force_overwrite = ALL_FILES;
1213 void LyX::easyParse(int & argc, char * argv[])
1215 map<string, cmd_helper> cmdmap;
1217 cmdmap["-dbg"] = parse_dbg;
1218 cmdmap["-help"] = parse_help;
1219 cmdmap["--help"] = parse_help;
1220 cmdmap["-version"] = parse_version;
1221 cmdmap["--version"] = parse_version;
1222 cmdmap["-sysdir"] = parse_sysdir;
1223 cmdmap["-userdir"] = parse_userdir;
1224 cmdmap["-x"] = parse_execute;
1225 cmdmap["--execute"] = parse_execute;
1226 cmdmap["-e"] = parse_export;
1227 cmdmap["--export"] = parse_export;
1228 cmdmap["-i"] = parse_import;
1229 cmdmap["--import"] = parse_import;
1230 cmdmap["-geometry"] = parse_geometry;
1231 cmdmap["-batch"] = parse_batch;
1232 cmdmap["-f"] = parse_force;
1233 cmdmap["--force-overwrite"] = parse_force;
1234 cmdmap["-n"] = parse_noremote;
1235 cmdmap["--no-remote"] = parse_noremote;
1236 cmdmap["-r"] = parse_remote;
1237 cmdmap["--remote"] = parse_remote;
1239 for (int i = 1; i < argc; ++i) {
1240 map<string, cmd_helper>::const_iterator it
1241 = cmdmap.find(argv[i]);
1243 // don't complain if not found - may be parsed later
1244 if (it == cmdmap.end())
1248 (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
1250 (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
1253 int const remove = 1 + it->second(arg, arg2, batch);
1255 pimpl_->batch_commands.push_back(batch);
1257 // Now, remove used arguments by shifting
1258 // the following ones remove places down.
1260 os::remove_internal_args(i, remove);
1262 for (int j = i; j < argc; ++j)
1263 argv[j] = argv[j + remove];
1270 FuncStatus getStatus(FuncRequest const & action)
1272 LASSERT(theApp(), /**/);
1273 return theApp()->getStatus(action);
1277 void dispatch(FuncRequest const & action)
1279 LASSERT(theApp(), /**/);
1280 return theApp()->dispatch(action);
1284 void dispatch(FuncRequest const & action, DispatchResult & dr)
1286 LASSERT(theApp(), /**/);
1287 return theApp()->dispatch(action, dr);
1291 vector<string> & theFilesToLoad()
1293 LASSERT(singleton_, /**/);
1294 return singleton_->pimpl_->files_to_load_;
1298 BufferList & theBufferList()
1300 LASSERT(singleton_, /**/);
1301 return singleton_->pimpl_->buffer_list_;
1305 Server & theServer()
1307 // FIXME: this should not be use_gui dependent
1308 LASSERT(use_gui, /**/);
1309 LASSERT(singleton_, /**/);
1310 return *singleton_->pimpl_->lyx_server_.get();
1314 ServerSocket & theServerSocket()
1316 // FIXME: this should not be use_gui dependent
1317 LASSERT(use_gui, /**/);
1318 LASSERT(singleton_, /**/);
1319 return *singleton_->pimpl_->lyx_socket_.get();
1323 KeyMap & theTopLevelKeymap()
1325 LASSERT(singleton_, /**/);
1326 return singleton_->pimpl_->toplevel_keymap_;
1330 Converters & theConverters()
1332 LASSERT(singleton_, /**/);
1333 return singleton_->pimpl_->converters_;
1337 Converters & theSystemConverters()
1339 LASSERT(singleton_, /**/);
1340 return singleton_->pimpl_->system_converters_;
1344 Movers & theMovers()
1346 LASSERT(singleton_, /**/);
1347 return singleton_->pimpl_->movers_;
1351 Mover const & getMover(string const & fmt)
1353 LASSERT(singleton_, /**/);
1354 return singleton_->pimpl_->movers_(fmt);
1358 void setMover(string const & fmt, string const & command)
1360 LASSERT(singleton_, /**/);
1361 singleton_->pimpl_->movers_.set(fmt, command);
1365 Movers & theSystemMovers()
1367 LASSERT(singleton_, /**/);
1368 return singleton_->pimpl_->system_movers_;
1372 Messages const & getMessages(string const & language)
1374 LASSERT(singleton_, /**/);
1375 return singleton_->messages(language);
1379 Messages const & getGuiMessages()
1381 LASSERT(singleton_, /**/);
1382 return singleton_->pimpl_->messages_["GUI"];
1386 graphics::Previews & thePreviews()
1388 LASSERT(singleton_, /**/);
1389 return singleton_->pimpl_->preview_;
1393 Session & theSession()
1395 LASSERT(singleton_, /**/);
1396 return *singleton_->pimpl_->session_.get();
1400 CmdDef & theTopLevelCmdDef()
1402 LASSERT(singleton_, /**/);
1403 return singleton_->pimpl_->toplevel_cmddef_;
1407 SpellChecker * theSpellChecker()
1409 if (!singleton_->pimpl_->spell_checker_)
1411 return singleton_->pimpl_->spell_checker_;
1415 void setSpellChecker()
1417 SpellChecker::ChangeNumber speller_change_number =singleton_->pimpl_->spell_checker_ ?
1418 singleton_->pimpl_->spell_checker_->changeNumber() : 0;
1420 if (lyxrc.spellchecker == "native") {
1421 #if defined(USE_MACOSX_PACKAGING)
1422 if (!singleton_->pimpl_->apple_spell_checker_)
1423 singleton_->pimpl_->apple_spell_checker_ = new AppleSpellChecker();
1424 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->apple_spell_checker_;
1426 singleton_->pimpl_->spell_checker_ = 0;
1428 } else if (lyxrc.spellchecker == "aspell") {
1429 #if defined(USE_ASPELL)
1430 if (!singleton_->pimpl_->aspell_checker_)
1431 singleton_->pimpl_->aspell_checker_ = new AspellChecker();
1432 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->aspell_checker_;
1434 singleton_->pimpl_->spell_checker_ = 0;
1436 } else if (lyxrc.spellchecker == "enchant") {
1437 #if defined(USE_ENCHANT)
1438 if (!singleton_->pimpl_->enchant_checker_)
1439 singleton_->pimpl_->enchant_checker_ = new EnchantChecker();
1440 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->enchant_checker_;
1442 singleton_->pimpl_->spell_checker_ = 0;
1444 } else if (lyxrc.spellchecker == "hunspell") {
1445 #if defined(USE_HUNSPELL)
1446 if (!singleton_->pimpl_->hunspell_checker_)
1447 singleton_->pimpl_->hunspell_checker_ = new HunspellChecker();
1448 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->hunspell_checker_;
1450 singleton_->pimpl_->spell_checker_ = 0;
1453 singleton_->pimpl_->spell_checker_ = 0;
1455 if (singleton_->pimpl_->spell_checker_) {
1456 singleton_->pimpl_->spell_checker_->changeNumber(speller_change_number);
1457 singleton_->pimpl_->spell_checker_->advanceChangeNumber();