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 "LayoutFile.h"
22 #include "BufferList.h"
25 #include "ConverterCache.h"
26 #include "Converter.h"
27 #include "CutAndPaste.h"
29 #include "ErrorList.h"
31 #include "FuncStatus.h"
35 #include "LyXAction.h"
38 #include "ModuleList.h"
41 #include "ServerSocket.h"
44 #include "frontends/alert.h"
45 #include "frontends/Application.h"
47 #include "support/lassert.h"
48 #include "support/debug.h"
49 #include "support/environment.h"
50 #include "support/ExceptionMessage.h"
51 #include "support/filetools.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h"
54 #include "support/Messages.h"
55 #include "support/os.h"
56 #include "support/Package.h"
57 #include "support/Path.h"
58 #include "support/Systemcall.h"
60 #include <boost/bind.hpp>
61 #include <boost/scoped_ptr.hpp>
72 using namespace lyx::support;
76 namespace Alert = frontend::Alert;
77 namespace os = support::os;
81 // Are we using the GUI at all? We default to true and this is changed
82 // to false when the export feature is used.
88 // Filled with the command line arguments "foo" of "-sysdir foo" or
90 string cl_system_support;
91 string cl_user_support;
97 void showFileError(string const & error)
99 Alert::warning(_("Could not read configuration file"),
100 bformat(_("Error while reading the configuration file\n%1$s.\n"
101 "Please check your installation."), from_utf8(error)));
105 void reconfigureUserLyXDir()
107 string const configure_command = package().configure_command();
109 lyxerr << to_utf8(_("LyX: reconfiguring user directory")) << endl;
110 PathChanger p(package().user_support());
112 one.startscript(Systemcall::Wait, configure_command);
113 lyxerr << "LyX: " << to_utf8(_("Done!")) << endl;
119 /// The main application class private implementation.
124 // Set the default User Interface language as soon as possible.
125 // The language used will be derived from the environment
127 messages_["GUI"] = Messages();
129 /// our function handler
132 BufferList buffer_list_;
134 KeyMap toplevel_keymap_;
136 CmdDef toplevel_cmddef_;
138 boost::scoped_ptr<Server> lyx_server_;
140 boost::scoped_ptr<ServerSocket> lyx_socket_;
142 boost::scoped_ptr<frontend::Application> application_;
143 /// lyx session, containing lastfiles, lastfilepos, and lastopened
144 boost::scoped_ptr<Session> session_;
146 /// Files to load at start.
147 vector<string> files_to_load_;
149 /// The messages translators.
150 map<string, Messages> messages_;
152 /// The file converters.
153 Converters converters_;
155 // The system converters copy after reading lyxrc.defaults.
156 Converters system_converters_;
161 Movers system_movers_;
163 /// has this user started lyx for the first time?
165 /// the parsed command line batch command if any
166 vector<string> batch_commands;
170 frontend::Application * theApp()
173 return singleton_->pimpl_->application_.get();
185 void LyX::exit(int exit_code) const
188 // Something wrong happened so better save everything, just in
193 // Properly crash in debug mode in order to get a useful backtrace.
197 // In release mode, try to exit gracefully.
199 theApp()->exit(exit_code);
207 LASSERT(singleton_, /**/);
212 LyX const & LyX::cref()
214 LASSERT(singleton_, /**/);
227 BufferList & LyX::bufferList()
229 return pimpl_->buffer_list_;
233 BufferList const & LyX::bufferList() const
235 return pimpl_->buffer_list_;
239 Session & LyX::session()
241 LASSERT(pimpl_->session_.get(), /**/);
242 return *pimpl_->session_.get();
246 Session const & LyX::session() const
248 LASSERT(pimpl_->session_.get(), /**/);
249 return *pimpl_->session_.get();
253 LyXFunc & LyX::lyxFunc()
255 return pimpl_->lyxfunc_;
259 LyXFunc const & LyX::lyxFunc() const
261 return pimpl_->lyxfunc_;
265 Server & LyX::server()
267 LASSERT(pimpl_->lyx_server_.get(), /**/);
268 return *pimpl_->lyx_server_.get();
272 Server const & LyX::server() const
274 LASSERT(pimpl_->lyx_server_.get(), /**/);
275 return *pimpl_->lyx_server_.get();
279 ServerSocket & LyX::socket()
281 LASSERT(pimpl_->lyx_socket_.get(), /**/);
282 return *pimpl_->lyx_socket_.get();
286 ServerSocket const & LyX::socket() const
288 LASSERT(pimpl_->lyx_socket_.get(), /**/);
289 return *pimpl_->lyx_socket_.get();
293 frontend::Application & LyX::application()
295 LASSERT(pimpl_->application_.get(), /**/);
296 return *pimpl_->application_.get();
300 frontend::Application const & LyX::application() const
302 LASSERT(pimpl_->application_.get(), /**/);
303 return *pimpl_->application_.get();
307 CmdDef & LyX::topLevelCmdDef()
309 return pimpl_->toplevel_cmddef_;
313 Converters & LyX::converters()
315 return pimpl_->converters_;
319 Converters & LyX::systemConverters()
321 return pimpl_->system_converters_;
325 Messages & LyX::getMessages(string const & language)
327 map<string, Messages>::iterator it = pimpl_->messages_.find(language);
329 if (it != pimpl_->messages_.end())
332 pair<map<string, Messages>::iterator, bool> result =
333 pimpl_->messages_.insert(make_pair(language, Messages(language)));
335 LASSERT(result.second, /**/);
336 return result.first->second;
340 Messages & LyX::getGuiMessages()
342 return pimpl_->messages_["GUI"];
346 void LyX::setRcGuiLanguage()
348 if (lyxrc.gui_language == "auto")
350 LYXERR(Debug::LOCALE, "Setting LANGUAGE to " << lyxrc.gui_language);
351 if (!setEnv("LANGUAGE", lyxrc.gui_language))
352 LYXERR(Debug::LOCALE, "\t... failed!");
353 LYXERR(Debug::LOCALE, "Setting LC_ALL to en_US");
354 if (!setEnv("LC_ALL", "en_US"))
355 LYXERR(Debug::LOCALE, "\t... failed!");
356 pimpl_->messages_["GUI"] = Messages();
360 int LyX::exec(int & argc, char * argv[])
362 // Here we need to parse the command line. At least
363 // we need to parse for "-dbg" and "-help"
364 easyParse(argc, argv);
367 init_package(to_utf8(from_local8bit(argv[0])),
368 cl_system_support, cl_user_support,
369 top_build_dir_is_one_level_up);
370 } catch (ExceptionMessage const & message) {
371 if (message.type_ == ErrorException) {
372 Alert::error(message.title_, message.details_);
374 } else if (message.type_ == WarningException) {
375 Alert::warning(message.title_, message.details_);
379 // Reinit the messages machinery in case package() knows
380 // something interesting about the locale directory.
384 // FIXME: create a ConsoleApplication
385 int exit_status = init(argc, argv);
391 // this is correct, since return values are inverted.
392 exit_status = !loadFiles();
394 if (pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
399 BufferList::iterator begin = pimpl_->buffer_list_.begin();
401 bool final_success = false;
402 for (BufferList::iterator I = begin; I != pimpl_->buffer_list_.end(); ++I) {
404 if (buf != buf->masterBuffer())
406 bool success = false;
407 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
408 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
409 for (; bcit != bcend; bcit++) {
410 buf->dispatch(*bcit, &success);
411 final_success |= success;
415 return !final_success;
418 // Let the frontend parse and remove all arguments that it knows
419 pimpl_->application_.reset(createApplication(argc, argv));
421 // Reestablish our defaults, as Qt overwrites them
422 // after createApplication()
425 // Parse and remove all known arguments in the LyX singleton
426 // Give an error for all remaining ones.
427 int exit_status = init(argc, argv);
429 // Kill the application object before exiting.
430 pimpl_->application_.reset();
437 /* Create a CoreApplication class that will provide the main event loop
438 * and the socket callback registering. With Qt4, only QtCore
439 * library would be needed.
440 * When this is done, a server_mode could be created and the following two
441 * line would be moved out from here.
443 // Note: socket callback must be registered after init(argc, argv)
444 // such that package().temp_dir() is properly initialized.
445 pimpl_->lyx_server_.reset(new Server(&pimpl_->lyxfunc_, lyxrc.lyxpipes));
446 pimpl_->lyx_socket_.reset(new ServerSocket(&pimpl_->lyxfunc_,
447 FileName(package().temp_dir().absFilename() + "/lyxsocket")));
449 // Start the real execution loop.
450 exit_status = pimpl_->application_->exec();
458 void LyX::prepareExit()
460 // Clear the clipboard and selection stack:
461 cap::clearCutStack();
462 cap::clearSelection();
464 // close buffers first
465 pimpl_->buffer_list_.closeAll();
467 // register session changes and shutdown server and socket
469 if (pimpl_->session_)
470 pimpl_->session_->writeFile();
471 pimpl_->session_.reset();
472 pimpl_->lyx_server_.reset();
473 pimpl_->lyx_socket_.reset();
476 // do any other cleanup procedures now
477 if (package().temp_dir() != package().system_temp_dir()) {
478 string const abs_tmpdir = package().temp_dir().absFilename();
479 if (!contains(package().temp_dir().absFilename(), "lyx_tmpdir")) {
480 docstring const msg =
481 bformat(_("%1$s does not appear like a LyX created temporary directory."),
482 from_utf8(abs_tmpdir));
483 Alert::warning(_("Cannot remove temporary directory"), msg);
485 LYXERR(Debug::INFO, "Deleting tmp dir "
486 << package().temp_dir().absFilename());
487 if (!package().temp_dir().destroyDirectory()) {
488 docstring const msg =
489 bformat(_("Unable to remove the temporary directory %1$s"),
490 from_utf8(package().temp_dir().absFilename()));
491 Alert::warning(_("Unable to remove temporary directory"), msg);
496 // Kill the application object before exiting. This avoids crashes
497 // when exiting on Linux.
498 if (pimpl_->application_)
499 pimpl_->application_.reset();
503 void LyX::earlyExit(int status)
505 LASSERT(pimpl_->application_.get(), /**/);
506 // LyX::pimpl_::application_ is not initialised at this
507 // point so it's safe to just exit after some cleanup.
513 int LyX::init(int & argc, char * argv[])
515 // check for any spurious extra arguments
516 // other than documents
517 for (int argi = 1; argi < argc ; ++argi) {
518 if (argv[argi][0] == '-') {
520 bformat(_("Wrong command line option `%1$s'. Exiting."),
521 from_utf8(argv[argi]))) << endl;
526 // Initialization of LyX (reads lyxrc and more)
527 LYXERR(Debug::INIT, "Initializing LyX::init...");
528 bool success = init();
529 LYXERR(Debug::INIT, "Initializing LyX::init...done");
533 // Remaining arguments are assumed to be files to load.
534 for (int argi = argc - 1; argi >= 1; --argi)
535 pimpl_->files_to_load_.push_back(to_utf8(from_local8bit(argv[argi])));
538 pimpl_->files_to_load_.push_back(
539 i18nLibFileSearch("examples", "splash.lyx").absFilename());
546 bool LyX::loadFiles()
548 LASSERT(!use_gui, /**/);
550 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
551 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
553 for (; it != end; ++it) {
554 // get absolute path of file and add ".lyx" to
555 // the filename if necessary
556 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
562 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFilename(), false);
563 if (buf->loadLyXFile(fname)) {
564 ErrorList const & el = buf->errorList("Parse");
566 for_each(el.begin(), el.end(),
567 boost::bind(&LyX::printError, this, _1));
570 pimpl_->buffer_list_.release(buf);
578 void LyX::execBatchCommands()
580 // The advantage of doing this here is that the event loop
581 // is already started. So any need for interaction will be
584 // if reconfiguration is needed.
585 while (LayoutFileList::get().empty()) {
586 switch (Alert::prompt(
587 _("No textclass is found"),
588 _("LyX cannot continue because no textclass is found. "
589 "You can either reconfigure normally, or reconfigure using "
590 "default textclasses, or quit LyX."),
597 // regular reconfigure
598 pimpl_->lyxfunc_.dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
601 // reconfigure --without-latex-config
602 pimpl_->lyxfunc_.dispatch(FuncRequest(LFUN_RECONFIGURE,
603 " --without-latex-config"));
606 pimpl_->lyxfunc_.dispatch(FuncRequest(LFUN_LYX_QUIT));
611 // create the first main window
612 pimpl_->lyxfunc_.dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
614 if (!pimpl_->files_to_load_.empty()) {
615 // if some files were specified at command-line we assume that the
616 // user wants to edit *these* files and not to restore the session.
617 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
618 pimpl_->lyxfunc_.dispatch(
619 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
621 // clear this list to save a few bytes of RAM
622 pimpl_->files_to_load_.clear();
625 pimpl_->application_->restoreGuiSession();
627 // Execute batch commands if available
628 if (pimpl_->batch_commands.empty())
631 vector<string>::const_iterator bcit = pimpl_->batch_commands.begin();
632 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
633 for (; bcit != bcend; bcit++) {
634 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
635 pimpl_->lyxfunc_.dispatch(lyxaction.lookupFunc(*bcit));
643 The SIGHUP signal does not exist on Windows and does not need to be handled.
645 Windows handles SIGFPE and SIGSEGV signals as expected.
647 Cntl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
648 cause a new thread to be spawned. This may well result in unexpected
649 behaviour by the single-threaded LyX.
651 SIGTERM signals will come only from another process actually sending
652 that signal using 'raise' in Windows' POSIX compatability layer. It will
653 not come from the general "terminate process" methods that everyone
654 actually uses (and which can't be trapped). Killing an app 'politely' on
655 Windows involves first sending a WM_CLOSE message, something that is
656 caught already by the Qt frontend.
658 For more information see:
660 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
661 ...signals are mostly useless on Windows for a variety of reasons that are
664 'UNIX Application Migration Guide, Chapter 9'
665 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
667 'How To Terminate an Application "Cleanly" in Win32'
668 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
672 static void error_handler(int err_sig)
674 // Throw away any signals other than the first one received.
675 static sig_atomic_t handling_error = false;
678 handling_error = true;
680 // We have received a signal indicating a fatal error, so
681 // try and save the data ASAP.
682 LyX::cref().emergencyCleanup();
684 // These lyxerr calls may or may not work:
686 // Signals are asynchronous, so the main program may be in a very
687 // fragile state when a signal is processed and thus while a signal
688 // handler function executes.
689 // In general, therefore, we should avoid performing any
690 // I/O operations or calling most library and system functions from
693 // This shouldn't matter here, however, as we've already invoked
698 lyxerr << "\nlyx: SIGHUP signal caught\nBye." << endl;
702 lyxerr << "\nlyx: SIGFPE signal caught\nBye." << endl;
705 lyxerr << "\nlyx: SIGSEGV signal caught\n"
706 "Sorry, you have found a bug in LyX. "
707 "Please read the bug-reporting instructions "
708 "in Help->Introduction and send us a bug report, "
709 "if necessary. Thanks !\nBye." << endl;
717 // Deinstall the signal handlers
719 signal(SIGHUP, SIG_DFL);
721 signal(SIGINT, SIG_DFL);
722 signal(SIGFPE, SIG_DFL);
723 signal(SIGSEGV, SIG_DFL);
724 signal(SIGTERM, SIG_DFL);
727 if (err_sig == SIGSEGV ||
728 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty()))
730 if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty())
739 void LyX::printError(ErrorItem const & ei)
741 docstring tmp = _("LyX: ") + ei.error + char_type(':')
743 cerr << to_utf8(tmp) << endl;
750 signal(SIGHUP, error_handler);
752 signal(SIGFPE, error_handler);
753 signal(SIGSEGV, error_handler);
754 signal(SIGINT, error_handler);
755 signal(SIGTERM, error_handler);
756 // SIGPIPE can be safely ignored.
758 lyxrc.tempdir_path = package().temp_dir().absFilename();
759 lyxrc.document_path = package().document_dir().absFilename();
761 if (lyxrc.example_path.empty()) {
762 lyxrc.example_path = addPath(package().system_support().absFilename(),
765 if (lyxrc.template_path.empty()) {
766 lyxrc.template_path = addPath(package().system_support().absFilename(),
771 // Read configuration files
774 // This one may have been distributed along with LyX.
775 if (!readRcFile("lyxrc.dist"))
778 // Set the language defined by the distributor.
781 // Set the PATH correctly.
782 #if !defined (USE_POSIX_PACKAGING)
783 // Add the directory containing the LyX executable to the path
784 // so that LyX can find things like tex2lyx.
785 if (package().build_support().empty())
786 prependEnvPath("PATH", package().binary_dir().absFilename());
788 if (!lyxrc.path_prefix.empty())
789 prependEnvPath("PATH", lyxrc.path_prefix);
791 // Check that user LyX directory is ok.
792 if (queryUserLyXDir(package().explicit_user_support()))
793 reconfigureUserLyXDir();
795 // no need for a splash when there is no GUI
800 // This one is generated in user_support directory by lib/configure.py.
801 if (!readRcFile("lyxrc.defaults"))
804 // Query the OS to know what formats are viewed natively
805 formats.setAutoOpen();
807 // Read lyxrc.dist again to be able to override viewer auto-detection.
808 readRcFile("lyxrc.dist");
810 system_lyxrc = lyxrc;
811 system_formats = formats;
812 pimpl_->system_converters_ = pimpl_->converters_;
813 pimpl_->system_movers_ = pimpl_->movers_;
814 system_lcolor = lcolor;
816 // This one is edited through the preferences dialog.
817 if (!readRcFile("preferences"))
820 if (!readEncodingsFile("encodings", "unicodesymbols"))
822 if (!readLanguagesFile("languages"))
825 // Set the language defined by the user.
829 LYXERR(Debug::INIT, "Reading layouts...");
835 // read keymap and ui files in batch mode as well
836 // because InsetInfo needs to know these to produce
837 // the correct output
839 // Set up command definitions
840 pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
843 pimpl_->toplevel_keymap_.read("site");
844 pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
845 // load user bind file user.bind
846 pimpl_->toplevel_keymap_.read("user");
848 pimpl_->lyxfunc_.initKeySequences(&pimpl_->toplevel_keymap_);
850 if (lyxerr.debugging(Debug::LYXRC))
853 os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
854 if (!lyxrc.path_prefix.empty())
855 prependEnvPath("PATH", lyxrc.path_prefix);
857 FileName const document_path(lyxrc.document_path);
858 if (document_path.exists() && document_path.isDirectory())
859 package().document_dir() = document_path;
861 package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
862 if (package().temp_dir().empty()) {
863 Alert::error(_("Could not create temporary directory"),
864 bformat(_("Could not create a temporary directory in\n"
866 "Make sure that this path exists and is writable and try again."),
867 from_utf8(lyxrc.tempdir_path)));
868 // createLyXTmpDir() tries sufficiently hard to create a
869 // usable temp dir, so the probability to come here is
870 // close to zero. We therefore don't try to overcome this
871 // problem with e.g. asking the user for a new path and
872 // trying again but simply exit.
876 LYXERR(Debug::INIT, "LyX tmp dir: `"
877 << package().temp_dir().absFilename() << '\'');
879 LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
880 pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
882 // This must happen after package initialization and after lyxrc is
883 // read, therefore it can't be done by a static object.
884 ConverterCache::init();
890 void LyX::emergencyCleanup() const
892 // what to do about tmpfiles is non-obvious. we would
893 // like to delete any we find, but our lyxdir might
894 // contain documents etc. which might be helpful on
897 pimpl_->buffer_list_.emergencyWriteAll();
899 if (pimpl_->lyx_server_)
900 pimpl_->lyx_server_->emergencyCleanup();
901 pimpl_->lyx_server_.reset();
902 pimpl_->lyx_socket_.reset();
907 // return true if file does not exist or is older than configure.py.
908 static bool needsUpdate(string const & file)
910 // We cannot initialize configure_script directly because the package
911 // is not initialized yet when static objects are constructed.
912 static FileName configure_script;
913 static bool firstrun = true;
916 FileName(addName(package().system_support().absFilename(),
922 FileName(addName(package().user_support().absFilename(), file));
923 return !absfile.exists()
924 || configure_script.lastModified() > absfile.lastModified();
928 bool LyX::queryUserLyXDir(bool explicit_userdir)
930 // Does user directory exist?
931 FileName const sup = package().user_support();
932 if (sup.exists() && sup.isDirectory()) {
935 return needsUpdate("lyxrc.defaults")
936 || needsUpdate("lyxmodules.lst")
937 || needsUpdate("textclass.lst")
938 || needsUpdate("packages.lst");
941 first_start = !explicit_userdir;
943 // If the user specified explicitly a directory, ask whether
944 // to create it. If the user says "no", then exit.
945 if (explicit_userdir &&
947 _("Missing user LyX directory"),
948 bformat(_("You have specified a non-existent user "
949 "LyX directory, %1$s.\n"
950 "It is needed to keep your own configuration."),
951 from_utf8(package().user_support().absFilename())),
953 _("&Create directory"),
955 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
956 earlyExit(EXIT_FAILURE);
959 lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
960 from_utf8(sup.absFilename()))) << endl;
962 if (!sup.createDirectory(0755)) {
963 // Failed, so let's exit.
964 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
966 earlyExit(EXIT_FAILURE);
973 bool LyX::readRcFile(string const & name)
975 LYXERR(Debug::INIT, "About to read " << name << "... ");
977 FileName const lyxrc_path = libFileSearch(string(), name);
978 if (!lyxrc_path.empty()) {
979 LYXERR(Debug::INIT, "Found in " << lyxrc_path);
980 if (lyxrc.read(lyxrc_path) < 0) {
985 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
990 // Read the languages file `name'
991 bool LyX::readLanguagesFile(string const & name)
993 LYXERR(Debug::INIT, "About to read " << name << "...");
995 FileName const lang_path = libFileSearch(string(), name);
996 if (lang_path.empty()) {
1000 languages.read(lang_path);
1005 // Read the encodings file `name'
1006 bool LyX::readEncodingsFile(string const & enc_name,
1007 string const & symbols_name)
1009 LYXERR(Debug::INIT, "About to read " << enc_name << " and "
1010 << symbols_name << "...");
1012 FileName const symbols_path = libFileSearch(string(), symbols_name);
1013 if (symbols_path.empty()) {
1014 showFileError(symbols_name);
1018 FileName const enc_path = libFileSearch(string(), enc_name);
1019 if (enc_path.empty()) {
1020 showFileError(enc_name);
1023 encodings.read(enc_path, symbols_path);
1030 /// return the the number of arguments consumed
1031 typedef boost::function<int(string const &, string const &, string &)> cmd_helper;
1033 int parse_dbg(string const & arg, string const &, string &)
1036 lyxerr << to_utf8(_("List of supported debug flags:")) << endl;
1037 Debug::showTags(lyxerr);
1040 lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1042 lyxerr.level(Debug::value(arg));
1043 Debug::showLevel(lyxerr, lyxerr.level());
1048 int parse_help(string const &, string const &, string &)
1051 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1052 "Command line switches (case sensitive):\n"
1053 "\t-help summarize LyX usage\n"
1054 "\t-userdir dir set user directory to dir\n"
1055 "\t-sysdir dir set system directory to dir\n"
1056 "\t-geometry WxH+X+Y set geometry of the main window\n"
1057 "\t-dbg feature[,feature]...\n"
1058 " select the features to debug.\n"
1059 " Type `lyx -dbg' to see the list of features\n"
1060 "\t-x [--execute] command\n"
1061 " where command is a lyx command.\n"
1062 "\t-e [--export] fmt\n"
1063 " where fmt is the export format of choice.\n"
1064 " Look on Tools->Preferences->File formats->Format\n"
1065 " to get an idea which parameters should be passed.\n"
1066 "\t-i [--import] fmt file.xxx\n"
1067 " where fmt is the import format of choice\n"
1068 " and file.xxx is the file to be imported.\n"
1069 "\t-version summarize version and build info\n"
1070 "Check the LyX man page for more details.")) << endl;
1076 int parse_version(string const &, string const &, string &)
1078 lyxerr << "LyX " << lyx_version
1079 << " (" << lyx_release_date << ")" << endl;
1080 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
1082 lyxerr << lyx_version_info << endl;
1088 int parse_sysdir(string const & arg, string const &, string &)
1091 Alert::error(_("No system directory"),
1092 _("Missing directory for -sysdir switch"));
1095 cl_system_support = arg;
1100 int parse_userdir(string const & arg, string const &, string &)
1103 Alert::error(_("No user directory"),
1104 _("Missing directory for -userdir switch"));
1107 cl_user_support = arg;
1112 int parse_execute(string const & arg, string const &, string & batch)
1115 Alert::error(_("Incomplete command"),
1116 _("Missing command string after --execute switch"));
1124 int parse_export(string const & type, string const &, string & batch)
1127 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1128 "--export switch")) << endl;
1131 batch = "buffer-export " + type;
1137 int parse_import(string const & type, string const & file, string & batch)
1140 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1141 "--import switch")) << endl;
1145 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1149 batch = "buffer-import " + type + ' ' + file;
1154 int parse_geometry(string const & arg1, string const &, string &)
1157 #if defined(_WIN32) || (defined(__CYGWIN__) && defined(X_DISPLAY_MISSING))
1158 // remove also the arg
1161 // don't remove "-geometry"
1170 void LyX::easyParse(int & argc, char * argv[])
1172 map<string, cmd_helper> cmdmap;
1174 cmdmap["-dbg"] = parse_dbg;
1175 cmdmap["-help"] = parse_help;
1176 cmdmap["--help"] = parse_help;
1177 cmdmap["-version"] = parse_version;
1178 cmdmap["--version"] = parse_version;
1179 cmdmap["-sysdir"] = parse_sysdir;
1180 cmdmap["-userdir"] = parse_userdir;
1181 cmdmap["-x"] = parse_execute;
1182 cmdmap["--execute"] = parse_execute;
1183 cmdmap["-e"] = parse_export;
1184 cmdmap["--export"] = parse_export;
1185 cmdmap["-i"] = parse_import;
1186 cmdmap["--import"] = parse_import;
1187 cmdmap["-geometry"] = parse_geometry;
1189 for (int i = 1; i < argc; ++i) {
1190 map<string, cmd_helper>::const_iterator it
1191 = cmdmap.find(argv[i]);
1193 // don't complain if not found - may be parsed later
1194 if (it == cmdmap.end())
1198 (i + 1 < argc) ? to_utf8(from_local8bit(argv[i + 1])) : string();
1200 (i + 2 < argc) ? to_utf8(from_local8bit(argv[i + 2])) : string();
1203 int const remove = 1 + it->second(arg, arg2, batch);
1205 pimpl_->batch_commands.push_back(batch);
1207 // Now, remove used arguments by shifting
1208 // the following ones remove places down.
1211 for (int j = i; j < argc; ++j)
1212 argv[j] = argv[j + remove];
1219 FuncStatus getStatus(FuncRequest const & action)
1221 return LyX::ref().lyxFunc().getStatus(action);
1225 void dispatch(FuncRequest const & action)
1227 LyX::ref().lyxFunc().dispatch(action);
1231 BufferList & theBufferList()
1233 return LyX::ref().bufferList();
1237 LyXFunc & theLyXFunc()
1239 return LyX::ref().lyxFunc();
1243 Server & theServer()
1245 // FIXME: this should not be use_gui dependent
1246 LASSERT(use_gui, /**/);
1247 return LyX::ref().server();
1251 ServerSocket & theServerSocket()
1253 // FIXME: this should not be use_gui dependent
1254 LASSERT(use_gui, /**/);
1255 return LyX::ref().socket();
1259 KeyMap & theTopLevelKeymap()
1261 return LyX::ref().pimpl_->toplevel_keymap_;
1265 Converters & theConverters()
1267 return LyX::ref().converters();
1271 Converters & theSystemConverters()
1273 return LyX::ref().systemConverters();
1277 Movers & theMovers()
1279 return LyX::ref().pimpl_->movers_;
1283 Mover const & getMover(string const & fmt)
1285 return LyX::ref().pimpl_->movers_(fmt);
1289 void setMover(string const & fmt, string const & command)
1291 LyX::ref().pimpl_->movers_.set(fmt, command);
1295 Movers & theSystemMovers()
1297 return LyX::ref().pimpl_->system_movers_;
1301 Messages & getMessages(string const & language)
1303 return LyX::ref().getMessages(language);
1307 Messages & getGuiMessages()
1309 return LyX::ref().getGuiMessages();