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