]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
Fix "stray '}' in text" warnings: When parsing with FLAG_ITEM the braces need
[lyx.git] / src / tex2lyx / tex2lyx.cpp
1 /**
2  * \file tex2lyx.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 // {[(
12
13 #include <config.h>
14 #include <version.h>
15
16 #include "tex2lyx.h"
17
18 #include "Context.h"
19 #include "Encoding.h"
20 #include "Layout.h"
21 #include "LayoutFile.h"
22 #include "LayoutModuleList.h"
23 #include "ModuleList.h"
24 #include "Preamble.h"
25 #include "TextClass.h"
26
27 #include "support/convert.h"
28 #include "support/debug.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/filetools.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/Messages.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36 #include "support/Systemcall.h"
37
38 #include <cstdlib>
39 #include <iostream>
40 #include <string>
41 #include <sstream>
42 #include <vector>
43 #include <map>
44
45 using namespace std;
46 using namespace lyx::support;
47 using namespace lyx::support::os;
48
49 namespace lyx {
50
51 namespace frontend {
52 namespace Alert {
53         void warning(docstring const & title, docstring const & message,
54                                  bool const &)
55         {
56                 LYXERR0(title);
57                 LYXERR0(message);
58         }
59 }
60 }
61
62
63 // Dummy texrow support
64 void TexRow::newline()
65 {}
66
67
68 void TexRow::newlines(int)
69 {}
70
71
72 // Dummy LyXRC support
73 class LyXRC {
74 public:
75         string icon_set;
76 } lyxrc;
77
78
79 // Dummy translation support
80 Messages messages_;
81 Messages const & getMessages(std::string const &)
82 {
83         return messages_;
84 }
85
86
87 Messages const & getGuiMessages()
88 {
89         return messages_;
90 }
91
92
93 // Keep the linker happy on Windows
94 void lyx_exit(int)
95 {}
96
97
98 string const trimSpaceAndEol(string const & a)
99 {
100         return trim(a, " \t\n\r");
101 }
102
103
104 void split(string const & s, vector<string> & result, char delim)
105 {
106         //cerr << "split 1: '" << s << "'\n";
107         istringstream is(s);
108         string t;
109         while (getline(is, t, delim))
110                 result.push_back(t);
111         //cerr << "split 2\n";
112 }
113
114
115 string join(vector<string> const & input, char const * delim)
116 {
117         ostringstream os;
118         for (size_t i = 0; i != input.size(); ++i) {
119                 if (i)
120                         os << delim;
121                 os << input[i];
122         }
123         return os.str();
124 }
125
126
127 char const * const * is_known(string const & str, char const * const * what)
128 {
129         for ( ; *what; ++what)
130                 if (str == *what)
131                         return what;
132         return 0;
133 }
134
135
136
137 // current stack of nested environments
138 vector<string> active_environments;
139
140
141 string active_environment()
142 {
143         return active_environments.empty() ? string() : active_environments.back();
144 }
145
146
147 TeX2LyXDocClass textclass;
148 CommandMap known_commands;
149 CommandMap known_environments;
150 CommandMap known_math_environments;
151 FullCommandMap possible_textclass_commands;
152 FullEnvironmentMap possible_textclass_environments;
153 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
154
155 /// used modules
156 LayoutModuleList used_modules;
157
158
159 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
160 {
161         // We have to handle the following cases:
162         // definition                      o1    o2    invocation result
163         // \newcommand{\foo}{bar}          ""    false \foo       bar
164         // \newcommand{\foo}[1]{bar #1}    "[1]" false \foo{x}    bar x
165         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo       bar
166         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo[x]    bar x
167         // \newcommand{\foo}[1][x]{bar #1} "[1]" true  \foo[x]    bar x
168         unsigned int nargs = 0;
169         string const opt1 = rtrim(ltrim(o1, "["), "]");
170         if (isStrUnsignedInt(opt1)) {
171                 // The command has arguments
172                 nargs = convert<unsigned int>(opt1);
173                 if (nargs > 0 && o2) {
174                         // The first argument is optional
175                         arguments.push_back(optional);
176                         --nargs;
177                 }
178         }
179         for (unsigned int i = 0; i < nargs; ++i)
180                 arguments.push_back(required);
181 }
182
183
184 void add_known_command(string const & command, string const & o1,
185                        bool o2, docstring const & definition)
186 {
187         vector<ArgumentType> arguments;
188         convertArgs(o1, o2, arguments);
189         known_commands[command] = arguments;
190         if (!definition.empty())
191                 possible_textclass_commands[command] =
192                         FullCommand(arguments, definition);
193 }
194
195
196 void add_known_environment(string const & environment, string const & o1,
197                            bool o2, docstring const & beg, docstring const &end)
198 {
199         vector<ArgumentType> arguments;
200         convertArgs(o1, o2, arguments);
201         known_environments[environment] = arguments;
202         if (!beg.empty() || ! end.empty())
203                 possible_textclass_environments[environment] =
204                         FullEnvironment(arguments, beg, end);
205 }
206
207
208 Layout const * findLayoutWithoutModule(TextClass const & textclass,
209                                        string const & name, bool command)
210 {
211         DocumentClass::const_iterator it = textclass.begin();
212         DocumentClass::const_iterator en = textclass.end();
213         for (; it != en; ++it) {
214                 if (it->latexname() == name &&
215                     ((command && it->isCommand()) || (!command && it->isEnvironment())))
216                         return &*it;
217         }
218         return 0;
219 }
220
221
222 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
223                                                  string const & name, bool command)
224 {
225         DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
226         DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
227         for (; it != en; ++it) {
228                 if (it->second.latexname() == name &&
229                     ((command && it->second.latextype() == InsetLayout::COMMAND) ||
230                      (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
231                         return &(it->second);
232         }
233         return 0;
234 }
235
236
237 bool checkModule(string const & name, bool command)
238 {
239         // Cache to avoid slowdown by repated searches
240         static set<string> failed[2];
241
242         // Only add the module if the command was actually defined in the LyX preamble
243         if (command) {
244                 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
245                         return false;
246         } else {
247                 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
248                         return false;
249         }
250         if (failed[command].find(name) != failed[command].end())
251                 return false;
252
253         // Create list of dummy document classes if not already done.
254         // This is needed since a module cannot be read on its own, only as
255         // part of a document class.
256         LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
257         typedef map<string, DocumentClass *> ModuleMap;
258         static ModuleMap modules;
259         static bool init = true;
260         if (init) {
261                 baseClass.load();
262                 DocumentClassBundle & bundle = DocumentClassBundle::get();
263                 LyXModuleList::const_iterator const end = theModuleList.end();
264                 LyXModuleList::const_iterator it = theModuleList.begin();
265                 for (; it != end; it++) {
266                         string const module = it->getID();
267                         LayoutModuleList m;
268                         // FIXME this excludes all modules that depend on another one
269                         if (!m.moduleCanBeAdded(module, &baseClass))
270                                 continue;
271                         m.push_back(module);
272                         modules[module] = &bundle.makeDocumentClass(baseClass, m);
273                 }
274                 init = false;
275         }
276
277         // Try to find a module that defines the command.
278         // Only add it if the definition can be found in the preamble of the
279         // style that corresponds to the command. This is a heuristic and
280         // different from the way how we parse the builtin commands of the
281         // text class (in that case we only compare the name), but it is
282         // needed since it is not unlikely that two different modules define a
283         // command with the same name.
284         ModuleMap::iterator const end = modules.end();
285         for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
286                 string const module = it->first;
287                 if (!used_modules.moduleCanBeAdded(module, &baseClass))
288                         continue;
289                 if (findLayoutWithoutModule(textclass, name, command))
290                         continue;
291                 if (findInsetLayoutWithoutModule(textclass, name, command))
292                         continue;
293                 DocumentClass const * c = it->second;
294                 Layout const * layout = findLayoutWithoutModule(*c, name, command);
295                 InsetLayout const * insetlayout = layout ? 0 :
296                         findInsetLayoutWithoutModule(*c, name, command);
297                 docstring preamble;
298                 if (layout)
299                         preamble = layout->preamble();
300                 else if (insetlayout)
301                         preamble = insetlayout->preamble();
302                 if (preamble.empty())
303                         continue;
304                 bool add = false;
305                 if (command) {
306                         FullCommand const & cmd =
307                                 possible_textclass_commands['\\' + name];
308                         if (preamble.find(cmd.def) != docstring::npos)
309                                 add = true;
310                 } else {
311                         FullEnvironment const & env =
312                                 possible_textclass_environments[name];
313                         if (preamble.find(env.beg) != docstring::npos &&
314                             preamble.find(env.end) != docstring::npos)
315                                 add = true;
316                 }
317                 if (add) {
318                         FileName layout_file = libFileSearch("layouts", module, "module");
319                         if (textclass.read(layout_file, TextClass::MODULE)) {
320                                 used_modules.push_back(module);
321                                 // speed up further searches:
322                                 // the module does not need to be checked anymore.
323                                 modules.erase(it);
324                                 return true;
325                         }
326                 }
327         }
328         failed[command].insert(name);
329         return false;
330 }
331
332
333 bool noweb_mode = false;
334 bool pdflatex = false;
335 bool xetex = false;
336 bool roundtrip = false;
337
338
339 namespace {
340
341
342 /*!
343  * Read one command definition from the syntax file
344  */
345 void read_command(Parser & p, string command, CommandMap & commands)
346 {
347         if (p.next_token().asInput() == "*") {
348                 p.get_token();
349                 command += '*';
350         }
351         vector<ArgumentType> arguments;
352         while (p.next_token().cat() == catBegin ||
353                p.next_token().asInput() == "[") {
354                 if (p.next_token().cat() == catBegin) {
355                         string const arg = p.getArg('{', '}');
356                         if (arg == "translate")
357                                 arguments.push_back(required);
358                         else if (arg == "item")
359                                 arguments.push_back(item);
360                         else
361                                 arguments.push_back(verbatim);
362                 } else {
363                         p.getArg('[', ']');
364                         arguments.push_back(optional);
365                 }
366         }
367         commands[command] = arguments;
368 }
369
370
371 /*!
372  * Read a class of environments from the syntax file
373  */
374 void read_environment(Parser & p, string const & begin,
375                       CommandMap & environments)
376 {
377         string environment;
378         while (p.good()) {
379                 Token const & t = p.get_token();
380                 if (t.cat() == catLetter)
381                         environment += t.asInput();
382                 else if (!environment.empty()) {
383                         p.putback();
384                         read_command(p, environment, environments);
385                         environment.erase();
386                 }
387                 if (t.cat() == catEscape && t.asInput() == "\\end") {
388                         string const end = p.getArg('{', '}');
389                         if (end == begin)
390                                 return;
391                 }
392         }
393 }
394
395
396 /*!
397  * Read a list of TeX commands from a reLyX compatible syntax file.
398  * Since this list is used after all commands that have a LyX counterpart
399  * are handled, it does not matter that the "syntax.default" file
400  * has almost all of them listed. For the same reason the reLyX-specific
401  * reLyXre environment is ignored.
402  */
403 void read_syntaxfile(FileName const & file_name)
404 {
405         ifdocstream is(file_name.toFilesystemEncoding().c_str());
406         if (!is.good()) {
407                 cerr << "Could not open syntax file \"" << file_name
408                      << "\" for reading." << endl;
409                 exit(2);
410         }
411         // We can use our TeX parser, since the syntax of the layout file is
412         // modeled after TeX.
413         // Unknown tokens are just silently ignored, this helps us to skip some
414         // reLyX specific things.
415         Parser p(is);
416         while (p.good()) {
417                 Token const & t = p.get_token();
418                 if (t.cat() == catEscape) {
419                         string const command = t.asInput();
420                         if (command == "\\begin") {
421                                 string const name = p.getArg('{', '}');
422                                 if (name == "environments" || name == "reLyXre")
423                                         // We understand "reLyXre", but it is
424                                         // not as powerful as "environments".
425                                         read_environment(p, name,
426                                                 known_environments);
427                                 else if (name == "mathenvironments")
428                                         read_environment(p, name,
429                                                 known_math_environments);
430                         } else {
431                                 read_command(p, command, known_commands);
432                         }
433                 }
434         }
435 }
436
437
438 string documentclass;
439 string default_encoding;
440 string syntaxfile;
441 bool overwrite_files = false;
442 int error_code = 0;
443
444 /// return the number of arguments consumed
445 typedef int (*cmd_helper)(string const &, string const &);
446
447
448 int parse_help(string const &, string const &)
449 {
450         cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
451                 "Options:\n"
452                 "\t-c textclass       Declare the textclass.\n"
453                 "\t-e encoding        Set the default encoding (latex name).\n"
454                 "\t-f                 Force overwrite of .lyx files.\n"
455                 "\t-help              Print this message and quit.\n"
456                 "\t-n                 translate a noweb (aka literate programming) file.\n"
457                 "\t-roundtrip         re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
458                 "\t-s syntaxfile      read additional syntax file.\n"
459                 "\t-sysdir SYSDIR     Set system directory to SYSDIR.\n"
460                 "\t                   Default: " << package().system_support() << "\n"
461                 "\t-userdir USERDIR   Set user directory to USERDIR.\n"
462                 "\t                   Default: " << package().user_support() << "\n"
463                 "\t-version           Summarize version and build info.\n"
464                 "Paths:\n"
465                 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
466                 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
467                 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
468                 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
469                 "Check the tex2lyx man page for more details."
470              << endl;
471         exit(error_code);
472 }
473
474
475 int parse_version(string const &, string const &)
476 {
477         lyxerr << "tex2lyx " << lyx_version
478                << " (" << lyx_release_date << ")" << endl;
479         lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
480
481         lyxerr << lyx_version_info << endl;
482         exit(error_code);
483 }
484
485
486 void error_message(string const & message)
487 {
488         cerr << "tex2lyx: " << message << "\n\n";
489         error_code = 1;
490         parse_help(string(), string());
491 }
492
493
494 int parse_class(string const & arg, string const &)
495 {
496         if (arg.empty())
497                 error_message("Missing textclass string after -c switch");
498         documentclass = arg;
499         return 1;
500 }
501
502
503 int parse_encoding(string const & arg, string const &)
504 {
505         if (arg.empty())
506                 error_message("Missing encoding string after -e switch");
507         default_encoding = arg;
508         return 1;
509 }
510
511
512 int parse_syntaxfile(string const & arg, string const &)
513 {
514         if (arg.empty())
515                 error_message("Missing syntaxfile string after -s switch");
516         syntaxfile = internal_path(arg);
517         return 1;
518 }
519
520
521 // Filled with the command line arguments "foo" of "-sysdir foo" or
522 // "-userdir foo".
523 string cl_system_support;
524 string cl_user_support;
525
526
527 int parse_sysdir(string const & arg, string const &)
528 {
529         if (arg.empty())
530                 error_message("Missing directory for -sysdir switch");
531         cl_system_support = internal_path(arg);
532         return 1;
533 }
534
535
536 int parse_userdir(string const & arg, string const &)
537 {
538         if (arg.empty())
539                 error_message("Missing directory for -userdir switch");
540         cl_user_support = internal_path(arg);
541         return 1;
542 }
543
544
545 int parse_force(string const &, string const &)
546 {
547         overwrite_files = true;
548         return 0;
549 }
550
551
552 int parse_noweb(string const &, string const &)
553 {
554         noweb_mode = true;
555         return 0;
556 }
557
558
559 int parse_roundtrip(string const &, string const &)
560 {
561         roundtrip = true;
562         return 0;
563 }
564
565
566 void easyParse(int & argc, char * argv[])
567 {
568         map<string, cmd_helper> cmdmap;
569
570         cmdmap["-h"] = parse_help;
571         cmdmap["-help"] = parse_help;
572         cmdmap["--help"] = parse_help;
573         cmdmap["-v"] = parse_version;
574         cmdmap["-version"] = parse_version;
575         cmdmap["--version"] = parse_version;
576         cmdmap["-c"] = parse_class;
577         cmdmap["-e"] = parse_encoding;
578         cmdmap["-f"] = parse_force;
579         cmdmap["-s"] = parse_syntaxfile;
580         cmdmap["-n"] = parse_noweb;
581         cmdmap["-sysdir"] = parse_sysdir;
582         cmdmap["-userdir"] = parse_userdir;
583         cmdmap["-roundtrip"] = parse_roundtrip;
584
585         for (int i = 1; i < argc; ++i) {
586                 map<string, cmd_helper>::const_iterator it
587                         = cmdmap.find(argv[i]);
588
589                 // don't complain if not found - may be parsed later
590                 if (it == cmdmap.end()) {
591                         if (argv[i][0] == '-')
592                                 error_message(string("Unknown option `") + argv[i] + "'.");
593                         else
594                                 continue;
595                 }
596
597                 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
598                 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
599
600                 int const remove = 1 + it->second(arg, arg2);
601
602                 // Now, remove used arguments by shifting
603                 // the following ones remove places down.
604                 os::remove_internal_args(i, remove);
605                 argc -= remove;
606                 for (int j = i; j < argc; ++j)
607                         argv[j] = argv[j + remove];
608                 --i;
609         }
610 }
611
612
613 // path of the first parsed file
614 string masterFilePath;
615 // path of the currently parsed file
616 string parentFilePath;
617
618 } // anonymous namespace
619
620
621 string getMasterFilePath()
622 {
623         return masterFilePath;
624 }
625
626 string getParentFilePath()
627 {
628         return parentFilePath;
629 }
630
631
632 namespace {
633
634 /*!
635  *  Reads tex input from \a is and writes lyx output to \a os.
636  *  Uses some common settings for the preamble, so this should only
637  *  be used more than once for included documents.
638  *  Caution: Overwrites the existing preamble settings if the new document
639  *  contains a preamble.
640  *  You must ensure that \p parentFilePath is properly set before calling
641  *  this function!
642  */
643 bool tex2lyx(idocstream & is, ostream & os, string encoding)
644 {
645         // Set a sensible default encoding.
646         // This is used until an encoding command is found.
647         // For child documents use the encoding of the master, else latin1,
648         // since latin1 does not cause an iconv error if the actual encoding
649         // is different (bug 7509).
650         if (encoding.empty()) {
651                 if (preamble.inputencoding() == "auto")
652                         encoding = "latin1";
653                 else
654                         encoding = preamble.inputencoding();
655         }
656
657         Parser p(is);
658         p.setEncoding(encoding);
659         //p.dump();
660
661         preamble.parse(p, documentclass, textclass);
662
663         active_environments.push_back("document");
664         Context context(true, textclass);
665         stringstream ss;
666         parse_text(p, ss, FLAG_END, true, context);
667         if (Context::empty)
668                 // Empty document body. LyX needs at least one paragraph.
669                 context.check_layout(ss);
670         context.check_end_layout(ss);
671         ss << "\n\\end_body\n\\end_document\n";
672         active_environments.pop_back();
673
674         // We know the used modules only after parsing the full text
675         if (!used_modules.empty()) {
676                 LayoutModuleList::const_iterator const end = used_modules.end();
677                 LayoutModuleList::const_iterator it = used_modules.begin();
678                 for (; it != end; it++)
679                         preamble.addModule(*it);
680         }
681         if (!preamble.writeLyXHeader(os)) {
682                 cerr << "Could write LyX file header." << endl;
683                 return false;
684         }
685
686         ss.seekg(0);
687         os << ss.str();
688 #ifdef TEST_PARSER
689         p.reset();
690         ofdocstream parsertest("parsertest.tex");
691         while (p.good())
692                 parsertest << p.get_token().asInput();
693         // <origfile> and parsertest.tex should now have identical content
694 #endif
695         return true;
696 }
697
698
699 /// convert TeX from \p infilename to LyX and write it to \p os
700 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
701 {
702         ifdocstream is;
703         // forbid buffering on this stream
704         is.rdbuf()->pubsetbuf(0,0);
705         is.open(infilename.toFilesystemEncoding().c_str());
706         if (!is.good()) {
707                 cerr << "Could not open input file \"" << infilename
708                      << "\" for reading." << endl;
709                 return false;
710         }
711         string const oldParentFilePath = parentFilePath;
712         parentFilePath = onlyPath(infilename.absFileName());
713         bool retval = tex2lyx(is, os, encoding);
714         parentFilePath = oldParentFilePath;
715         return retval;
716 }
717
718 } // anonymous namespace
719
720
721 bool tex2lyx(string const & infilename, FileName const & outfilename, 
722              string const & encoding)
723 {
724         if (outfilename.isReadableFile()) {
725                 if (overwrite_files) {
726                         cerr << "Overwriting existing file "
727                              << outfilename << endl;
728                 } else {
729                         cerr << "Not overwriting existing file "
730                              << outfilename << endl;
731                         return false;
732                 }
733         } else {
734                 cerr << "Creating file " << outfilename << endl;
735         }
736         ofstream os(outfilename.toFilesystemEncoding().c_str());
737         if (!os.good()) {
738                 cerr << "Could not open output file \"" << outfilename
739                      << "\" for writing." << endl;
740                 return false;
741         }
742 #ifdef FILEDEBUG
743         cerr << "Input file: " << infilename << "\n";
744         cerr << "Output file: " << outfilename << "\n";
745 #endif
746         return tex2lyx(FileName(infilename), os, encoding);
747 }
748
749
750 bool tex2tex(string const & infilename, FileName const & outfilename,
751              string const & encoding)
752 {
753         if (!tex2lyx(infilename, outfilename, encoding))
754                 return false;
755         string command = quoteName(package().lyx_binary().toFilesystemEncoding());
756         if (overwrite_files)
757                 command += " -f main";
758         else
759                 command += " -f none";
760         if (pdflatex)
761                 command += " -e pdflatex ";
762         else
763                 command += " -e latex ";
764         command += quoteName(outfilename.toFilesystemEncoding());
765         Systemcall one;
766         if (one.startscript(Systemcall::Wait, command) == 0)
767                 return true;
768         cerr << "Error: Running '" << command << "' failed." << endl;
769         return false;
770 }
771
772 } // namespace lyx
773
774
775 int main(int argc, char * argv[])
776 {
777         using namespace lyx;
778
779         //setlocale(LC_CTYPE, "");
780
781         lyxerr.setStream(cerr);
782
783         os::init(argc, argv);
784
785         try {
786                 init_package(internal_path(os::utf8_argv(0)), string(), string());
787         } catch (ExceptionMessage const & message) {
788                 cerr << to_utf8(message.title_) << ":\n"
789                      << to_utf8(message.details_) << endl;
790                 if (message.type_ == ErrorException)
791                         return EXIT_FAILURE;
792         }
793
794         easyParse(argc, argv);
795
796         if (argc <= 1) 
797                 error_message("Not enough arguments.");
798
799         try {
800                 init_package(internal_path(os::utf8_argv(0)),
801                              cl_system_support, cl_user_support);
802         } catch (ExceptionMessage const & message) {
803                 cerr << to_utf8(message.title_) << ":\n"
804                      << to_utf8(message.details_) << endl;
805                 if (message.type_ == ErrorException)
806                         return EXIT_FAILURE;
807         }
808
809         // Now every known option is parsed. Look for input and output
810         // file name (the latter is optional).
811         string infilename = internal_path(os::utf8_argv(1));
812         infilename = makeAbsPath(infilename).absFileName();
813
814         string outfilename;
815         if (roundtrip) {
816                 if (argc > 2) {
817                         // Do not allow a user supplied output filename
818                         // (otherwise it could easily happen that LyX would
819                         // overwrite the original .tex file)
820                         cerr << "Error: output filename must not be given in roundtrip mode."
821                              << endl;
822                         return EXIT_FAILURE;
823                 }
824                 outfilename = changeExtension(infilename, ".lyx.lyx");
825         } else if (argc > 2) {
826                 outfilename = internal_path(os::utf8_argv(2));
827                 if (outfilename != "-")
828                         outfilename = makeAbsPath(outfilename).absFileName();
829         } else
830                 outfilename = changeExtension(infilename, ".lyx");
831
832         // Read the syntax tables
833         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
834         if (system_syntaxfile.empty()) {
835                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
836                 return EXIT_FAILURE;
837         }
838         read_syntaxfile(system_syntaxfile);
839         if (!syntaxfile.empty())
840                 read_syntaxfile(makeAbsPath(syntaxfile));
841
842         // Read the encodings table.
843         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
844         if (symbols_path.empty()) {
845                 cerr << "Error: Could not find file \"unicodesymbols\"." 
846                      << endl;
847                 return EXIT_FAILURE;
848         }
849         FileName const enc_path = libFileSearch(string(), "encodings");
850         if (enc_path.empty()) {
851                 cerr << "Error: Could not find file \"encodings\"." 
852                      << endl;
853                 return EXIT_FAILURE;
854         }
855         encodings.read(enc_path, symbols_path);
856         if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
857                 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
858
859         // Load the layouts
860         LayoutFileList::get().read();
861         //...and the modules
862         theModuleList.read();
863
864         // The real work now.
865         masterFilePath = onlyPath(infilename);
866         parentFilePath = masterFilePath;
867         if (outfilename == "-") {
868                 if (tex2lyx(FileName(infilename), cout, default_encoding))
869                         return EXIT_SUCCESS;
870         } else if (roundtrip) {
871                 if (tex2tex(infilename, FileName(outfilename), default_encoding))
872                         return EXIT_SUCCESS;
873         } else {
874                 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
875                         return EXIT_SUCCESS;
876         }
877         return EXIT_FAILURE;
878 }
879
880 // }])