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