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