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