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