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