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