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 // Tell what files can be silently overwritten during batch export.
94 // Possible values are: NO_FILES, MAIN_FILE, ALL_FILES, UNSPECIFIED.
95 // Unless specified on command line (through the -f switch) or through the
96 // environment variable LYX_FORCE_OVERWRITE, the default will be MAIN_FILE.
98 OverwriteFiles force_overwrite = UNSPECIFIED;
103 // Filled with the command line arguments "foo" of "-sysdir foo" or
105 string cl_system_support;
106 string cl_user_support;
110 LyX * singleton_ = 0;
112 void showFileError(string const & error)
114 Alert::warning(_("Could not read configuration file"),
115 bformat(_("Error while reading the configuration file\n%1$s.\n"
116 "Please check your installation."), from_utf8(error)));
120 void reconfigureUserLyXDir()
122 string const configure_command = package().configure_command();
124 lyxerr << to_utf8(_("LyX: reconfiguring user directory")) << endl;
125 PathChanger p(package().user_support());
127 one.startscript(Systemcall::Wait, configure_command);
128 lyxerr << "LyX: " << to_utf8(_("Done!")) << endl;
133 /// The main application class private implementation.
136 Impl() : spell_checker_(0), apple_spell_checker_(0), aspell_checker_(0), enchant_checker_(0), hunspell_checker_(0)
138 // Set the default User Interface language as soon as possible.
139 // The language used will be derived from the environment
141 messages_["GUI"] = Messages();
146 delete apple_spell_checker_;
147 delete aspell_checker_;
148 delete enchant_checker_;
149 delete hunspell_checker_;
153 BufferList buffer_list_;
155 KeyMap toplevel_keymap_;
157 CmdDef toplevel_cmddef_;
159 boost::scoped_ptr<Server> lyx_server_;
161 boost::scoped_ptr<ServerSocket> lyx_socket_;
163 boost::scoped_ptr<frontend::Application> application_;
164 /// lyx session, containing lastfiles, lastfilepos, and lastopened
165 boost::scoped_ptr<Session> session_;
167 /// Files to load at start.
168 vector<string> files_to_load_;
170 /// The messages translators.
171 map<string, Messages> messages_;
173 /// The file converters.
174 Converters converters_;
176 // The system converters copy after reading lyxrc.defaults.
177 Converters system_converters_;
182 Movers system_movers_;
184 /// has this user started lyx for the first time?
186 /// the parsed command line batch command if any
187 vector<string> batch_commands;
190 graphics::Previews preview_;
192 SpellChecker * spell_checker_;
194 SpellChecker * apple_spell_checker_;
196 SpellChecker * aspell_checker_;
198 SpellChecker * enchant_checker_;
200 SpellChecker * hunspell_checker_;
204 frontend::Application * theApp()
207 return singleton_->pimpl_->application_.get();
220 void lyx_exit(int exit_code)
223 // Something wrong happened so better save everything, just in
228 // Properly crash in debug mode in order to get a useful backtrace.
232 // In release mode, try to exit gracefully.
234 theApp()->exit(exit_code);
248 Messages & LyX::messages(string const & language)
250 map<string, Messages>::iterator it = pimpl_->messages_.find(language);
252 if (it != pimpl_->messages_.end())
255 pair<map<string, Messages>::iterator, bool> result =
256 pimpl_->messages_.insert(make_pair(language, Messages(language)));
258 LASSERT(result.second, /**/);
259 return result.first->second;
263 void setRcGuiLanguage()
265 LASSERT(singleton_, /**/);
266 if (lyxrc.gui_language == "auto")
268 Language const * language = languages.getLanguage(lyxrc.gui_language);
270 LYXERR(Debug::LOCALE, "Setting LANGUAGE to " << language->code());
271 if (!setEnv("LANGUAGE", language->code()))
272 LYXERR(Debug::LOCALE, "\t... failed!");
274 LYXERR(Debug::LOCALE, "Setting LC_ALL to en_US");
275 if (!setEnv("LC_ALL", "en_US"))
276 LYXERR(Debug::LOCALE, "\t... failed!");
278 singleton_->pimpl_->messages_["GUI"] = Messages();
282 int LyX::exec(int & argc, char * argv[])
284 // Minimal setting of locale before parsing command line
286 init_package(os::utf8_argv(0), string(), string(),
287 top_build_dir_is_one_level_up);
288 } catch (ExceptionMessage const & message) {}
291 // Here we need to parse the command line. At least
292 // we need to parse for "-dbg" and "-help"
293 easyParse(argc, argv);
296 init_package(os::utf8_argv(0),
297 cl_system_support, cl_user_support,
298 top_build_dir_is_one_level_up);
299 } catch (ExceptionMessage const & message) {
300 if (message.type_ == ErrorException) {
301 Alert::error(message.title_, message.details_);
303 } else if (message.type_ == WarningException) {
304 Alert::warning(message.title_, message.details_);
308 // Reinit the messages machinery in case package() knows
309 // something interesting about the locale directory.
313 // FIXME: create a ConsoleApplication
314 int exit_status = init(argc, argv);
320 // this is correct, since return values are inverted.
321 exit_status = !loadFiles();
323 if (pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
328 BufferList::iterator begin = pimpl_->buffer_list_.begin();
330 bool final_success = false;
331 for (BufferList::iterator I = begin; I != pimpl_->buffer_list_.end(); ++I) {
333 if (buf != buf->masterBuffer())
335 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
336 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
338 for (; bcit != bcend; bcit++) {
339 LYXERR(Debug::ACTION, "Buffer::dispatch: cmd: " << *bcit);
340 buf->dispatch(*bcit, dr);
341 final_success |= !dr.error();
345 return !final_success;
348 // Let the frontend parse and remove all arguments that it knows
349 pimpl_->application_.reset(createApplication(argc, argv));
351 // Reestablish our defaults, as Qt overwrites them
352 // after createApplication()
355 // Parse and remove all known arguments in the LyX singleton
356 // Give an error for all remaining ones.
357 int exit_status = init(argc, argv);
359 // Kill the application object before exiting.
360 pimpl_->application_.reset();
367 /* Create a CoreApplication class that will provide the main event loop
368 * and the socket callback registering. With Qt4, only QtCore
369 * library would be needed.
370 * When this is done, a server_mode could be created and the following two
371 * line would be moved out from here.
373 // Note: socket callback must be registered after init(argc, argv)
374 // such that package().temp_dir() is properly initialized.
375 pimpl_->lyx_server_.reset(new Server(lyxrc.lyxpipes));
376 pimpl_->lyx_socket_.reset(new ServerSocket(
377 FileName(package().temp_dir().absFileName() + "/lyxsocket")));
379 // Start the real execution loop.
380 exit_status = pimpl_->application_->exec();
388 void LyX::prepareExit()
390 // Clear the clipboard and selection stack:
391 cap::clearCutStack();
392 cap::clearSelection();
394 // Write the index file of the converter cache
395 ConverterCache::get().writeIndex();
397 // close buffers first
398 pimpl_->buffer_list_.closeAll();
400 // register session changes and shutdown server and socket
402 if (pimpl_->session_)
403 pimpl_->session_->writeFile();
404 pimpl_->session_.reset();
405 pimpl_->lyx_server_.reset();
406 pimpl_->lyx_socket_.reset();
409 // do any other cleanup procedures now
410 if (package().temp_dir() != package().system_temp_dir()) {
411 string const abs_tmpdir = package().temp_dir().absFileName();
412 if (!contains(package().temp_dir().absFileName(), "lyx_tmpdir")) {
413 docstring const msg =
414 bformat(_("%1$s does not appear like a LyX created temporary directory."),
415 from_utf8(abs_tmpdir));
416 Alert::warning(_("Cannot remove temporary directory"), msg);
418 LYXERR(Debug::INFO, "Deleting tmp dir "
419 << package().temp_dir().absFileName());
420 if (!package().temp_dir().destroyDirectory()) {
421 docstring const msg =
422 bformat(_("Unable to remove the temporary directory %1$s"),
423 from_utf8(package().temp_dir().absFileName()));
424 Alert::warning(_("Unable to remove temporary directory"), msg);
429 // Kill the application object before exiting. This avoids crashes
430 // when exiting on Linux.
431 if (pimpl_->application_)
432 pimpl_->application_.reset();
436 void LyX::earlyExit(int status)
438 LASSERT(pimpl_->application_.get(), /**/);
439 // LyX::pimpl_::application_ is not initialised at this
440 // point so it's safe to just exit after some cleanup.
446 int LyX::init(int & argc, char * argv[])
448 // check for any spurious extra arguments
449 // other than documents
450 for (int argi = 1; argi < argc ; ++argi) {
451 if (argv[argi][0] == '-') {
453 bformat(_("Wrong command line option `%1$s'. Exiting."),
454 from_utf8(os::utf8_argv(argi)))) << endl;
459 // Initialization of LyX (reads lyxrc and more)
460 LYXERR(Debug::INIT, "Initializing LyX::init...");
461 bool success = init();
462 LYXERR(Debug::INIT, "Initializing LyX::init...done");
466 // Remaining arguments are assumed to be files to load.
467 for (int argi = argc - 1; argi >= 1; --argi)
468 pimpl_->files_to_load_.push_back(os::utf8_argv(argi));
471 pimpl_->files_to_load_.push_back(
472 i18nLibFileSearch("examples", "splash.lyx").absFileName());
479 bool LyX::loadFiles()
481 LASSERT(!use_gui, /**/);
483 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
484 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
486 for (; it != end; ++it) {
487 // get absolute path of file and add ".lyx" to
488 // the filename if necessary
489 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
495 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFileName(), false);
496 if (buf->loadLyXFile(fname)) {
497 ErrorList const & el = buf->errorList("Parse");
499 for_each(el.begin(), el.end(),
500 bind(&LyX::printError, this, _1));
503 pimpl_->buffer_list_.release(buf);
511 void execBatchCommands()
513 LASSERT(singleton_, /**/);
514 singleton_->execCommands();
518 void LyX::execCommands()
520 // The advantage of doing this here is that the event loop
521 // is already started. So any need for interaction will be
524 // if reconfiguration is needed.
525 if (LayoutFileList::get().empty()) {
526 switch (Alert::prompt(
527 _("No textclass is found"),
528 _("LyX will only have minimal functionality because no textclasses "
529 "have been found. You can either try to reconfigure LyX normally, "
530 "try to reconfigure using only the defaults, or continue."),
537 // regular reconfigure
538 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
541 // reconfigure --without-latex-config
542 lyx::dispatch(FuncRequest(LFUN_RECONFIGURE,
543 " --without-latex-config"));
550 // create the first main window
551 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
553 if (!pimpl_->files_to_load_.empty()) {
554 // if some files were specified at command-line we assume that the
555 // user wants to edit *these* files and not to restore the session.
556 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
558 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
560 // clear this list to save a few bytes of RAM
561 pimpl_->files_to_load_.clear();
563 pimpl_->application_->restoreGuiSession();
565 // Execute batch commands if available
566 if (pimpl_->batch_commands.empty())
569 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
570 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
571 for (; bcit != bcend; bcit++) {
572 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
573 lyx::dispatch(lyxaction.lookupFunc(*bcit));
581 The SIGHUP signal does not exist on Windows and does not need to be handled.
583 Windows handles SIGFPE and SIGSEGV signals as expected.
585 Ctrl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
586 cause a new thread to be spawned. This may well result in unexpected
587 behaviour by the single-threaded LyX.
589 SIGTERM signals will come only from another process actually sending
590 that signal using 'raise' in Windows' POSIX compatability layer. It will
591 not come from the general "terminate process" methods that everyone
592 actually uses (and which can't be trapped). Killing an app 'politely' on
593 Windows involves first sending a WM_CLOSE message, something that is
594 caught already by the Qt frontend.
596 For more information see:
598 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
599 ...signals are mostly useless on Windows for a variety of reasons that are
602 'UNIX Application Migration Guide, Chapter 9'
603 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
605 'How To Terminate an Application "Cleanly" in Win32'
606 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
610 static void error_handler(int err_sig)
612 // Throw away any signals other than the first one received.
613 static sig_atomic_t handling_error = false;
616 handling_error = true;
618 // We have received a signal indicating a fatal error, so
619 // try and save the data ASAP.
622 // These lyxerr calls may or may not work:
624 // Signals are asynchronous, so the main program may be in a very
625 // fragile state when a signal is processed and thus while a signal
626 // handler function executes.
627 // In general, therefore, we should avoid performing any
628 // I/O operations or calling most library and system functions from
631 // This shouldn't matter here, however, as we've already invoked
637 msg = _("SIGHUP signal caught!\nBye.");
641 msg = _("SIGFPE signal caught!\nBye.");
644 msg = _("SIGSEGV signal caught!\n"
645 "Sorry, you have found a bug in LyX, "
646 "hope you have not lost any data.\n"
647 "Please read the bug-reporting instructions "
648 "in 'Help->Introduction' and send us a bug report, "
649 "if necessary. Thanks !\nBye.");
658 lyxerr << "\nlyx: " << msg << endl;
659 // try to make a GUI message
660 Alert::error(_("LyX crashed!"), msg);
663 // Deinstall the signal handlers
665 signal(SIGHUP, SIG_DFL);
667 signal(SIGINT, SIG_DFL);
668 signal(SIGFPE, SIG_DFL);
669 signal(SIGSEGV, SIG_DFL);
670 signal(SIGTERM, SIG_DFL);
673 if (err_sig == SIGSEGV ||
674 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty())) {
676 if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty()) {
679 // with abort() it crashes again.
692 void LyX::printError(ErrorItem const & ei)
694 docstring tmp = _("LyX: ") + ei.error + char_type(':')
696 cerr << to_utf8(tmp) << endl;
703 signal(SIGHUP, error_handler);
705 signal(SIGFPE, error_handler);
706 signal(SIGSEGV, error_handler);
707 signal(SIGINT, error_handler);
708 signal(SIGTERM, error_handler);
709 // SIGPIPE can be safely ignored.
711 lyxrc.tempdir_path = package().temp_dir().absFileName();
712 lyxrc.document_path = package().document_dir().absFileName();
714 if (lyxrc.example_path.empty()) {
715 lyxrc.example_path = addPath(package().system_support().absFileName(),
718 if (lyxrc.template_path.empty()) {
719 lyxrc.template_path = addPath(package().system_support().absFileName(),
724 // Read configuration files
727 // This one may have been distributed along with LyX.
728 if (!readRcFile("lyxrc.dist"))
731 // Set the language defined by the distributor.
734 // Set the PATH correctly.
735 #if !defined (USE_POSIX_PACKAGING)
736 // Add the directory containing the LyX executable to the path
737 // so that LyX can find things like tex2lyx.
738 if (package().build_support().empty())
739 prependEnvPath("PATH", package().binary_dir().absFileName());
741 if (!lyxrc.path_prefix.empty())
742 prependEnvPath("PATH", lyxrc.path_prefix);
744 // Check that user LyX directory is ok.
745 if (queryUserLyXDir(package().explicit_user_support()))
746 reconfigureUserLyXDir();
749 // No need for a splash when there is no GUI
751 // Default is to overwrite the main file during export, unless
752 // the -f switch was specified or LYX_FORCE_OVERWRITE was set
753 if (force_overwrite == UNSPECIFIED) {
754 string const what = getEnv("LYX_FORCE_OVERWRITE");
756 force_overwrite = ALL_FILES;
757 else if (what == "none")
758 force_overwrite = NO_FILES;
760 force_overwrite = MAIN_FILE;
764 // This one is generated in user_support directory by lib/configure.py.
765 if (!readRcFile("lyxrc.defaults"))
768 // Query the OS to know what formats are viewed natively
769 formats.setAutoOpen();
771 // Read lyxrc.dist again to be able to override viewer auto-detection.
772 readRcFile("lyxrc.dist");
774 // Set again the language defined by the distributor.
777 system_lyxrc = lyxrc;
778 system_formats = formats;
779 pimpl_->system_converters_ = pimpl_->converters_;
780 pimpl_->system_movers_ = pimpl_->movers_;
781 system_lcolor = lcolor;
783 // This one is edited through the preferences dialog.
784 if (!readRcFile("preferences"))
787 if (!readEncodingsFile("encodings", "unicodesymbols"))
789 if (!readLanguagesFile("languages"))
792 // Set the language defined by the user.
795 LYXERR(Debug::INIT, "Reading layouts...");
797 LayoutFileList::get().read();
799 theModuleList.read();
801 // read keymap and ui files in batch mode as well
802 // because InsetInfo needs to know these to produce
803 // the correct output
805 // Set up command definitions
806 pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
809 pimpl_->toplevel_keymap_.read("site");
810 pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
811 // load user bind file user.bind
812 pimpl_->toplevel_keymap_.read("user", 0, KeyMap::MissingOK);
814 if (lyxerr.debugging(Debug::LYXRC))
817 os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
818 if (!lyxrc.path_prefix.empty())
819 prependEnvPath("PATH", lyxrc.path_prefix);
821 FileName const document_path(lyxrc.document_path);
822 if (document_path.exists() && document_path.isDirectory())
823 package().document_dir() = document_path;
825 package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
826 if (package().temp_dir().empty()) {
827 Alert::error(_("Could not create temporary directory"),
828 bformat(_("Could not create a temporary directory in\n"
830 "Make sure that this path exists and is writable and try again."),
831 from_utf8(lyxrc.tempdir_path)));
832 // createLyXTmpDir() tries sufficiently hard to create a
833 // usable temp dir, so the probability to come here is
834 // close to zero. We therefore don't try to overcome this
835 // problem with e.g. asking the user for a new path and
836 // trying again but simply exit.
840 LYXERR(Debug::INIT, "LyX tmp dir: `"
841 << package().temp_dir().absFileName() << '\'');
843 LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
844 pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
846 // This must happen after package initialization and after lyxrc is
847 // read, therefore it can't be done by a static object.
848 ConverterCache::init();
854 void emergencyCleanup()
856 // what to do about tmpfiles is non-obvious. we would
857 // like to delete any we find, but our lyxdir might
858 // contain documents etc. which might be helpful on
861 singleton_->pimpl_->buffer_list_.emergencyWriteAll();
863 if (singleton_->pimpl_->lyx_server_)
864 singleton_->pimpl_->lyx_server_->emergencyCleanup();
865 singleton_->pimpl_->lyx_server_.reset();
866 singleton_->pimpl_->lyx_socket_.reset();
871 // return true if file does not exist or is older than configure.py.
872 static bool needsUpdate(string const & file)
874 // We cannot initialize configure_script directly because the package
875 // is not initialized yet when static objects are constructed.
876 static FileName configure_script;
877 static bool firstrun = true;
880 FileName(addName(package().system_support().absFileName(),
886 FileName(addName(package().user_support().absFileName(), file));
887 return !absfile.exists()
888 || configure_script.lastModified() > absfile.lastModified();
892 bool LyX::queryUserLyXDir(bool explicit_userdir)
894 // Does user directory exist?
895 FileName const sup = package().user_support();
896 if (sup.exists() && sup.isDirectory()) {
899 return needsUpdate("lyxrc.defaults")
900 || needsUpdate("lyxmodules.lst")
901 || needsUpdate("textclass.lst")
902 || needsUpdate("packages.lst");
905 first_start = !explicit_userdir;
907 // If the user specified explicitly a directory, ask whether
908 // to create it. If the user says "no", then exit.
909 if (explicit_userdir &&
911 _("Missing user LyX directory"),
912 bformat(_("You have specified a non-existent user "
913 "LyX directory, %1$s.\n"
914 "It is needed to keep your own configuration."),
915 from_utf8(package().user_support().absFileName())),
917 _("&Create directory"),
919 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
920 earlyExit(EXIT_FAILURE);
923 lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
924 from_utf8(sup.absFileName()))) << endl;
926 if (!sup.createDirectory(0755)) {
927 // Failed, so let's exit.
928 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
930 earlyExit(EXIT_FAILURE);
937 bool LyX::readRcFile(string const & name)
939 LYXERR(Debug::INIT, "About to read " << name << "... ");
941 FileName const lyxrc_path = libFileSearch(string(), name);
942 if (!lyxrc_path.empty()) {
943 LYXERR(Debug::INIT, "Found in " << lyxrc_path);
944 if (lyxrc.read(lyxrc_path) < 0) {
949 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
954 // Read the languages file `name'
955 bool LyX::readLanguagesFile(string const & name)
957 LYXERR(Debug::INIT, "About to read " << name << "...");
959 FileName const lang_path = libFileSearch(string(), name);
960 if (lang_path.empty()) {
964 languages.read(lang_path);
969 // Read the encodings file `name'
970 bool LyX::readEncodingsFile(string const & enc_name,
971 string const & symbols_name)
973 LYXERR(Debug::INIT, "About to read " << enc_name << " and "
974 << symbols_name << "...");
976 FileName const symbols_path = libFileSearch(string(), symbols_name);
977 if (symbols_path.empty()) {
978 showFileError(symbols_name);
982 FileName const enc_path = libFileSearch(string(), enc_name);
983 if (enc_path.empty()) {
984 showFileError(enc_name);
987 encodings.read(enc_path, symbols_path);
994 /// return the the number of arguments consumed
995 typedef boost::function<int(string const &, string const &, string &)> cmd_helper;
997 int parse_dbg(string const & arg, string const &, string &)
1000 lyxerr << to_utf8(_("List of supported debug flags:")) << endl;
1001 Debug::showTags(lyxerr);
1004 lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1006 lyxerr.setLevel(Debug::value(arg));
1007 Debug::showLevel(lyxerr, lyxerr.level());
1012 int parse_help(string const &, string const &, string &)
1015 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1016 "Command line switches (case sensitive):\n"
1017 "\t-help summarize LyX usage\n"
1018 "\t-userdir dir set user directory to dir\n"
1019 "\t-sysdir dir set system directory to dir\n"
1020 "\t-geometry WxH+X+Y set geometry of the main window\n"
1021 "\t-dbg feature[,feature]...\n"
1022 " select the features to debug.\n"
1023 " Type `lyx -dbg' to see the list of features\n"
1024 "\t-x [--execute] command\n"
1025 " where command is a lyx command.\n"
1026 "\t-e [--export] fmt\n"
1027 " where fmt is the export format of choice.\n"
1028 " Look on Tools->Preferences->File formats->Format\n"
1029 " to get an idea which parameters should be passed.\n"
1030 " Note that the order of -e and -x switches matters.\n"
1031 "\t-i [--import] fmt file.xxx\n"
1032 " where fmt is the import format of choice\n"
1033 " and file.xxx is the file to be imported.\n"
1034 "\t-f [--force-overwrite] what\n"
1035 " where what is either `all', `main' or `none',\n"
1036 " specifying whether all files, main file only, or no files,\n"
1037 " respectively, are to be overwritten during a batch export.\n"
1038 " Anything else is equivalent to `all', but is not consumed.\n"
1039 "\t-batch execute commands without launching GUI and exit.\n"
1040 "\t-version summarize version and build info\n"
1041 "Check the LyX man page for more details.")) << endl;
1047 int parse_version(string const &, string const &, string &)
1049 lyxerr << "LyX " << lyx_version
1050 << " (" << lyx_release_date << ")" << endl;
1051 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
1053 lyxerr << lyx_version_info << endl;
1059 int parse_sysdir(string const & arg, string const &, string &)
1062 Alert::error(_("No system directory"),
1063 _("Missing directory for -sysdir switch"));
1066 cl_system_support = arg;
1071 int parse_userdir(string const & arg, string const &, string &)
1074 Alert::error(_("No user directory"),
1075 _("Missing directory for -userdir switch"));
1078 cl_user_support = arg;
1083 int parse_execute(string const & arg, string const &, string & batch)
1086 Alert::error(_("Incomplete command"),
1087 _("Missing command string after --execute switch"));
1095 int parse_export(string const & type, string const &, string & batch)
1098 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1099 "--export switch")) << endl;
1102 batch = "buffer-export " + type;
1108 int parse_import(string const & type, string const & file, string & batch)
1111 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1112 "--import switch")) << endl;
1116 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1120 batch = "buffer-import " + type + ' ' + file;
1125 int parse_geometry(string const & arg1, string const &, string &)
1128 // don't remove "-geometry", it will be pruned out later in the
1129 // frontend if need be.
1134 int parse_batch(string const &, string const &, string &)
1141 int parse_force(string const & arg, string const &, string &)
1144 force_overwrite = ALL_FILES;
1146 } else if (arg == "main") {
1147 force_overwrite = MAIN_FILE;
1149 } else if (arg == "none") {
1150 force_overwrite = NO_FILES;
1153 force_overwrite = ALL_FILES;
1161 void LyX::easyParse(int & argc, char * argv[])
1163 map<string, cmd_helper> cmdmap;
1165 cmdmap["-dbg"] = parse_dbg;
1166 cmdmap["-help"] = parse_help;
1167 cmdmap["--help"] = parse_help;
1168 cmdmap["-version"] = parse_version;
1169 cmdmap["--version"] = parse_version;
1170 cmdmap["-sysdir"] = parse_sysdir;
1171 cmdmap["-userdir"] = parse_userdir;
1172 cmdmap["-x"] = parse_execute;
1173 cmdmap["--execute"] = parse_execute;
1174 cmdmap["-e"] = parse_export;
1175 cmdmap["--export"] = parse_export;
1176 cmdmap["-i"] = parse_import;
1177 cmdmap["--import"] = parse_import;
1178 cmdmap["-geometry"] = parse_geometry;
1179 cmdmap["-batch"] = parse_batch;
1180 cmdmap["-f"] = parse_force;
1181 cmdmap["--force-overwrite"] = parse_force;
1183 for (int i = 1; i < argc; ++i) {
1184 map<string, cmd_helper>::const_iterator it
1185 = cmdmap.find(argv[i]);
1187 // don't complain if not found - may be parsed later
1188 if (it == cmdmap.end())
1192 (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
1194 (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
1197 int const remove = 1 + it->second(arg, arg2, batch);
1199 pimpl_->batch_commands.push_back(batch);
1201 // Now, remove used arguments by shifting
1202 // the following ones remove places down.
1204 os::remove_internal_args(i, remove);
1206 for (int j = i; j < argc; ++j)
1207 argv[j] = argv[j + remove];
1214 FuncStatus getStatus(FuncRequest const & action)
1216 LASSERT(theApp(), /**/);
1217 return theApp()->getStatus(action);
1221 void dispatch(FuncRequest const & action)
1223 LASSERT(theApp(), /**/);
1224 return theApp()->dispatch(action);
1228 void dispatch(FuncRequest const & action, DispatchResult & dr)
1230 LASSERT(theApp(), /**/);
1231 return theApp()->dispatch(action, dr);
1235 BufferList & theBufferList()
1237 LASSERT(singleton_, /**/);
1238 return singleton_->pimpl_->buffer_list_;
1242 Server & theServer()
1244 // FIXME: this should not be use_gui dependent
1245 LASSERT(use_gui, /**/);
1246 LASSERT(singleton_, /**/);
1247 return *singleton_->pimpl_->lyx_server_.get();
1251 ServerSocket & theServerSocket()
1253 // FIXME: this should not be use_gui dependent
1254 LASSERT(use_gui, /**/);
1255 LASSERT(singleton_, /**/);
1256 return *singleton_->pimpl_->lyx_socket_.get();
1260 KeyMap & theTopLevelKeymap()
1262 LASSERT(singleton_, /**/);
1263 return singleton_->pimpl_->toplevel_keymap_;
1267 Converters & theConverters()
1269 LASSERT(singleton_, /**/);
1270 return singleton_->pimpl_->converters_;
1274 Converters & theSystemConverters()
1276 LASSERT(singleton_, /**/);
1277 return singleton_->pimpl_->system_converters_;
1281 Movers & theMovers()
1283 LASSERT(singleton_, /**/);
1284 return singleton_->pimpl_->movers_;
1288 Mover const & getMover(string const & fmt)
1290 LASSERT(singleton_, /**/);
1291 return singleton_->pimpl_->movers_(fmt);
1295 void setMover(string const & fmt, string const & command)
1297 LASSERT(singleton_, /**/);
1298 singleton_->pimpl_->movers_.set(fmt, command);
1302 Movers & theSystemMovers()
1304 LASSERT(singleton_, /**/);
1305 return singleton_->pimpl_->system_movers_;
1309 Messages const & getMessages(string const & language)
1311 LASSERT(singleton_, /**/);
1312 return singleton_->messages(language);
1316 Messages const & getGuiMessages()
1318 LASSERT(singleton_, /**/);
1319 return singleton_->pimpl_->messages_["GUI"];
1323 graphics::Previews & thePreviews()
1325 LASSERT(singleton_, /**/);
1326 return singleton_->pimpl_->preview_;
1330 Session & theSession()
1332 LASSERT(singleton_, /**/);
1333 return *singleton_->pimpl_->session_.get();
1337 CmdDef & theTopLevelCmdDef()
1339 LASSERT(singleton_, /**/);
1340 return singleton_->pimpl_->toplevel_cmddef_;
1344 SpellChecker * theSpellChecker()
1346 if (!singleton_->pimpl_->spell_checker_)
1348 return singleton_->pimpl_->spell_checker_;
1352 void setSpellChecker()
1354 #if defined(USE_MACOSX_PACKAGING)
1355 if (lyxrc.spellchecker == "native") {
1356 if (!singleton_->pimpl_->apple_spell_checker_)
1357 singleton_->pimpl_->apple_spell_checker_ = new AppleSpellChecker();
1358 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->apple_spell_checker_;
1362 #if defined(USE_ASPELL)
1363 if (lyxrc.spellchecker == "aspell") {
1364 if (!singleton_->pimpl_->aspell_checker_)
1365 singleton_->pimpl_->aspell_checker_ = new AspellChecker();
1366 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->aspell_checker_;
1370 #if defined(USE_ENCHANT)
1371 if (lyxrc.spellchecker == "enchant") {
1372 if (!singleton_->pimpl_->enchant_checker_)
1373 singleton_->pimpl_->enchant_checker_ = new EnchantChecker();
1374 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->enchant_checker_;
1378 #if defined(USE_HUNSPELL)
1379 if (lyxrc.spellchecker == "hunspell") {
1380 if (!singleton_->pimpl_->hunspell_checker_)
1381 singleton_->pimpl_->hunspell_checker_ = new HunspellChecker();
1382 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->hunspell_checker_;
1386 singleton_->pimpl_->spell_checker_ = 0;