]> git.lyx.org Git - lyx.git/blob - src/lyx_main.C
cleanup after svn hang-up, #undef CursorShape. Should be compilable ganin now.
[lyx.git] / src / lyx_main.C
1 /**
2  * \file lyx_main.C
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_main.h"
19
20 #include "buffer.h"
21 #include "buffer_funcs.h"
22 #include "bufferlist.h"
23 #include "converter.h"
24 #include "debug.h"
25 #include "encoding.h"
26 #include "errorlist.h"
27 #include "format.h"
28 #include "gettext.h"
29 #include "kbmap.h"
30 #include "language.h"
31 #include "session.h"
32 #include "LColor.h"
33 #include "lyx_cb.h"
34 #include "lyxfunc.h"
35 #include "lyxlex.h"
36 #include "lyxrc.h"
37 #include "lyxtextclasslist.h"
38 #include "lyxserver.h"
39 #include "MenuBackend.h"
40 #include "mover.h"
41 #include "ToolbarBackend.h"
42
43 #include "frontends/Alert.h"
44 #include "frontends/lyx_gui.h"
45 #include "frontends/LyXView.h"
46
47 #include "support/environment.h"
48 #include "support/filetools.h"
49 #include "support/lyxlib.h"
50 #include "support/convert.h"
51 #include "support/os.h"
52 #include "support/package.h"
53 #include "support/path.h"
54 #include "support/systemcall.h"
55
56 #include <boost/bind.hpp>
57 #include <boost/filesystem/operations.hpp>
58
59 #include <iostream>
60 #include <csignal>
61
62 using lyx::support::addName;
63 using lyx::support::addPath;
64 using lyx::support::bformat;
65 using lyx::support::createDirectory;
66 using lyx::support::createLyXTmpDir;
67 using lyx::support::fileSearch;
68 using lyx::support::getEnv;
69 using lyx::support::i18nLibFileSearch;
70 using lyx::support::libFileSearch;
71 using lyx::support::package;
72 using lyx::support::prependEnvPath;
73 using lyx::support::rtrim;
74 using lyx::support::Systemcall;
75
76 using lyx::docstring;
77
78 namespace os = lyx::support::os;
79 namespace fs = boost::filesystem;
80
81 using std::endl;
82 using std::string;
83 using std::vector;
84
85 #ifndef CXX_GLOBAL_CSTD
86 using std::exit;
87 using std::signal;
88 using std::system;
89 #endif
90
91
92 extern LyXServer * lyxserver;
93
94 // This is the global bufferlist object
95 BufferList bufferlist;
96
97 // convenient to have it here.
98 boost::scoped_ptr<kb_keymap> toplevel_keymap;
99
100 namespace {
101
102 // Filled with the command line arguments "foo" of "-sysdir foo" or
103 // "-userdir foo".
104 string cl_system_support;
105 string cl_user_support;
106
107
108 void lyx_exit(int status)
109 {
110         // FIXME: We should not directly call exit(), since it only
111         // guarantees a return to the system, no application cleanup.
112         // This may cause troubles with not executed destructors.
113         if (lyx_gui::use_gui)
114                 // lyx_gui::exit may return and only schedule the exit
115                 lyx_gui::exit(status);
116         exit(status);
117 }
118
119
120 void showFileError(string const & error)
121 {
122         Alert::warning(_("Could not read configuration file"),
123                        bformat(_("Error while reading the configuration file\n%1$s.\n"
124                            "Please check your installation."), lyx::from_utf8(error)));
125 }
126
127
128 void reconfigureUserLyXDir()
129 {
130         string const configure_command = package().configure_command();
131
132         lyxerr << lyx::to_utf8(_("LyX: reconfiguring user directory")) << endl;
133         lyx::support::Path p(package().user_support());
134         Systemcall one;
135         one.startscript(Systemcall::Wait, configure_command);
136         lyxerr << "LyX: " << lyx::to_utf8(_("Done!")) << endl;
137 }
138
139 } // namespace anon
140
141
142 boost::scoped_ptr<LyX> LyX::singleton_;
143
144 int LyX::exec(int & argc, char * argv[])
145 {
146         BOOST_ASSERT(!singleton_.get());
147         // We must return from this before launching the gui so that
148         // other parts of the code can access singleton_ through
149         // LyX::ref and LyX::cref.
150         singleton_.reset(new LyX);
151         // Start the real execution loop.
152         return singleton_->priv_exec(argc, argv);
153 }
154
155
156 LyX & LyX::ref()
157 {
158         BOOST_ASSERT(singleton_.get());
159         return *singleton_.get();
160 }
161
162
163 LyX const & LyX::cref()
164 {
165         BOOST_ASSERT(singleton_.get());
166         return *singleton_.get();
167 }
168
169
170 LyX::LyX()
171         : first_start(false), geometryOption_(false)
172 {}
173
174
175 lyx::Session & LyX::session()
176 {
177         BOOST_ASSERT(session_.get());
178         return *session_.get();
179 }
180
181
182 lyx::Session const & LyX::session() const
183 {
184         BOOST_ASSERT(session_.get());
185         return *session_.get();
186 }
187
188
189 void LyX::addLyXView(LyXView * lyxview)
190 {
191         views_.push_back(lyxview);
192 }
193
194
195 Buffer const * const LyX::updateInset(InsetBase const * inset) const
196 {
197         if (!inset)
198                 return 0;
199
200         Buffer const * buffer_ptr = 0;
201         ViewList::const_iterator it = views_.begin();
202         ViewList::const_iterator const end = views_.end();
203         for (; it != end; ++it) {
204                 Buffer const * ptr = (*it)->updateInset(inset);
205                 if (ptr)
206                         buffer_ptr = ptr;
207         }
208         return buffer_ptr;
209 }
210
211
212 int LyX::priv_exec(int & argc, char * argv[])
213 {
214         // Here we need to parse the command line. At least
215         // we need to parse for "-dbg" and "-help"
216         lyx_gui::use_gui = easyParse(argc, argv);
217
218         lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
219                                    lyx::support::top_build_dir_is_one_level_up);
220
221         // Start the real execution loop.
222         if (lyx_gui::use_gui)
223                 return lyx_gui::exec(argc, argv);
224         else
225                 return exec2(argc, argv);
226 }
227
228
229 int LyX::exec2(int & argc, char * argv[])
230 {
231         // check for any spurious extra arguments
232         // other than documents
233         for (int argi = 1; argi < argc ; ++argi) {
234                 if (argv[argi][0] == '-') {
235                         lyxerr << lyx::to_utf8(
236                                 bformat(_("Wrong command line option `%1$s'. Exiting."),
237                                 lyx::from_utf8(argv[argi]))) << endl;
238                         return EXIT_FAILURE;
239                 }
240         }
241
242         // Initialization of LyX (reads lyxrc and more)
243         lyxerr[Debug::INIT] << "Initializing LyX::init..." << endl;
244         bool const success = init();
245         lyxerr[Debug::INIT] << "Initializing LyX::init...done" << endl;
246         if (!success)
247                 return EXIT_FAILURE;
248
249         if (lyx_gui::use_gui)
250                 lyx_gui::parse_lyxrc();
251
252         vector<string> files;
253
254         for (int argi = argc - 1; argi >= 1; --argi)
255                 files.push_back(os::internal_path(argv[argi]));
256
257         if (first_start)
258                 files.push_back(i18nLibFileSearch("examples", "splash.lyx"));
259
260         // Execute batch commands if available
261         if (!batch_command.empty()) {
262
263                 lyxerr[Debug::INIT] << "About to handle -x '"
264                        << batch_command << '\'' << endl;
265
266                 Buffer * last_loaded = 0;
267
268                 vector<string>::const_iterator it = files.begin();
269                 vector<string>::const_iterator end = files.end();
270
271                 for (; it != end; ++it) {
272                         // get absolute path of file and add ".lyx" to
273                         // the filename if necessary
274                         string s = fileSearch(string(), *it, "lyx");
275                         if (s.empty()) {
276                                 Buffer * const b = newFile(*it, string(), true);
277                                 if (b)
278                                         last_loaded = b;
279                         } else {
280                                 Buffer * buf = bufferlist.newBuffer(s, false);
281                                 if (loadLyXFile(buf, s)) {
282                                         last_loaded = buf;
283                                         ErrorList const & el = buf->errorList("Parse");
284                                         if (!el.empty())
285                                                 for_each(el.begin(), el.end(),
286                                                         boost::bind(&LyX::printError, this, _1));
287                                 }
288                                 else
289                                         bufferlist.release(buf);
290                         }
291                 }
292
293                 // try to dispatch to last loaded buffer first
294                 if (last_loaded) {
295                         bool success = false;
296                         if (last_loaded->dispatch(batch_command, &success)) {
297                                 quitLyX(false);
298                                 return !success;
299                         }
300                 }
301                 files.clear(); // the files are already loaded
302         }
303
304         if (lyx_gui::use_gui) {
305                 // determine windows size and position, from lyxrc and/or session
306                 // initial geometry
307                 unsigned int width = 690;
308                 unsigned int height = 510;
309                 bool maximize = false;
310                 // first try lyxrc
311                 if (lyxrc.geometry_width != 0 && lyxrc.geometry_height != 0 ) {
312                         width = lyxrc.geometry_width;
313                         height = lyxrc.geometry_height;
314                 }
315                 // if lyxrc returns (0,0), then use session info
316                 else {
317                         string val = session().loadSessionInfo("WindowWidth");
318                         if (!val.empty())
319                                 width = convert<unsigned int>(val);
320                         val = session().loadSessionInfo("WindowHeight");
321                         if (!val.empty())
322                                 height = convert<unsigned int>(val);
323                         if (session().loadSessionInfo("WindowIsMaximized") == "yes")
324                                 maximize = true;
325                 }
326                 // if user wants to restore window position
327                 int posx = -1;
328                 int posy = -1;
329                 if (lyxrc.geometry_xysaved) {
330                         string val = session().loadSessionInfo("WindowPosX");
331                         if (!val.empty())
332                                 posx = convert<int>(val);
333                         val = session().loadSessionInfo("WindowPosY");
334                         if (!val.empty())
335                                 posy = convert<int>(val);
336                 }
337
338                 if (geometryOption_) {
339                         width = 0;
340                         height = 0;
341                 }
342                 // create the main window
343                 LyXView * view = lyx_gui::create_view(width, height, posx, posy, maximize);
344
345                 // load files
346                 for_each(files.begin(), files.end(),
347                         bind(&LyXView::loadLyXFile, view, _1, true));
348
349                 // if a file is specified, I assume that user wants to edit *that* file
350                 if (files.empty() && lyxrc.load_session) {
351                         vector<string> const & lastopened = session_->lastOpenedFiles();
352                         // do not add to the lastfile list since these files are restored from
353                         // last seesion, and should be already there (regular files), or should
354                         // not be added at all (help files).
355                         for_each(lastopened.begin(), lastopened.end(),
356                                 bind(&LyXView::loadLyXFile, view, _1, false));
357                 }
358                 // clear this list to save a few bytes of RAM
359                 session_->clearLastOpenedFiles();
360
361                 return lyx_gui::start(view, batch_command);
362         } else {
363                 // Something went wrong above
364                 quitLyX(false);
365                 return EXIT_FAILURE;
366         }
367 }
368
369
370 /*
371 Signals and Windows
372 ===================
373 The SIGHUP signal does not exist on Windows and does not need to be handled.
374
375 Windows handles SIGFPE and SIGSEGV signals as expected.
376
377 Cntl+C interrupts (mapped to SIGINT by Windows' POSIX compatability layer)
378 cause a new thread to be spawned. This may well result in unexpected
379 behaviour by the single-threaded LyX.
380
381 SIGTERM signals will come only from another process actually sending
382 that signal using 'raise' in Windows' POSIX compatability layer. It will
383 not come from the general "terminate process" methods that everyone
384 actually uses (and which can't be trapped). Killing an app 'politely' on
385 Windows involves first sending a WM_CLOSE message, something that is
386 caught already by the Qt frontend.
387
388 For more information see:
389
390 http://aspn.activestate.com/ASPN/Mail/Message/ActiveTcl/2034055
391 ...signals are mostly useless on Windows for a variety of reasons that are
392 Windows specific...
393
394 'UNIX Application Migration Guide, Chapter 9'
395 http://msdn.microsoft.com/library/en-us/dnucmg/html/UCMGch09.asp
396
397 'How To Terminate an Application "Cleanly" in Win32'
398 http://support.microsoft.com/default.aspx?scid=kb;en-us;178893
399 */
400 extern "C" {
401
402 static void error_handler(int err_sig)
403 {
404         // Throw away any signals other than the first one received.
405         static sig_atomic_t handling_error = false;
406         if (handling_error)
407                 return;
408         handling_error = true;
409
410         // We have received a signal indicating a fatal error, so
411         // try and save the data ASAP.
412         LyX::cref().emergencyCleanup();
413
414         // These lyxerr calls may or may not work:
415
416         // Signals are asynchronous, so the main program may be in a very
417         // fragile state when a signal is processed and thus while a signal
418         // handler function executes.
419         // In general, therefore, we should avoid performing any
420         // I/O operations or calling most library and system functions from
421         // signal handlers.
422
423         // This shouldn't matter here, however, as we've already invoked
424         // emergencyCleanup.
425         switch (err_sig) {
426 #ifdef SIGHUP
427         case SIGHUP:
428                 lyxerr << "\nlyx: SIGHUP signal caught\nBye." << endl;
429                 break;
430 #endif
431         case SIGFPE:
432                 lyxerr << "\nlyx: SIGFPE signal caught\nBye." << endl;
433                 break;
434         case SIGSEGV:
435                 lyxerr << "\nlyx: SIGSEGV signal caught\n"
436                           "Sorry, you have found a bug in LyX. "
437                           "Please read the bug-reporting instructions "
438                           "in Help->Introduction and send us a bug report, "
439                           "if necessary. Thanks !\nBye." << endl;
440                 break;
441         case SIGINT:
442         case SIGTERM:
443                 // no comments
444                 break;
445         }
446
447         // Deinstall the signal handlers
448 #ifdef SIGHUP
449         signal(SIGHUP, SIG_DFL);
450 #endif
451         signal(SIGINT, SIG_DFL);
452         signal(SIGFPE, SIG_DFL);
453         signal(SIGSEGV, SIG_DFL);
454         signal(SIGTERM, SIG_DFL);
455
456 #ifdef SIGHUP
457         if (err_sig == SIGSEGV ||
458             (err_sig != SIGHUP && !getEnv("LYXDEBUG").empty()))
459 #else
460         if (err_sig == SIGSEGV || !getEnv("LYXDEBUG").empty())
461 #endif
462                 lyx::support::abort();
463         exit(0);
464 }
465
466 }
467
468
469 void LyX::printError(ErrorItem const & ei)
470 {
471         docstring tmp = _("LyX: ") + ei.error + lyx::char_type(':')
472                 + ei.description;
473         std::cerr << lyx::to_utf8(tmp) << std::endl;
474 }
475
476
477 bool LyX::init()
478 {
479 #ifdef SIGHUP
480         signal(SIGHUP, error_handler);
481 #endif
482         signal(SIGFPE, error_handler);
483         signal(SIGSEGV, error_handler);
484         signal(SIGINT, error_handler);
485         signal(SIGTERM, error_handler);
486         // SIGPIPE can be safely ignored.
487
488         lyxrc.tempdir_path = package().temp_dir();
489         lyxrc.document_path = package().document_dir();
490
491         if (lyxrc.template_path.empty()) {
492                 lyxrc.template_path = addPath(package().system_support(),
493                                               "templates");
494         }
495
496         if (lyxrc.roman_font_name.empty())
497                 lyxrc.roman_font_name = lyx_gui::roman_font_name();
498         if (lyxrc.sans_font_name.empty())
499                 lyxrc.sans_font_name = lyx_gui::sans_font_name();
500         if (lyxrc.typewriter_font_name.empty())
501                 lyxrc.typewriter_font_name = lyx_gui::typewriter_font_name();
502
503         //
504         // Read configuration files
505         //
506
507         // This one may have been distributed along with LyX.
508         if (!readRcFile("lyxrc.dist"))
509                 return false;
510
511         // Set the PATH correctly.
512 #if !defined (USE_POSIX_PACKAGING)
513         // Add the directory containing the LyX executable to the path
514         // so that LyX can find things like tex2lyx.
515         if (package().build_support().empty())
516                 prependEnvPath("PATH", package().binary_dir());
517 #endif
518         if (!lyxrc.path_prefix.empty())
519                 prependEnvPath("PATH", lyxrc.path_prefix);
520
521         // Check that user LyX directory is ok.
522         if (queryUserLyXDir(package().explicit_user_support()))
523                 reconfigureUserLyXDir();
524
525         // no need for a splash when there is no GUI
526         if (!lyx_gui::use_gui) {
527                 first_start = false;
528         }
529
530         // This one is generated in user_support directory by lib/configure.py.
531         if (!readRcFile("lyxrc.defaults"))
532                 return false;
533
534         // Query the OS to know what formats are viewed natively
535         formats.setAutoOpen();
536
537         system_lyxrc = lyxrc;
538         system_formats = formats;
539         system_converters = converters;
540         system_movers = movers;
541         system_lcolor = lcolor;
542
543         // This one is edited through the preferences dialog.
544         if (!readRcFile("preferences"))
545                 return false;
546
547         if (!readEncodingsFile("encodings"))
548                 return false;
549         if (!readLanguagesFile("languages"))
550                 return false;
551
552         // Load the layouts
553         lyxerr[Debug::INIT] << "Reading layouts..." << endl;
554         if (!LyXSetStyle())
555                 return false;
556
557         if (lyx_gui::use_gui) {
558                 // Set up bindings
559                 toplevel_keymap.reset(new kb_keymap);
560                 defaultKeyBindings(toplevel_keymap.get());
561                 toplevel_keymap->read(lyxrc.bind_file);
562
563                 // Read menus
564                 if (!readUIFile(lyxrc.ui_file))
565                         return false;
566         }
567
568         if (lyxerr.debugging(Debug::LYXRC))
569                 lyxrc.print();
570
571         os::windows_style_tex_paths(lyxrc.windows_style_tex_paths);
572         if (!lyxrc.path_prefix.empty())
573                 prependEnvPath("PATH", lyxrc.path_prefix);
574
575         if (fs::exists(lyxrc.document_path) &&
576             fs::is_directory(lyxrc.document_path))
577                 package().document_dir() = lyxrc.document_path;
578
579         package().temp_dir() = createLyXTmpDir(lyxrc.tempdir_path);
580         if (package().temp_dir().empty()) {
581                 Alert::error(_("Could not create temporary directory"),
582                              bformat(_("Could not create a temporary directory in\n"
583                                                     "%1$s. Make sure that this\n"
584                                                     "path exists and is writable and try again."),
585                                      lyx::from_utf8(lyxrc.tempdir_path)));
586                 // createLyXTmpDir() tries sufficiently hard to create a
587                 // usable temp dir, so the probability to come here is
588                 // close to zero. We therefore don't try to overcome this
589                 // problem with e.g. asking the user for a new path and
590                 // trying again but simply exit.
591                 return false;
592         }
593
594         if (lyxerr.debugging(Debug::INIT)) {
595                 lyxerr << "LyX tmp dir: `" << package().temp_dir() << '\'' << endl;
596         }
597
598         lyxerr[Debug::INIT] << "Reading session information '.lyx/session'..." << endl;
599         session_.reset(new lyx::Session(lyxrc.num_lastfiles));
600         return true;
601 }
602
603
604 void LyX::defaultKeyBindings(kb_keymap  * kbmap)
605 {
606         kbmap->bind("Right", FuncRequest(LFUN_CHAR_FORWARD));
607         kbmap->bind("Left", FuncRequest(LFUN_CHAR_BACKWARD));
608         kbmap->bind("Up", FuncRequest(LFUN_UP));
609         kbmap->bind("Down", FuncRequest(LFUN_DOWN));
610
611         kbmap->bind("Tab", FuncRequest(LFUN_CELL_FORWARD));
612         kbmap->bind("C-Tab", FuncRequest(LFUN_CELL_SPLIT));
613         kbmap->bind("~S-ISO_Left_Tab", FuncRequest(LFUN_CELL_BACKWARD));
614         kbmap->bind("~S-BackTab", FuncRequest(LFUN_CELL_BACKWARD));
615
616         kbmap->bind("Home", FuncRequest(LFUN_LINE_BEGIN));
617         kbmap->bind("End", FuncRequest(LFUN_LINE_END));
618         kbmap->bind("Prior", FuncRequest(LFUN_SCREEN_UP));
619         kbmap->bind("Next", FuncRequest(LFUN_SCREEN_DOWN));
620
621         kbmap->bind("Return", FuncRequest(LFUN_BREAK_PARAGRAPH));
622         //kbmap->bind("~C-~S-~M-nobreakspace", FuncRequest(LFUN_PROTECTEDSPACE));
623
624         kbmap->bind("Delete", FuncRequest(LFUN_CHAR_DELETE_FORWARD));
625         kbmap->bind("BackSpace", FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
626
627         // kbmap->bindings to enable the use of the numeric keypad
628         // e.g. Num Lock set
629         //kbmap->bind("KP_0", FuncRequest(LFUN_SELF_INSERT));
630         //kbmap->bind("KP_Decimal", FuncRequest(LFUN_SELF_INSERT));
631         kbmap->bind("KP_Enter", FuncRequest(LFUN_BREAK_PARAGRAPH));
632         //kbmap->bind("KP_1", FuncRequest(LFUN_SELF_INSERT));
633         //kbmap->bind("KP_2", FuncRequest(LFUN_SELF_INSERT));
634         //kbmap->bind("KP_3", FuncRequest(LFUN_SELF_INSERT));
635         //kbmap->bind("KP_4", FuncRequest(LFUN_SELF_INSERT));
636         //kbmap->bind("KP_5", FuncRequest(LFUN_SELF_INSERT));
637         //kbmap->bind("KP_6", FuncRequest(LFUN_SELF_INSERT));
638         //kbmap->bind("KP_Add", FuncRequest(LFUN_SELF_INSERT));
639         //kbmap->bind("KP_7", FuncRequest(LFUN_SELF_INSERT));
640         //kbmap->bind("KP_8", FuncRequest(LFUN_SELF_INSERT));
641         //kbmap->bind("KP_9", FuncRequest(LFUN_SELF_INSERT));
642         //kbmap->bind("KP_Divide", FuncRequest(LFUN_SELF_INSERT));
643         //kbmap->bind("KP_Multiply", FuncRequest(LFUN_SELF_INSERT));
644         //kbmap->bind("KP_Subtract", FuncRequest(LFUN_SELF_INSERT));
645         kbmap->bind("KP_Right", FuncRequest(LFUN_CHAR_FORWARD));
646         kbmap->bind("KP_Left", FuncRequest(LFUN_CHAR_BACKWARD));
647         kbmap->bind("KP_Up", FuncRequest(LFUN_UP));
648         kbmap->bind("KP_Down", FuncRequest(LFUN_DOWN));
649         kbmap->bind("KP_Home", FuncRequest(LFUN_LINE_BEGIN));
650         kbmap->bind("KP_End", FuncRequest(LFUN_LINE_END));
651         kbmap->bind("KP_Prior", FuncRequest(LFUN_SCREEN_UP));
652         kbmap->bind("KP_Next", FuncRequest(LFUN_SCREEN_DOWN));
653 }
654
655
656 void LyX::emergencyCleanup() const
657 {
658         // what to do about tmpfiles is non-obvious. we would
659         // like to delete any we find, but our lyxdir might
660         // contain documents etc. which might be helpful on
661         // a crash
662
663         bufferlist.emergencyWriteAll();
664         if (lyxserver)
665                 lyxserver->emergencyCleanup();
666 }
667
668
669 void LyX::deadKeyBindings(kb_keymap * kbmap)
670 {
671         // bindKeyings for transparent handling of deadkeys
672         // The keysyms are gotten from XFree86 X11R6
673         kbmap->bind("~C-~S-~M-dead_acute", FuncRequest(LFUN_ACCENT_ACUTE));
674         kbmap->bind("~C-~S-~M-dead_breve", FuncRequest(LFUN_ACCENT_BREVE));
675         kbmap->bind("~C-~S-~M-dead_caron", FuncRequest(LFUN_ACCENT_CARON));
676         kbmap->bind("~C-~S-~M-dead_cedilla", FuncRequest(LFUN_ACCENT_CEDILLA));
677         kbmap->bind("~C-~S-~M-dead_abovering", FuncRequest(LFUN_ACCENT_CIRCLE));
678         kbmap->bind("~C-~S-~M-dead_circumflex", FuncRequest(LFUN_ACCENT_CIRCUMFLEX));
679         kbmap->bind("~C-~S-~M-dead_abovedot", FuncRequest(LFUN_ACCENT_DOT));
680         kbmap->bind("~C-~S-~M-dead_grave", FuncRequest(LFUN_ACCENT_GRAVE));
681         kbmap->bind("~C-~S-~M-dead_doubleacute", FuncRequest(LFUN_ACCENT_HUNGARIAN_UMLAUT));
682         kbmap->bind("~C-~S-~M-dead_macron", FuncRequest(LFUN_ACCENT_MACRON));
683         // nothing with this name
684         // kbmap->bind("~C-~S-~M-dead_special_caron", LFUN_ACCENT_SPECIAL_CARON);
685         kbmap->bind("~C-~S-~M-dead_tilde", FuncRequest(LFUN_ACCENT_TILDE));
686         kbmap->bind("~C-~S-~M-dead_diaeresis", FuncRequest(LFUN_ACCENT_UMLAUT));
687         // nothing with this name either...
688         //kbmap->bind("~C-~S-~M-dead_underbar", FuncRequest(LFUN_ACCENT_UNDERBAR));
689         kbmap->bind("~C-~S-~M-dead_belowdot", FuncRequest(LFUN_ACCENT_UNDERDOT));
690         kbmap->bind("~C-~S-~M-dead_tie", FuncRequest(LFUN_ACCENT_TIE));
691         kbmap->bind("~C-~S-~M-dead_ogonek",FuncRequest(LFUN_ACCENT_OGONEK));
692 }
693
694
695 namespace {
696
697 // return true if file does not exist or is older than configure.py.
698 bool needsUpdate(string const & file)
699 {
700         static string const configure_script =
701                 addName(package().system_support(), "configure.py");
702         string const absfile =
703                 addName(package().user_support(), file);
704
705         return (! fs::exists(absfile))
706                 || (fs::last_write_time(configure_script)
707                     > fs::last_write_time(absfile));
708 }
709
710 }
711
712
713 bool LyX::queryUserLyXDir(bool explicit_userdir)
714 {
715         // Does user directory exist?
716         if (fs::exists(package().user_support()) &&
717             fs::is_directory(package().user_support())) {
718                 first_start = false;
719
720                 return needsUpdate("lyxrc.defaults")
721                         || needsUpdate("textclass.lst")
722                         || needsUpdate("packages.lst");
723         }
724
725         first_start = !explicit_userdir;
726
727         // If the user specified explicitly a directory, ask whether
728         // to create it. If the user says "no", then exit.
729         if (explicit_userdir &&
730             Alert::prompt(
731                     _("Missing user LyX directory"),
732                     bformat(_("You have specified a non-existent user "
733                                            "LyX directory, %1$s.\n"
734                                            "It is needed to keep your own configuration."),
735                             lyx::from_utf8(package().user_support())),
736                     1, 0,
737                     _("&Create directory"),
738                     _("&Exit LyX"))) {
739                 lyxerr << lyx::to_utf8(_("No user LyX directory. Exiting.")) << endl;
740                 lyx_exit(EXIT_FAILURE);
741         }
742
743         lyxerr << lyx::to_utf8(bformat(_("LyX: Creating directory %1$s"),
744                           lyx::from_utf8(package().user_support())))
745                << endl;
746
747         if (!createDirectory(package().user_support(), 0755)) {
748                 // Failed, so let's exit.
749                 lyxerr << lyx::to_utf8(_("Failed to create directory. Exiting."))
750                        << endl;
751                 lyx_exit(EXIT_FAILURE);
752         }
753
754         return true;
755 }
756
757
758 bool LyX::readRcFile(string const & name)
759 {
760         lyxerr[Debug::INIT] << "About to read " << name << "... ";
761
762         string const lyxrc_path = libFileSearch(string(), name);
763         if (!lyxrc_path.empty()) {
764
765                 lyxerr[Debug::INIT] << "Found in " << lyxrc_path << endl;
766
767                 if (lyxrc.read(lyxrc_path) < 0) {
768                         showFileError(name);
769                         return false;
770                 }
771         } else
772                 lyxerr[Debug::INIT] << "Not found." << lyxrc_path << endl;
773         return true;
774
775 }
776
777
778 // Read the ui file `name'
779 bool LyX::readUIFile(string const & name)
780 {
781         enum Uitags {
782                 ui_menuset = 1,
783                 ui_toolbar,
784                 ui_toolbars,
785                 ui_include,
786                 ui_last
787         };
788
789         struct keyword_item uitags[ui_last - 1] = {
790                 { "include", ui_include },
791                 { "menuset", ui_menuset },
792                 { "toolbar", ui_toolbar },
793                 { "toolbars", ui_toolbars }
794         };
795
796         // Ensure that a file is read only once (prevents include loops)
797         static std::list<string> uifiles;
798         std::list<string>::const_iterator it  = uifiles.begin();
799         std::list<string>::const_iterator end = uifiles.end();
800         it = std::find(it, end, name);
801         if (it != end) {
802                 lyxerr[Debug::INIT] << "UI file '" << name
803                                     << "' has been read already. "
804                                     << "Is this an include loop?"
805                                     << endl;
806                 return false;
807         }
808
809         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
810
811         string const ui_path = libFileSearch("ui", name, "ui");
812
813         if (ui_path.empty()) {
814                 lyxerr[Debug::INIT] << "Could not find " << name << endl;
815                 showFileError(name);
816                 return false;
817         }
818         uifiles.push_back(name);
819
820         lyxerr[Debug::INIT] << "Found " << name
821                             << " in " << ui_path << endl;
822         LyXLex lex(uitags, ui_last - 1);
823         lex.setFile(ui_path);
824         if (!lex.isOK()) {
825                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
826                        << endl;
827         }
828
829         if (lyxerr.debugging(Debug::PARSER))
830                 lex.printTable(lyxerr);
831
832         while (lex.isOK()) {
833                 switch (lex.lex()) {
834                 case ui_include: {
835                         lex.next(true);
836                         string const file = lex.getString();
837                         if (!readUIFile(file))
838                                 return false;
839                         break;
840                 }
841                 case ui_menuset:
842                         menubackend.read(lex);
843                         break;
844
845                 case ui_toolbar:
846                         toolbarbackend.read(lex);
847                         break;
848
849                 case ui_toolbars:
850                         toolbarbackend.readToolbars(lex);
851                         break;
852
853                 default:
854                         if (!rtrim(lex.getString()).empty())
855                                 lex.printError("LyX::ReadUIFile: "
856                                                "Unknown menu tag: `$$Token'");
857                         break;
858                 }
859         }
860         return true;
861 }
862
863
864 // Read the languages file `name'
865 bool LyX::readLanguagesFile(string const & name)
866 {
867         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
868
869         string const lang_path = libFileSearch(string(), name);
870         if (lang_path.empty()) {
871                 showFileError(name);
872                 return false;
873         }
874         languages.read(lang_path);
875         return true;
876 }
877
878
879 // Read the encodings file `name'
880 bool LyX::readEncodingsFile(string const & name)
881 {
882         lyxerr[Debug::INIT] << "About to read " << name << "..." << endl;
883
884         string const enc_path = libFileSearch(string(), name);
885         if (enc_path.empty()) {
886                 showFileError(name);
887                 return false;
888         }
889         encodings.read(enc_path);
890         return true;
891 }
892
893
894 namespace {
895
896 bool is_gui = true;
897 string batch;
898
899 /// return the the number of arguments consumed
900 typedef boost::function<int(string const &, string const &)> cmd_helper;
901
902 int parse_dbg(string const & arg, string const &)
903 {
904         if (arg.empty()) {
905                 lyxerr << lyx::to_utf8(_("List of supported debug flags:")) << endl;
906                 Debug::showTags(lyxerr);
907                 exit(0);
908         }
909         lyxerr << lyx::to_utf8(bformat(_("Setting debug level to %1$s"), lyx::from_utf8(arg))) << endl;
910
911         lyxerr.level(Debug::value(arg));
912         Debug::showLevel(lyxerr, lyxerr.level());
913         return 1;
914 }
915
916
917 int parse_help(string const &, string const &)
918 {
919         lyxerr <<
920                 lyx::to_utf8(_("Usage: lyx [ command line switches ] [ name.lyx ... ]\n"
921                   "Command line switches (case sensitive):\n"
922                   "\t-help              summarize LyX usage\n"
923                   "\t-userdir dir       set user directory to dir\n"
924                   "\t-sysdir dir        set system directory to dir\n"
925                   "\t-geometry WxH+X+Y  set geometry of the main window\n"
926                   "\t-dbg feature[,feature]...\n"
927                   "                  select the features to debug.\n"
928                   "                  Type `lyx -dbg' to see the list of features\n"
929                   "\t-x [--execute] command\n"
930                   "                  where command is a lyx command.\n"
931                   "\t-e [--export] fmt\n"
932                   "                  where fmt is the export format of choice.\n"
933                   "\t-i [--import] fmt file.xxx\n"
934                   "                  where fmt is the import format of choice\n"
935                   "                  and file.xxx is the file to be imported.\n"
936                   "\t-version        summarize version and build info\n"
937                                "Check the LyX man page for more details.")) << endl;
938         exit(0);
939         return 0;
940 }
941
942 int parse_version(string const &, string const &)
943 {
944         lyxerr << "LyX " << lyx_version
945                << " (" << lyx_release_date << ")" << endl;
946         lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
947
948         lyxerr << lyx_version_info << endl;
949         exit(0);
950         return 0;
951 }
952
953 int parse_sysdir(string const & arg, string const &)
954 {
955         if (arg.empty()) {
956                 lyxerr << lyx::to_utf8(_("Missing directory for -sysdir switch")) << endl;
957                 exit(1);
958         }
959         cl_system_support = arg;
960         return 1;
961 }
962
963 int parse_userdir(string const & arg, string const &)
964 {
965         if (arg.empty()) {
966                 lyxerr << lyx::to_utf8(_("Missing directory for -userdir switch")) << endl;
967                 exit(1);
968         }
969         cl_user_support = arg;
970         return 1;
971 }
972
973 int parse_execute(string const & arg, string const &)
974 {
975         if (arg.empty()) {
976                 lyxerr << lyx::to_utf8(_("Missing command string after --execute switch")) << endl;
977                 exit(1);
978         }
979         batch = arg;
980         return 1;
981 }
982
983 int parse_export(string const & type, string const &)
984 {
985         if (type.empty()) {
986                 lyxerr << lyx::to_utf8(_("Missing file type [eg latex, ps...] after "
987                                          "--export switch")) << endl;
988                 exit(1);
989         }
990         batch = "buffer-export " + type;
991         is_gui = false;
992         return 1;
993 }
994
995 int parse_import(string const & type, string const & file)
996 {
997         if (type.empty()) {
998                 lyxerr << lyx::to_utf8(_("Missing file type [eg latex, ps...] after "
999                                          "--import switch")) << endl;
1000                 exit(1);
1001         }
1002         if (file.empty()) {
1003                 lyxerr << lyx::to_utf8(_("Missing filename for --import")) << endl;
1004                 exit(1);
1005         }
1006
1007         batch = "buffer-import " + type + ' ' + file;
1008         return 2;
1009 }
1010
1011 } // namespace anon
1012
1013
1014 bool LyX::easyParse(int & argc, char * argv[])
1015 {
1016         std::map<string, cmd_helper> cmdmap;
1017
1018         cmdmap["-dbg"] = parse_dbg;
1019         cmdmap["-help"] = parse_help;
1020         cmdmap["--help"] = parse_help;
1021         cmdmap["-version"] = parse_version;
1022         cmdmap["--version"] = parse_version;
1023         cmdmap["-sysdir"] = parse_sysdir;
1024         cmdmap["-userdir"] = parse_userdir;
1025         cmdmap["-x"] = parse_execute;
1026         cmdmap["--execute"] = parse_execute;
1027         cmdmap["-e"] = parse_export;
1028         cmdmap["--export"] = parse_export;
1029         cmdmap["-i"] = parse_import;
1030         cmdmap["--import"] = parse_import;
1031
1032         for (int i = 1; i < argc; ++i) {
1033                 std::map<string, cmd_helper>::const_iterator it
1034                         = cmdmap.find(argv[i]);
1035
1036                 // check for X11 -geometry option
1037                 if (lyx::support::compare(argv[i], "-geometry") == 0)
1038                         geometryOption_ = true;
1039
1040                 // don't complain if not found - may be parsed later
1041                 if (it == cmdmap.end())
1042                         continue;
1043
1044                 string arg((i + 1 < argc) ? argv[i + 1] : "");
1045                 string arg2((i + 2 < argc) ? argv[i + 2] : "");
1046
1047                 int const remove = 1 + it->second(arg, arg2);
1048
1049                 // Now, remove used arguments by shifting
1050                 // the following ones remove places down.
1051                 argc -= remove;
1052                 for (int j = i; j < argc; ++j)
1053                         argv[j] = argv[j + remove];
1054                 --i;
1055         }
1056
1057         batch_command = batch;
1058
1059         return is_gui;
1060 }