]> git.lyx.org Git - lyx.git/blob - src/LyX.cpp
Remove hardcoded values
[lyx.git] / src / LyX.cpp
1 /**
2  * \file LyX.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16 #include <version.h>
17
18 #include "LyX.h"
19
20 #include "AppleSpellChecker.h"
21 #include "AspellChecker.h"
22 #include "Buffer.h"
23 #include "BufferList.h"
24 #include "CmdDef.h"
25 #include "ColorSet.h"
26 #include "ConverterCache.h"
27 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "EnchantChecker.h"
30 #include "Encoding.h"
31 #include "ErrorList.h"
32 #include "Format.h"
33 #include "FuncStatus.h"
34 #include "HunspellChecker.h"
35 #include "KeyMap.h"
36 #include "Language.h"
37 #include "LaTeXFonts.h"
38 #include "LayoutFile.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXAction.h"
42 #include "LyXRC.h"
43 #include "ModuleList.h"
44 #include "Mover.h"
45 #include "Server.h"
46 #include "ServerSocket.h"
47 #include "Session.h"
48 #include "WordList.h"
49
50 #include "frontends/alert.h"
51 #include "frontends/Application.h"
52
53 #include "support/ConsoleApplication.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/environment.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/filetools.h"
59 #include "support/gettext.h"
60 #include "support/lstrings.h"
61 #include "support/Messages.h"
62 #include "support/os.h"
63 #include "support/Package.h"
64 #include "support/unique_ptr.h"
65
66 #include <algorithm>
67 #include <csignal>
68 #include <iostream>
69 #include <functional>
70 #include <map>
71 #include <stdlib.h>
72 #include <string>
73 #include <vector>
74
75 using namespace std;
76 using namespace lyx::support;
77
78 #if defined (USE_MACOSX_PACKAGING)
79 #include <crt_externs.h>
80 #endif
81
82 namespace lyx {
83
84 namespace Alert = frontend::Alert;
85 namespace os = support::os;
86
87
88
89 // Are we using the GUI at all?  We default to true and this is changed
90 // to false when the export feature is used.
91
92 bool use_gui = true;
93
94
95 // Report on the terminal about spawned commands. The default is false
96 // and can be changed with the option -v (--verbose).
97
98 bool verbose = false;
99
100
101 // We default to open documents in an already running instance, provided that
102 // the lyxpipe has been setup. This can be overridden either on the command
103 // line or through preference settings.
104
105 RunMode run_mode = PREFERRED;
106
107
108 // Tell what files can be silently overwritten during batch export.
109 // Possible values are: NO_FILES, MAIN_FILE, ALL_FILES, UNSPECIFIED.
110 // Unless specified on command line (through the -f switch) or through the
111 // environment variable LYX_FORCE_OVERWRITE, the default will be MAIN_FILE.
112
113 OverwriteFiles force_overwrite = UNSPECIFIED;
114
115
116 namespace {
117
118 // Filled with the command line arguments "foo" of "-sysdir foo" or
119 // "-userdir foo".
120 string cl_system_support;
121 string cl_user_support;
122
123 string geometryArg;
124
125 LyX * singleton_ = 0;
126
127 void showFileError(string const & error)
128 {
129         Alert::warning(_("Could not read configuration file"),
130                        bformat(_("Error while reading the configuration file\n%1$s.\n"
131                            "Please check your installation."), from_utf8(error)));
132 }
133
134 } // namespace anon
135
136 /// The main application class private implementation.
137 struct LyX::Impl {
138         Impl()
139                 : latexfonts_(0), spell_checker_(0), apple_spell_checker_(0), aspell_checker_(0), enchant_checker_(0), hunspell_checker_(0)
140         {}
141
142         ~Impl()
143         {
144                 delete latexfonts_;
145                 delete apple_spell_checker_;
146                 delete aspell_checker_;
147                 delete enchant_checker_;
148                 delete hunspell_checker_;
149         }
150
151         ///
152         BufferList buffer_list_;
153         ///
154         KeyMap toplevel_keymap_;
155         ///
156         CmdDef toplevel_cmddef_;
157         ///
158         unique_ptr<Server> lyx_server_;
159         ///
160         unique_ptr<ServerSocket> lyx_socket_;
161         ///
162         unique_ptr<frontend::Application> application_;
163         /// lyx session, containing lastfiles, lastfilepos, and lastopened
164         unique_ptr<Session> session_;
165
166         /// Files to load at start.
167         vector<string> files_to_load_;
168
169         /// The messages translators.
170         map<string, Messages> messages_;
171
172         /// The file converters.
173         Converters converters_;
174
175         // The system converters copy after reading lyxrc.defaults.
176         Converters system_converters_;
177
178         ///
179         Movers movers_;
180         ///
181         Movers system_movers_;
182
183         /// the parsed command line batch command if any
184         vector<string> batch_commands;
185
186         ///
187         LaTeXFonts * latexfonts_;
188
189         ///
190         SpellChecker * spell_checker_;
191         ///
192         SpellChecker * apple_spell_checker_;
193         ///
194         SpellChecker * aspell_checker_;
195         ///
196         SpellChecker * enchant_checker_;
197         ///
198         SpellChecker * hunspell_checker_;
199 };
200
201
202 /// The main application class for console mode
203 class LyXConsoleApp : public ConsoleApplication
204 {
205 public:
206         LyXConsoleApp(LyX * lyx, int & argc, char * argv[])
207                 : ConsoleApplication(lyx_package, argc, argv), lyx_(lyx),
208                   argc_(argc), argv_(argv)
209         {
210         }
211         void doExec()
212         {
213                 int const exit_status = lyx_->execWithoutGui(argc_, argv_);
214                 exit(exit_status);
215         }
216 private:
217         LyX * lyx_;
218         int & argc_;
219         char ** argv_;
220 };
221
222
223 ///
224 frontend::Application * theApp()
225 {
226         if (singleton_)
227                 return singleton_->pimpl_->application_.get();
228         else
229                 return 0;
230 }
231
232
233 LyX::~LyX()
234 {
235         delete pimpl_;
236         singleton_ = 0;
237 }
238
239
240 void lyx_exit(int exit_code)
241 {
242         if (exit_code)
243                 // Something wrong happened so better save everything, just in
244                 // case.
245                 emergencyCleanup();
246
247 #ifndef NDEBUG
248         // Properly crash in debug mode in order to get a useful backtrace.
249         abort();
250 #endif
251
252         // In release mode, try to exit gracefully.
253         if (theApp())
254                 theApp()->exit(exit_code);
255         else
256                 exit(exit_code);
257 }
258
259
260 LyX::LyX()
261         : first_start(false)
262 {
263         singleton_ = this;
264         pimpl_ = new Impl;
265 }
266
267
268 Messages & LyX::messages(string const & language)
269 {
270         map<string, Messages>::iterator it = pimpl_->messages_.find(language);
271
272         if (it != pimpl_->messages_.end())
273                 return it->second;
274
275         pair<map<string, Messages>::iterator, bool> result =
276                         pimpl_->messages_.insert(make_pair(language, Messages(language)));
277
278         LATTEST(result.second);
279         return result.first->second;
280 }
281
282
283 int LyX::exec(int & argc, char * argv[])
284 {
285         // Minimal setting of locale before parsing command line
286         try {
287                 init_package(os::utf8_argv(0), string(), string());
288                 // we do not get to this point when init_package throws an exception
289                 setLocale();
290         } catch (ExceptionMessage const & message) {
291                 LYXERR(Debug::LOCALE, message.title_ + ", " + message.details_);
292         }
293
294         // Here we need to parse the command line. At least
295         // we need to parse for "-dbg" and "-help"
296         easyParse(argc, argv);
297
298         try {
299                 init_package(os::utf8_argv(0), cl_system_support, cl_user_support);
300         } catch (ExceptionMessage const & message) {
301                 if (message.type_ == ErrorException) {
302                         Alert::error(message.title_, message.details_);
303                         lyx_exit(1);
304                 } else if (message.type_ == WarningException) {
305                         Alert::warning(message.title_, message.details_);
306                 }
307         }
308
309         // Reinit the messages machinery in case package() knows
310         // something interesting about the locale directory.
311         setLocale();
312
313         if (!use_gui) {
314                 LyXConsoleApp app(this, argc, argv);
315
316                 // Reestablish our defaults, as Qt overwrites them
317                 // after creating app
318                 setLocale();//???
319
320                 return app.exec();
321         }
322
323         // Let the frontend parse and remove all arguments that it knows
324         pimpl_->application_.reset(createApplication(argc, argv));
325
326         // Reestablish our defaults, as Qt overwrites them
327         // after createApplication()
328         setLocale();//???
329
330         // Parse and remove all known arguments in the LyX singleton
331         // Give an error for all remaining ones.
332         int exit_status = init(argc, argv);
333         if (exit_status) {
334                 // Kill the application object before exiting.
335                 pimpl_->application_.reset();
336                 use_gui = false;
337                 prepareExit();
338                 return exit_status;
339         }
340
341         // If not otherwise specified by a command line option or
342         // by preferences, we default to reuse a running instance.
343         if (run_mode == PREFERRED)
344                 run_mode = USE_REMOTE;
345
346         // FIXME
347         /* Create a CoreApplication class that will provide the main event loop
348         * and the socket callback registering. With Qt, only QtCore
349         * library would be needed.
350         * When this is done, a server_mode could be created and the following two
351         * line would be moved out from here.
352         * However, note that the first of the two lines below triggers the
353         * "single instance" behavior, which should occur right at this point.
354         */
355         // Note: socket callback must be registered after init(argc, argv)
356         // such that package().temp_dir() is properly initialized.
357         pimpl_->lyx_server_.reset(new Server(lyxrc.lyxpipes));
358         pimpl_->lyx_socket_.reset(new ServerSocket(
359                         FileName(package().temp_dir().absFileName() + "/lyxsocket")));
360
361         // Start the real execution loop.
362         if (!theServer().deferredLoadingToOtherInstance())
363                 exit_status = pimpl_->application_->exec();
364         else if (!pimpl_->files_to_load_.empty()) {
365                 vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
366                 vector<string>::const_iterator end = pimpl_->files_to_load_.end();
367                 lyxerr << _("The following files could not be loaded:") << endl;
368                 for (; it != end; ++it)
369                         lyxerr << *it << endl;
370         }
371
372         prepareExit();
373
374         return exit_status;
375 }
376
377
378 void LyX::prepareExit()
379 {
380         // Clear the clipboard and selection stack:
381         cap::clearCutStack();
382         cap::clearSelection();
383
384         // Write the index file of the converter cache
385         ConverterCache::get().writeIndex();
386
387         // close buffers first
388         pimpl_->buffer_list_.closeAll();
389
390         // register session changes and shutdown server and socket
391         if (use_gui) {
392                 if (pimpl_->session_)
393                         pimpl_->session_->writeFile();
394                 pimpl_->session_.reset();
395                 pimpl_->lyx_server_.reset();
396                 pimpl_->lyx_socket_.reset();
397         }
398
399         // do any other cleanup procedures now
400         if (package().temp_dir() != package().system_temp_dir()) {
401                 string const abs_tmpdir = package().temp_dir().absFileName();
402                 if (!contains(package().temp_dir().absFileName(), "lyx_tmpdir")) {
403                         docstring const msg =
404                                 bformat(_("%1$s does not appear like a LyX created temporary directory."),
405                                 from_utf8(abs_tmpdir));
406                         Alert::warning(_("Cannot remove temporary directory"), msg);
407                 } else {
408                         LYXERR(Debug::INFO, "Deleting tmp dir "
409                                 << package().temp_dir().absFileName());
410                         if (!package().temp_dir().destroyDirectory()) {
411                                 LYXERR0(bformat(_("Unable to remove the temporary directory %1$s"),
412                                         from_utf8(package().temp_dir().absFileName())));
413                         }
414                 }
415         }
416
417         // Kill the application object before exiting. This avoids crashes
418         // when exiting on Linux.
419         pimpl_->application_.reset();
420 }
421
422
423 void LyX::earlyExit(int status)
424 {
425         LATTEST(pimpl_->application_.get());
426         // LyX::pimpl_::application_ is not initialised at this
427         // point so it's safe to just exit after some cleanup.
428         prepareExit();
429         exit(status);
430 }
431
432
433 int LyX::init(int & argc, char * argv[])
434 {
435         // check for any spurious extra arguments
436         // other than documents
437         for (int argi = 1; argi < argc ; ++argi) {
438                 if (argv[argi][0] == '-') {
439                         lyxerr << to_utf8(
440                                 bformat(_("Wrong command line option `%1$s'. Exiting."),
441                                 from_utf8(os::utf8_argv(argi)))) << endl;
442                         return EXIT_FAILURE;
443                 }
444         }
445
446         // Initialization of LyX (reads lyxrc and more)
447         LYXERR(Debug::INIT, "Initializing LyX::init...");
448         bool success = init();
449         LYXERR(Debug::INIT, "Initializing LyX::init...done");
450         if (!success)
451                 return EXIT_FAILURE;
452
453         // Remaining arguments are assumed to be files to load.
454         for (int argi = 1; argi < argc; ++argi)
455                 pimpl_->files_to_load_.push_back(os::utf8_argv(argi));
456
457         if (!use_gui && pimpl_->files_to_load_.empty()) {
458                 lyxerr << to_utf8(_("Missing filename for this operation.")) << endl;
459                 return EXIT_FAILURE;
460         }
461
462         if (first_start) {
463                 pimpl_->files_to_load_.push_back(
464                         i18nLibFileSearch("examples", "splash.lyx").absFileName());
465         }
466
467         return EXIT_SUCCESS;
468 }
469
470
471 int LyX::execWithoutGui(int & argc, char * argv[])
472 {
473         int exit_status = init(argc, argv);
474         if (exit_status) {
475                 prepareExit();
476                 return exit_status;
477         }
478
479         // Used to keep track of which buffers were explicitly loaded by user request.
480         // This is necessary because master and child document buffers are loaded, even 
481         // if they were not named on the command line. We do not want to dispatch to
482         // those.
483         vector<Buffer *> command_line_buffers;
484
485         // Load the files specified on the command line
486         vector<string>::const_iterator it = pimpl_->files_to_load_.begin();
487         vector<string>::const_iterator end = pimpl_->files_to_load_.end();
488         for (; it != end; ++it) {
489                 // get absolute path of file and add ".lyx" to the filename if necessary
490                 FileName fname = fileSearch(string(), os::internal_path(*it), "lyx",
491                                                                                                                                 may_not_exist);
492
493                 if (fname.empty())
494                         continue;
495
496                 Buffer * buf = pimpl_->buffer_list_.newBuffer(fname.absFileName());
497                 LYXERR(Debug::FILES, "Loading " << fname);
498                 if (buf && buf->loadLyXFile() == Buffer::ReadSuccess) {
499                         ErrorList const & el = buf->errorList("Parse");
500                         for(ErrorItem const & e : el)
501                                 printError(e);
502                         command_line_buffers.push_back(buf);
503                 } else {
504                         if (buf)
505                                 pimpl_->buffer_list_.release(buf);
506                         docstring const error_message =
507                                         bformat(_("LyX failed to load the following file: %1$s"),
508                                                                         from_utf8(fname.absFileName()));
509                         lyxerr << to_utf8(error_message) << endl;
510                         exit_status = 1; // failed
511                 }
512         }
513
514         if (exit_status || pimpl_->batch_commands.empty() || pimpl_->buffer_list_.empty()) {
515                 prepareExit();
516                 return exit_status;
517         }
518
519         // Iterate through the buffers that were specified on the command line
520         bool final_success = false;
521         vector<Buffer *>::iterator buf_it = command_line_buffers.begin();
522         for (; buf_it != command_line_buffers.end(); ++buf_it) {
523                 Buffer * buf = *buf_it;
524                 vector<string>::const_iterator bcit  = pimpl_->batch_commands.begin();
525                 vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
526                 DispatchResult dr;
527                 for (; bcit != bcend; ++bcit) {
528                         LYXERR(Debug::ACTION, "Buffer::dispatch: cmd: " << *bcit);
529                         buf->dispatch(*bcit, dr);
530                         final_success |= !dr.error();
531                 }
532         }
533         prepareExit();
534         return !final_success;
535 }
536
537
538 void execBatchCommands()
539 {
540         LAPPERR(singleton_);
541         singleton_->execCommands();
542 }
543
544
545 void LyX::execCommands()
546 {
547         // The advantage of doing this here is that the event loop
548         // is already started. So any need for interaction will be
549         // aknowledged.
550
551         // if reconfiguration is needed.
552         if (LayoutFileList::get().empty()) {
553                 switch (Alert::prompt(
554                         _("No textclass is found"),
555                         _("LyX will only have minimal functionality because no textclasses "
556                                 "have been found. You can either try to reconfigure LyX normally, "
557                                 "try to reconfigure without checking your LaTeX installation, or continue."),
558                         0, 2,
559                         _("&Reconfigure"),
560                         _("&Without LaTeX"),
561                         _("&Continue")))
562                 {
563                 case 0:
564                         // regular reconfigure
565                         lyx::dispatch(FuncRequest(LFUN_RECONFIGURE, ""));
566                         break;
567                 case 1:
568                         // reconfigure --without-latex-config
569                         lyx::dispatch(FuncRequest(LFUN_RECONFIGURE,
570                                 " --without-latex-config"));
571                         break;
572                 default:
573                         break;
574                 }
575         }
576
577         // create the first main window
578         lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW, geometryArg));
579
580         if (!pimpl_->files_to_load_.empty()) {
581                 // if some files were specified at command-line we assume that the
582                 // user wants to edit *these* files and not to restore the session.
583                 for (size_t i = 0; i != pimpl_->files_to_load_.size(); ++i) {
584                         lyx::dispatch(
585                                 FuncRequest(LFUN_FILE_OPEN, pimpl_->files_to_load_[i]));
586                 }
587                 // clear this list to save a few bytes of RAM
588                 pimpl_->files_to_load_.clear();
589         } else
590                 pimpl_->application_->restoreGuiSession();
591
592         // Execute batch commands if available
593         if (pimpl_->batch_commands.empty())
594                 return;
595
596         vector<string>::const_iterator bcit  = pimpl_->batch_commands.begin();
597         vector<string>::const_iterator bcend = pimpl_->batch_commands.end();
598         for (; bcit != bcend; ++bcit) {
599                 LYXERR(Debug::INIT, "About to handle -x '" << *bcit << '\'');
600                 lyx::dispatch(lyxaction.lookupFunc(*bcit));
601         }
602 }
603
604
605 /*
606 Signals and Windows
607 ===================
608 The SIGHUP signal does not exist on Windows and does not need to be handled.
609
610 Windows handles SIGFPE and SIGSEGV signals as expected.
611
612 Ctrl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
613 cause a new thread to be spawned. This may well result in unexpected
614 behaviour by the single-threaded LyX.
615
616 SIGTERM signals will come only from another process actually sending
617 that signal using 'raise' in Windows' POSIX compatability layer. It will
618 not come from the general "terminate process" methods that everyone
619 actually uses (and which can't be trapped). Killing an app 'politely' on
620 Windows involves first sending a WM_CLOSE message, something that is
621 caught already by the Qt frontend.
622
623 For more information see:
624
625 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
626 ...signals are mostly useless on Windows for a variety of reasons that are
627 Windows specific...
628
629 'UNIX Application Migration Guide, Chapter 9'
630 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
631
632 'How To Terminate an Application "Cleanly" in Win32'
633 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
634 */
635 extern "C" {
636
637 static void error_handler(int err_sig)
638 {
639         // Throw away any signals other than the first one received.
640         static sig_atomic_t handling_error = false;
641         if (handling_error)
642                 return;
643         handling_error = true;
644
645         // We have received a signal indicating a fatal error, so
646         // try and save the data ASAP.
647         emergencyCleanup();
648
649         // These lyxerr calls may or may not work:
650
651         // Signals are asynchronous, so the main program may be in a very
652         // fragile state when a signal is processed and thus while a signal
653         // handler function executes.
654         // In general, therefore, we should avoid performing any
655         // I/O operations or calling most library and system functions from
656         // signal handlers.
657
658         // This shouldn't matter here, however, as we've already invoked
659         // emergencyCleanup.
660         docstring msg;
661         switch (err_sig) {
662 #ifdef SIGHUP
663         case SIGHUP:
664                 msg = _("SIGHUP signal caught!\nBye.");
665                 break;
666 #endif
667         case SIGFPE:
668                 msg = _("SIGFPE signal caught!\nBye.");
669                 break;
670         case SIGSEGV:
671                 msg = _("SIGSEGV signal caught!\n"
672                           "Sorry, you have found a bug in LyX, "
673                           "hope you have not lost any data.\n"
674                           "Please read the bug-reporting instructions "
675                           "in 'Help->Introduction' and send us a bug report, "
676                           "if necessary. Thanks!\nBye.");
677                 break;
678         case SIGINT:
679         case SIGTERM:
680                 // no comments
681                 break;
682         }
683
684         if (!msg.empty()) {
685                 lyxerr << "\nlyx: " << msg << endl;
686                 // try to make a GUI message
687                 Alert::error(_("LyX crashed!"), msg, true);
688         }
689
690         // Deinstall the signal handlers
691 #ifdef SIGHUP
692         signal(SIGHUP, SIG_DFL);
693 #endif
694         signal(SIGINT, SIG_DFL);
695         signal(SIGFPE, SIG_DFL);
696         signal(SIGSEGV, SIG_DFL);
697         signal(SIGTERM, SIG_DFL);
698
699 #ifdef SIGHUP
700         if (err_sig == SIGSEGV ||
701                 (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty())) {
702 #else
703         if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty()) {
704 #endif
705 #ifdef _MSC_VER
706                 // with abort() it crashes again.
707                 exit(err_sig);
708 #else
709                 abort();
710 #endif
711         }
712
713         exit(0);
714 }
715
716 }
717
718
719 void LyX::printError(ErrorItem const & ei)
720 {
721         docstring tmp = _("LyX: ") + ei.error + char_type(':')
722                 + ei.description;
723         cerr << to_utf8(tmp) << endl;
724 }
725
726 #if defined (USE_MACOSX_PACKAGING)
727 namespace {
728         // Unexposed--extract an environment variable name from its NAME=VALUE
729         // representation
730         std::string varname(const char* line)
731         {
732                 size_t nameLen = strcspn(line, "=");
733                 if (nameLen == strlen(line)) {
734                         return std::string();
735                 } else {
736                         return std::string(line, nameLen);
737                 }
738         }
739 }
740
741 void cleanDuplicateEnvVars()
742 {
743         std::set<std::string> seen;
744         std::set<std::string> dupes;
745
746         // Create a list of the environment variables that appear more than once
747         for (char **read = *_NSGetEnviron(); *read; read++) {
748                 std::string name = varname(*read);
749                 if (name.size() == 0) {
750                         continue;
751                 }
752                 if (seen.find(name) != seen.end()) {
753                         dupes.insert(name);
754                 } else {
755                         seen.insert(name);
756                 }
757         }
758
759         // Loop over the list of duplicated variables
760         std::set<std::string>::iterator dupe = dupes.begin();
761         std::set<std::string>::iterator const dend = dupes.end();
762         for (; dupe != dend; ++dupe) {
763                 const char *name = (*dupe).c_str();
764                 char *val = getenv(name);
765                 if (val != NULL) {
766                         LYXERR(Debug::INIT, "Duplicate environment variable: " << name);
767                         // unsetenv removes *all* instances of the variable from the environment
768                         unsetenv(name);
769
770                         // replace with the value from getenv (in practice appears to be the
771                         // first value in the list)
772                         setenv(name, val, 0);
773                 }
774         }
775 }
776 #endif
777
778
779 static void initTemplatePath()
780 {
781         FileName const package_template_path =
782                 FileName(addName(package().system_support().absFileName(), "templates"));
783
784         if (lyxrc.template_path.empty()) {
785                 lyxrc.template_path = package_template_path.absFileName();
786         }
787 #if defined (USE_MACOSX_PACKAGING)
788         FileName const user_template_path =
789                 FileName(addName(package().user_support().absFileName(), "templates"));
790
791         if (package_template_path != FileName(lyxrc.template_path) &&
792                 user_template_path != FileName(lyxrc.template_path))
793         {
794                 return;
795         }
796         FileName const user_template_link =
797                 FileName(addName(user_template_path.absFileName(),"SystemTemplates"));
798         if (user_template_link.isSymLink() && !equivalent(user_template_link, package_template_path)) {
799                 user_template_link.removeFile();
800         }
801         if (!user_template_link.exists()) {
802                 if (!package_template_path.link(user_template_link)) {
803                         FileName const user_support = package().user_support();
804                         if (user_support.exists() && user_support.isDirectory()) {
805                                 LYXERR(Debug::INIT, "Cannot create symlink " + user_template_link.absFileName());
806                                 lyxrc.template_path = package_template_path.absFileName();
807                         }
808                         return;
809                 }
810                 LYXERR(Debug::INIT, "Symlink \"" << user_template_link.absFileName() << "\" created.");
811         }
812         lyxrc.template_path = user_template_path.absFileName();
813 #endif
814 }
815
816
817 bool LyX::init()
818 {
819 #ifdef SIGHUP
820         signal(SIGHUP, error_handler);
821 #endif
822         signal(SIGFPE, error_handler);
823         signal(SIGSEGV, error_handler);
824         signal(SIGINT, error_handler);
825         signal(SIGTERM, error_handler);
826         // SIGPIPE can be safely ignored.
827
828 #if defined (USE_MACOSX_PACKAGING)
829         cleanDuplicateEnvVars();
830 #endif
831
832         lyxrc.tempdir_path = package().temp_dir().absFileName();
833         lyxrc.document_path = ".";
834
835         if (lyxrc.example_path.empty()) {
836                 lyxrc.example_path = addPath(package().system_support().absFileName(),
837                                               "examples");
838         }
839         initTemplatePath();
840
841         // init LyXDir environment variable
842         string const lyx_dir = package().lyx_dir().absFileName();
843         LYXERR(Debug::INIT, "Setting LyXDir... to \"" << lyx_dir << "\"");
844         if (!setEnv("LyXDir", lyx_dir))
845                 LYXERR(Debug::INIT, "\t... failed!");
846
847         if (package().explicit_user_support() && getEnv(LYX_USERDIR_VER).empty()) {
848                 // -userdir was given on the command line.
849                 // Make it available to child processes, otherwise tex2lyx
850                 // would not find all layout files, and other converters might
851                 // use it as well.
852                 string const user_dir = package().user_support().absFileName();
853                 LYXERR(Debug::INIT, "Setting " LYX_USERDIR_VER "... to \""
854                                     << user_dir << '"');
855                 if (!setEnv(LYX_USERDIR_VER, user_dir))
856                         LYXERR(Debug::INIT, "\t... failed!");
857         }
858
859         //
860         // Read configuration files
861         //
862
863         // This one may have been distributed along with LyX.
864         if (!readRcFile("lyxrc.dist"))
865                 return false;
866
867         // Set the PATH correctly.
868 #if !defined (USE_POSIX_PACKAGING) && !defined (USE_HAIKU_PACKAGING)
869         // Add the directory containing the LyX executable to the path
870         // so that LyX can find things like tex2lyx.
871         if (package().build_support().empty())
872                 prependEnvPath("PATH", package().binary_dir().absFileName());
873 #endif
874         if (!lyxrc.path_prefix.empty())
875                 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
876
877         // Check that user LyX directory is ok.
878         {
879                 string const lock_file = package().getConfigureLockName();
880                 int fd = fileLock(lock_file.c_str());
881
882                 if (queryUserLyXDir(package().explicit_user_support())) {
883                         package().reconfigureUserLyXDir("");
884                         // Now the user directory is present on first start.
885                         initTemplatePath();
886                 }
887                 fileUnlock(fd, lock_file.c_str());
888         }
889
890         if (!use_gui) {
891                 // No need for a splash when there is no GUI
892                 first_start = false;
893                 // Default is to overwrite the main file during export, unless
894                 // the -f switch was specified or LYX_FORCE_OVERWRITE was set
895                 if (force_overwrite == UNSPECIFIED) {
896                         string const what = getEnv("LYX_FORCE_OVERWRITE");
897                         if (what == "all")
898                                 force_overwrite = ALL_FILES;
899                         else if (what == "none")
900                                 force_overwrite = NO_FILES;
901                         else
902                                 force_overwrite = MAIN_FILE;
903                 }
904         }
905
906         // This one is generated in user_support directory by lib/configure.py.
907         if (!readRcFile("lyxrc.defaults"))
908                 return false;
909
910         // Query the OS to know what formats are viewed natively
911         formats.setAutoOpen();
912
913         // Read lyxrc.dist again to be able to override viewer auto-detection.
914         readRcFile("lyxrc.dist");
915
916         system_lyxrc = lyxrc;
917         system_formats = formats;
918         pimpl_->system_converters_ = pimpl_->converters_;
919         pimpl_->system_movers_ = pimpl_->movers_;
920         system_lcolor = lcolor;
921
922         // This one is edited through the preferences dialog.
923         if (!readRcFile("preferences", true))
924                 return false;
925
926         // The language may have been set to someting useful through prefs
927         setLocale();
928
929         if (!readEncodingsFile("encodings", "unicodesymbols"))
930                 return false;
931         if (!readLanguagesFile("languages"))
932                 return false;
933
934         LYXERR(Debug::INIT, "Reading layouts...");
935         // Load the layouts
936         LayoutFileList::get().read();
937         //...and the modules
938         theModuleList.read();
939
940         // read keymap and ui files in batch mode as well
941         // because InsetInfo needs to know these to produce
942         // the correct output
943
944         // Set up command definitions
945         pimpl_->toplevel_cmddef_.read(lyxrc.def_file);
946
947         // FIXME
948         // Set up bindings
949         pimpl_->toplevel_keymap_.read("site");
950         pimpl_->toplevel_keymap_.read(lyxrc.bind_file);
951         // load user bind file user.bind
952         pimpl_->toplevel_keymap_.read("user", 0, KeyMap::MissingOK);
953
954         if (lyxerr.debugging(Debug::LYXRC))
955                 lyxrc.print();
956
957         os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
958         // Prepend path prefix a second time to take the user preferences into a account
959         if (!lyxrc.path_prefix.empty())
960                 prependEnvPath("PATH", replaceEnvironmentPath(lyxrc.path_prefix));
961
962         FileName const document_path(lyxrc.document_path);
963         if (document_path.exists() && document_path.isDirectory())
964                 package().document_dir() = document_path;
965
966         package().set_temp_dir(createLyXTmpDir(FileName(lyxrc.tempdir_path)));
967         if (package().temp_dir().empty()) {
968                 Alert::error(_("Could not create temporary directory"),
969                              bformat(_("Could not create a temporary directory in\n"
970                                                        "\"%1$s\"\n"
971                                                            "Make sure that this path exists and is writable and try again."),
972                                      from_utf8(lyxrc.tempdir_path)));
973                 // createLyXTmpDir() tries sufficiently hard to create a
974                 // usable temp dir, so the probability to come here is
975                 // close to zero. We therefore don't try to overcome this
976                 // problem with e.g. asking the user for a new path and
977                 // trying again but simply exit.
978                 return false;
979         }
980
981         LYXERR(Debug::INIT, "LyX tmp dir: `"
982                             << package().temp_dir().absFileName() << '\'');
983
984         LYXERR(Debug::INIT, "Reading session information '.lyx/session'...");
985         pimpl_->session_.reset(new Session(lyxrc.num_lastfiles));
986
987         // This must happen after package initialization and after lyxrc is
988         // read, therefore it can't be done by a static object.
989         ConverterCache::init();
990
991         return true;
992 }
993
994
995 void emergencyCleanup()
996 {
997         // what to do about tmpfiles is non-obvious. we would
998         // like to delete any we find, but our lyxdir might
999         // contain documents etc. which might be helpful on
1000         // a crash
1001
1002         singleton_->pimpl_->buffer_list_.emergencyWriteAll();
1003         if (use_gui) {
1004                 if (singleton_->pimpl_->lyx_server_)
1005                         singleton_->pimpl_->lyx_server_->emergencyCleanup();
1006                 singleton_->pimpl_->lyx_server_.reset();
1007                 singleton_->pimpl_->lyx_socket_.reset();
1008         }
1009 }
1010
1011
1012 bool LyX::queryUserLyXDir(bool explicit_userdir)
1013 {
1014         // Does user directory exist?
1015         FileName const sup = package().user_support();
1016         if (sup.exists() && sup.isDirectory()) {
1017                 first_start = false;
1018
1019                 return configFileNeedsUpdate("lyxrc.defaults")
1020                         || configFileNeedsUpdate("lyxmodules.lst")
1021                         || configFileNeedsUpdate("textclass.lst")
1022                         || configFileNeedsUpdate("packages.lst");
1023         }
1024
1025         first_start = !explicit_userdir;
1026
1027         // If the user specified explicitly a directory, ask whether
1028         // to create it. If the user says "no", then exit.
1029         if (explicit_userdir &&
1030             Alert::prompt(
1031                     _("Missing user LyX directory"),
1032                     bformat(_("You have specified a non-existent user "
1033                                            "LyX directory, %1$s.\n"
1034                                            "It is needed to keep your own configuration."),
1035                             from_utf8(package().user_support().absFileName())),
1036                     1, 0,
1037                     _("&Create directory"),
1038                     _("&Exit LyX"))) {
1039                 lyxerr << to_utf8(_("No user LyX directory. Exiting.")) << endl;
1040                 earlyExit(EXIT_FAILURE);
1041         }
1042
1043         lyxerr << to_utf8(bformat(_("LyX: Creating directory %1$s"),
1044                           from_utf8(sup.absFileName()))) << endl;
1045
1046         if (!sup.createDirectory(0755)) {
1047                 // Failed, so let's exit.
1048                 lyxerr << to_utf8(_("Failed to create directory. Exiting."))
1049                        << endl;
1050                 earlyExit(EXIT_FAILURE);
1051         }
1052
1053         return true;
1054 }
1055
1056
1057 bool LyX::readRcFile(string const & name, bool check_format)
1058 {
1059         LYXERR(Debug::INIT, "About to read " << name << "... ");
1060
1061         FileName const lyxrc_path = libFileSearch(string(), name);
1062         if (lyxrc_path.empty()) {
1063                 LYXERR(Debug::INIT, "Not found." << lyxrc_path);
1064                 // FIXME
1065                 // This was the previous logic, but can it be right??
1066                 return true;
1067         }
1068         LYXERR(Debug::INIT, "Found in " << lyxrc_path);
1069         bool const success = lyxrc.read(lyxrc_path, check_format);
1070         if (!success)
1071                 showFileError(name);
1072         return success;
1073 }
1074
1075 // Read the languages file `name'
1076 bool LyX::readLanguagesFile(string const & name)
1077 {
1078         LYXERR(Debug::INIT, "About to read " << name << "...");
1079
1080         FileName const lang_path = libFileSearch(string(), name);
1081         if (lang_path.empty()) {
1082                 showFileError(name);
1083                 return false;
1084         }
1085         languages.read(lang_path);
1086         return true;
1087 }
1088
1089
1090 // Read the encodings file `name'
1091 bool LyX::readEncodingsFile(string const & enc_name,
1092                             string const & symbols_name)
1093 {
1094         LYXERR(Debug::INIT, "About to read " << enc_name << " and "
1095                             << symbols_name << "...");
1096
1097         FileName const symbols_path = libFileSearch(string(), symbols_name);
1098         if (symbols_path.empty()) {
1099                 showFileError(symbols_name);
1100                 return false;
1101         }
1102
1103         FileName const enc_path = libFileSearch(string(), enc_name);
1104         if (enc_path.empty()) {
1105                 showFileError(enc_name);
1106                 return false;
1107         }
1108         encodings.read(enc_path, symbols_path);
1109         return true;
1110 }
1111
1112
1113 namespace {
1114
1115 /// return the the number of arguments consumed
1116 typedef function<int(string const &, string const &, string &)> cmd_helper;
1117
1118 int parse_dbg(string const & arg, string const &, string &)
1119 {
1120         if (arg.empty()) {
1121                 cout << to_utf8(_("List of supported debug flags:")) << endl;
1122                 Debug::showTags(cout);
1123                 exit(0);
1124         }
1125         lyxerr << to_utf8(bformat(_("Setting debug level to %1$s"), from_utf8(arg))) << endl;
1126
1127         lyxerr.setLevel(Debug::value(arg));
1128         Debug::showLevel(lyxerr, lyxerr.level());
1129         return 1;
1130 }
1131
1132
1133 int parse_help(string const &, string const &, string &)
1134 {
1135         cout <<
1136                 to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
1137                   "Command line switches (case sensitive):\n"
1138                   "\t-help              summarize LyX usage\n"
1139                   "\t-userdir dir       set user directory to dir\n"
1140                   "\t-sysdir dir        set system directory to dir\n"
1141                   "\t-geometry WxH+X+Y  set geometry of the main window\n"
1142                   "\t-dbg feature[,feature]...\n"
1143                   "                  select the features to debug.\n"
1144                   "                  Type `lyx -dbg' to see the list of features\n"
1145                   "\t-x [--execute] command\n"
1146                   "                  where command is a lyx command.\n"
1147                   "\t-e [--export] fmt\n"
1148                   "                  where fmt is the export format of choice. Look in\n"
1149                   "                  Tools->Preferences->File Handling->File Formats->Short Name\n"
1150                   "                  to see which parameter (which differs from the format name\n"
1151                   "                  in the File->Export menu) should be passed.\n"
1152                   "                  Note that the order of -e and -x switches matters.\n"
1153                   "\t-E [--export-to] fmt filename\n"
1154                   "                  where fmt is the export format of choice (see --export),\n"
1155                   "                  and filename is the destination filename.\n"
1156                   "\t-i [--import] fmt file.xxx\n"
1157                   "                  where fmt is the import format of choice\n"
1158                   "                  and file.xxx is the file to be imported.\n"
1159                   "\t-f [--force-overwrite] what\n"
1160                   "                  where what is either `all', `main' or `none',\n"
1161                   "                  specifying whether all files, main file only, or no files,\n"
1162                   "                  respectively, are to be overwritten during a batch export.\n"
1163                   "                  Anything else is equivalent to `all', but is not consumed.\n"
1164                   "\t-n [--no-remote]\n"
1165                   "                  open documents in a new instance\n"
1166                   "\t-r [--remote]\n"
1167                   "                  open documents in an already running instance\n"
1168                   "                  (a working lyxpipe is needed)\n"
1169                   "\t-v [--verbose]\n"
1170                   "                  report on terminal about spawned commands.\n"
1171                   "\t-batch    execute commands without launching GUI and exit.\n"
1172                   "\t-version  summarize version and build info\n"
1173                                "Check the LyX man page for more details.")) << endl;
1174         exit(0);
1175         return 0;
1176 }
1177
1178
1179 int parse_version(string const &, string const &, string &)
1180 {
1181         cout << "LyX " << lyx_version
1182                << " (" << lyx_release_date << ")" << endl;
1183         if (string(lyx_git_commit_hash) != "none")
1184                 cout << to_utf8(_("  Git commit hash "))
1185                      << string(lyx_git_commit_hash).substr(0,8) << endl;
1186         cout << lyx_version_info << endl;
1187         exit(0);
1188         return 0;
1189 }
1190
1191
1192 int parse_sysdir(string const & arg, string const &, string &)
1193 {
1194         if (arg.empty()) {
1195                 Alert::error(_("No system directory"),
1196                         _("Missing directory for -sysdir switch"));
1197                 exit(1);
1198         }
1199         cl_system_support = arg;
1200         return 1;
1201 }
1202
1203
1204 int parse_userdir(string const & arg, string const &, string &)
1205 {
1206         if (arg.empty()) {
1207                 Alert::error(_("No user directory"),
1208                         _("Missing directory for -userdir switch"));
1209                 exit(1);
1210         }
1211         cl_user_support = arg;
1212         return 1;
1213 }
1214
1215
1216 int parse_execute(string const & arg, string const &, string & batch)
1217 {
1218         if (arg.empty()) {
1219                 Alert::error(_("Incomplete command"),
1220                         _("Missing command string after --execute switch"));
1221                 exit(1);
1222         }
1223         batch = arg;
1224         return 1;
1225 }
1226
1227
1228 int parse_export_to(string const & type, string const & output_file, string & batch)
1229 {
1230         if (type.empty()) {
1231                 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1232                                          "--export-to switch")) << endl;
1233                 exit(1);
1234         }
1235         if (output_file.empty()) {
1236                 lyxerr << to_utf8(_("Missing destination filename after "
1237                                          "--export-to switch")) << endl;
1238                 exit(1);
1239         }
1240         batch = "buffer-export " + type + " " + output_file;
1241         use_gui = false;
1242         return 2;
1243 }
1244
1245
1246 int parse_export(string const & type, string const &, string & batch)
1247 {
1248         if (type.empty()) {
1249                 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1250                                          "--export switch")) << endl;
1251                 exit(1);
1252         }
1253         batch = "buffer-export " + type;
1254         use_gui = false;
1255         return 1;
1256 }
1257
1258
1259 int parse_import(string const & type, string const & file, string & batch)
1260 {
1261         if (type.empty()) {
1262                 lyxerr << to_utf8(_("Missing file type [eg latex, ps...] after "
1263                                          "--import switch")) << endl;
1264                 exit(1);
1265         }
1266         if (file.empty()) {
1267                 lyxerr << to_utf8(_("Missing filename for --import")) << endl;
1268                 exit(1);
1269         }
1270         batch = "buffer-import " + type + ' ' + file;
1271         return 2;
1272 }
1273
1274
1275 int parse_geometry(string const & arg1, string const &, string &)
1276 {
1277         geometryArg = arg1;
1278         // don't remove "-geometry", it will be pruned out later in the
1279         // frontend if need be.
1280         return -1;
1281 }
1282
1283
1284 int parse_batch(string const &, string const &, string &)
1285 {
1286         use_gui = false;
1287         return 0;
1288 }
1289
1290
1291 int parse_noremote(string const &, string const &, string &)
1292 {
1293         run_mode = NEW_INSTANCE;
1294         return 0;
1295 }
1296
1297
1298 int parse_remote(string const &, string const &, string &)
1299 {
1300         run_mode = USE_REMOTE;
1301         return 0;
1302 }
1303
1304
1305 int parse_verbose(string const &, string const &, string &)
1306 {
1307         verbose = true;
1308         return 0;
1309 }
1310
1311
1312 int parse_force(string const & arg, string const &, string &)
1313 {
1314         if (arg == "all") {
1315                 force_overwrite = ALL_FILES;
1316                 return 1;
1317         } else if (arg == "main") {
1318                 force_overwrite = MAIN_FILE;
1319                 return 1;
1320         } else if (arg == "none") {
1321                 force_overwrite = NO_FILES;
1322                 return 1;
1323         }
1324         force_overwrite = ALL_FILES;
1325         return 0;
1326 }
1327
1328
1329 } // namespace anon
1330
1331
1332 void LyX::easyParse(int & argc, char * argv[])
1333 {
1334         map<string, cmd_helper> cmdmap;
1335
1336         cmdmap["-dbg"] = parse_dbg;
1337         cmdmap["-help"] = parse_help;
1338         cmdmap["--help"] = parse_help;
1339         cmdmap["-version"] = parse_version;
1340         cmdmap["--version"] = parse_version;
1341         cmdmap["-sysdir"] = parse_sysdir;
1342         cmdmap["-userdir"] = parse_userdir;
1343         cmdmap["-x"] = parse_execute;
1344         cmdmap["--execute"] = parse_execute;
1345         cmdmap["-e"] = parse_export;
1346         cmdmap["--export"] = parse_export;
1347         cmdmap["-E"] = parse_export_to;
1348         cmdmap["--export-to"] = parse_export_to;
1349         cmdmap["-i"] = parse_import;
1350         cmdmap["--import"] = parse_import;
1351         cmdmap["-geometry"] = parse_geometry;
1352         cmdmap["-batch"] = parse_batch;
1353         cmdmap["-f"] = parse_force;
1354         cmdmap["--force-overwrite"] = parse_force;
1355         cmdmap["-n"] = parse_noremote;
1356         cmdmap["--no-remote"] = parse_noremote;
1357         cmdmap["-r"] = parse_remote;
1358         cmdmap["--remote"] = parse_remote;
1359         cmdmap["-v"] = parse_verbose;
1360         cmdmap["--verbose"] = parse_verbose;
1361
1362         for (int i = 1; i < argc; ++i) {
1363                 map<string, cmd_helper>::const_iterator it
1364                         = cmdmap.find(argv[i]);
1365
1366                 // don't complain if not found - may be parsed later
1367                 if (it == cmdmap.end())
1368                         continue;
1369
1370                 string const arg =
1371                         (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
1372                 string const arg2 =
1373                         (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
1374
1375                 string batch;
1376                 int const remove = 1 + it->second(arg, arg2, batch);
1377                 if (!batch.empty())
1378                         pimpl_->batch_commands.push_back(batch);
1379
1380                 // Now, remove used arguments by shifting
1381                 // the following ones remove places down.
1382                 if (remove > 0) {
1383                         os::remove_internal_args(i, remove);
1384                         argc -= remove;
1385                         for (int j = i; j < argc; ++j)
1386                                 argv[j] = argv[j + remove];
1387                         --i;
1388                 }
1389         }
1390 }
1391
1392
1393 FuncStatus getStatus(FuncRequest const & action)
1394 {
1395         LAPPERR(theApp());
1396         return theApp()->getStatus(action);
1397 }
1398
1399
1400 DispatchResult const & dispatch(FuncRequest const & action)
1401 {
1402         LAPPERR(theApp());
1403         return theApp()->dispatch(action);
1404 }
1405
1406
1407 void dispatch(FuncRequest const & action, DispatchResult & dr)
1408 {
1409         LAPPERR(theApp());
1410         theApp()->dispatch(action, dr);
1411 }
1412
1413
1414 vector<string> & theFilesToLoad()
1415 {
1416         LAPPERR(singleton_);
1417         return singleton_->pimpl_->files_to_load_;
1418 }
1419
1420
1421 BufferList & theBufferList()
1422 {
1423         LAPPERR(singleton_);
1424         return singleton_->pimpl_->buffer_list_;
1425 }
1426
1427
1428 Server & theServer()
1429 {
1430         // FIXME: this should not be use_gui dependent
1431         LWARNIF(use_gui);
1432         LAPPERR(singleton_);
1433         return *singleton_->pimpl_->lyx_server_;
1434 }
1435
1436
1437 ServerSocket & theServerSocket()
1438 {
1439         // FIXME: this should not be use_gui dependent
1440         LWARNIF(use_gui);
1441         LAPPERR(singleton_);
1442         return *singleton_->pimpl_->lyx_socket_;
1443 }
1444
1445
1446 KeyMap & theTopLevelKeymap()
1447 {
1448         LAPPERR(singleton_);
1449         return singleton_->pimpl_->toplevel_keymap_;
1450 }
1451
1452
1453 Converters & theConverters()
1454 {
1455         LAPPERR(singleton_);
1456         return  singleton_->pimpl_->converters_;
1457 }
1458
1459
1460 Converters & theSystemConverters()
1461 {
1462         LAPPERR(singleton_);
1463         return  singleton_->pimpl_->system_converters_;
1464 }
1465
1466
1467 Movers & theMovers()
1468 {
1469         LAPPERR(singleton_);
1470         return singleton_->pimpl_->movers_;
1471 }
1472
1473
1474 Mover const & getMover(string  const & fmt)
1475 {
1476         LAPPERR(singleton_);
1477         return singleton_->pimpl_->movers_(fmt);
1478 }
1479
1480
1481 void setMover(string const & fmt, string const & command)
1482 {
1483         LAPPERR(singleton_);
1484         singleton_->pimpl_->movers_.set(fmt, command);
1485 }
1486
1487
1488 Movers & theSystemMovers()
1489 {
1490         LAPPERR(singleton_);
1491         return singleton_->pimpl_->system_movers_;
1492 }
1493
1494
1495 Messages const & getMessages(string const & language)
1496 {
1497         LAPPERR(singleton_);
1498         return singleton_->messages(language);
1499 }
1500
1501
1502 Messages const & getGuiMessages()
1503 {
1504         LAPPERR(singleton_);
1505         return singleton_->messages(Messages::guiLanguage());
1506 }
1507
1508
1509 Session & theSession()
1510 {
1511         LAPPERR(singleton_);
1512         return *singleton_->pimpl_->session_.get();
1513 }
1514
1515
1516 LaTeXFonts & theLaTeXFonts()
1517 {
1518         LAPPERR(singleton_);
1519         if (!singleton_->pimpl_->latexfonts_)
1520                 singleton_->pimpl_->latexfonts_ = new LaTeXFonts;
1521         return *singleton_->pimpl_->latexfonts_;
1522 }
1523
1524
1525 CmdDef & theTopLevelCmdDef()
1526 {
1527         LAPPERR(singleton_);
1528         return singleton_->pimpl_->toplevel_cmddef_;
1529 }
1530
1531
1532 SpellChecker * theSpellChecker()
1533 {
1534         if (!singleton_->pimpl_->spell_checker_)
1535                 setSpellChecker();
1536         return singleton_->pimpl_->spell_checker_;
1537 }
1538
1539
1540 void setSpellChecker()
1541 {
1542         SpellChecker::ChangeNumber speller_change_number =singleton_->pimpl_->spell_checker_ ?
1543                 singleton_->pimpl_->spell_checker_->changeNumber() : 0;
1544
1545         if (lyxrc.spellchecker == "native") {
1546 #if defined(USE_MACOSX_PACKAGING)
1547                 if (!singleton_->pimpl_->apple_spell_checker_)
1548                         singleton_->pimpl_->apple_spell_checker_ = new AppleSpellChecker;
1549                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->apple_spell_checker_;
1550 #else
1551                 singleton_->pimpl_->spell_checker_ = 0;
1552 #endif
1553         } else if (lyxrc.spellchecker == "aspell") {
1554 #if defined(USE_ASPELL)
1555                 if (!singleton_->pimpl_->aspell_checker_)
1556                         singleton_->pimpl_->aspell_checker_ = new AspellChecker;
1557                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->aspell_checker_;
1558 #else
1559                 singleton_->pimpl_->spell_checker_ = 0;
1560 #endif
1561         } else if (lyxrc.spellchecker == "enchant") {
1562 #if defined(USE_ENCHANT)
1563                 if (!singleton_->pimpl_->enchant_checker_)
1564                         singleton_->pimpl_->enchant_checker_ = new EnchantChecker;
1565                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->enchant_checker_;
1566 #else
1567                 singleton_->pimpl_->spell_checker_ = 0;
1568 #endif
1569         } else if (lyxrc.spellchecker == "hunspell") {
1570 #if defined(USE_HUNSPELL)
1571                 if (!singleton_->pimpl_->hunspell_checker_)
1572                         singleton_->pimpl_->hunspell_checker_ = new HunspellChecker;
1573                 singleton_->pimpl_->spell_checker_ = singleton_->pimpl_->hunspell_checker_;
1574 #else
1575                 singleton_->pimpl_->spell_checker_ = 0;
1576 #endif
1577         } else {
1578                 singleton_->pimpl_->spell_checker_ = 0;
1579         }
1580         if (singleton_->pimpl_->spell_checker_) {
1581                 singleton_->pimpl_->spell_checker_->changeNumber(speller_change_number);
1582                 singleton_->pimpl_->spell_checker_->advanceChangeNumber();
1583         }
1584 }
1585
1586 } // namespace lyx