]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
tex2lyx : Also allow -h and -v command-line options, manpage update.
[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["-h"] = parse_help;
580         cmdmap["-help"] = parse_help;
581         cmdmap["--help"] = parse_help;
582         cmdmap["-v"] = parse_version;
583         cmdmap["-version"] = parse_version;
584         cmdmap["--version"] = parse_version;
585         cmdmap["-c"] = parse_class;
586         cmdmap["-e"] = parse_encoding;
587         cmdmap["-f"] = parse_force;
588         cmdmap["-s"] = parse_syntaxfile;
589         cmdmap["-n"] = parse_noweb;
590         cmdmap["-sysdir"] = parse_sysdir;
591         cmdmap["-userdir"] = parse_userdir;
592         cmdmap["-roundtrip"] = parse_roundtrip;
593
594         for (int i = 1; i < argc; ++i) {
595                 map<string, cmd_helper>::const_iterator it
596                         = cmdmap.find(argv[i]);
597
598                 // don't complain if not found - may be parsed later
599                 if (it == cmdmap.end()) {
600                         if (argv[i][0] == '-')
601                                 error_message(string("Unknown option `") + argv[i] + "'.");
602                         else
603                                 continue;
604                 }
605
606                 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
607                 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
608
609                 int const remove = 1 + it->second(arg, arg2);
610
611                 // Now, remove used arguments by shifting
612                 // the following ones remove places down.
613                 os::remove_internal_args(i, remove);
614                 argc -= remove;
615                 for (int j = i; j < argc; ++j)
616                         argv[j] = argv[j + remove];
617                 --i;
618         }
619 }
620
621
622 // path of the first parsed file
623 string masterFilePath;
624 // path of the currently parsed file
625 string parentFilePath;
626
627 } // anonymous namespace
628
629
630 string getMasterFilePath()
631 {
632         return masterFilePath;
633 }
634
635 string getParentFilePath()
636 {
637         return parentFilePath;
638 }
639
640
641 namespace {
642
643 /*!
644  *  Reads tex input from \a is and writes lyx output to \a os.
645  *  Uses some common settings for the preamble, so this should only
646  *  be used more than once for included documents.
647  *  Caution: Overwrites the existing preamble settings if the new document
648  *  contains a preamble.
649  *  You must ensure that \p parentFilePath is properly set before calling
650  *  this function!
651  */
652 void tex2lyx(idocstream & is, ostream & os, string encoding)
653 {
654         // Set a sensible default encoding.
655         // This is used until an encoding command is found.
656         // For child documents use the encoding of the master, else latin1,
657         // since latin1 does not cause an iconv error if the actual encoding
658         // is different (bug 7509).
659         if (encoding.empty()) {
660                 if (h_inputencoding == "auto")
661                         encoding = "latin1";
662                 else
663                         encoding = h_inputencoding;
664         }
665
666         Parser p(is);
667         p.setEncoding(encoding);
668         //p.dump();
669
670         ostringstream ps;
671         parse_preamble(p, ps, documentclass, textclass);
672
673         active_environments.push_back("document");
674         Context context(true, textclass);
675         stringstream ss;
676         parse_text(p, ss, FLAG_END, true, context);
677         if (Context::empty)
678                 // Empty document body. LyX needs at least one paragraph.
679                 context.check_layout(ss);
680         context.check_end_layout(ss);
681         ss << "\n\\end_body\n\\end_document\n";
682         active_environments.pop_back();
683
684         // We know the used modules only after parsing the full text
685         ostringstream ms;
686         if (!used_modules.empty()) {
687                 ms << "\\begin_modules\n";
688                 LayoutModuleList::const_iterator const end = used_modules.end();
689                 LayoutModuleList::const_iterator it = used_modules.begin();
690                 for (; it != end; it++)
691                         ms << *it << '\n';
692                 ms << "\\end_modules\n";
693         }
694         os << subst(ps.str(), modules_placeholder, ms.str());
695
696         ss.seekg(0);
697         os << ss.str();
698 #ifdef TEST_PARSER
699         p.reset();
700         ofdocstream parsertest("parsertest.tex");
701         while (p.good())
702                 parsertest << p.get_token().asInput();
703         // <origfile> and parsertest.tex should now have identical content
704 #endif
705 }
706
707
708 /// convert TeX from \p infilename to LyX and write it to \p os
709 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
710 {
711         ifdocstream is;
712         // forbid buffering on this stream
713         is.rdbuf()->pubsetbuf(0,0);
714         is.open(infilename.toFilesystemEncoding().c_str());
715         if (!is.good()) {
716                 cerr << "Could not open input file \"" << infilename
717                      << "\" for reading." << endl;
718                 return false;
719         }
720         string const oldParentFilePath = parentFilePath;
721         parentFilePath = onlyPath(infilename.absFileName());
722         tex2lyx(is, os, encoding);
723         parentFilePath = oldParentFilePath;
724         return true;
725 }
726
727 } // anonymous namespace
728
729
730 bool tex2lyx(string const & infilename, FileName const & outfilename, 
731              string const & encoding)
732 {
733         if (outfilename.isReadableFile()) {
734                 if (overwrite_files) {
735                         cerr << "Overwriting existing file "
736                              << outfilename << endl;
737                 } else {
738                         cerr << "Not overwriting existing file "
739                              << outfilename << endl;
740                         return false;
741                 }
742         } else {
743                 cerr << "Creating file " << outfilename << endl;
744         }
745         ofstream os(outfilename.toFilesystemEncoding().c_str());
746         if (!os.good()) {
747                 cerr << "Could not open output file \"" << outfilename
748                      << "\" for writing." << endl;
749                 return false;
750         }
751 #ifdef FILEDEBUG
752         cerr << "Input file: " << infilename << "\n";
753         cerr << "Output file: " << outfilename << "\n";
754 #endif
755         return tex2lyx(FileName(infilename), os, encoding);
756 }
757
758
759 bool tex2tex(string const & infilename, FileName const & outfilename,
760              string const & encoding)
761 {
762         if (!tex2lyx(infilename, outfilename, encoding))
763                 return false;
764         string command = quoteName(package().lyx_binary().toFilesystemEncoding());
765         if (overwrite_files)
766                 command += " -f main";
767         else
768                 command += " -f none";
769         if (pdflatex)
770                 command += " -e pdflatex ";
771         else
772                 command += " -e latex ";
773         command += quoteName(outfilename.toFilesystemEncoding());
774         Systemcall one;
775         if (one.startscript(Systemcall::Wait, command) == 0)
776                 return true;
777         cerr << "Error: Running '" << command << "' failed." << endl;
778         return false;
779 }
780
781 } // namespace lyx
782
783
784 int main(int argc, char * argv[])
785 {
786         using namespace lyx;
787
788         //setlocale(LC_CTYPE, "");
789
790         lyxerr.setStream(cerr);
791
792         os::init(argc, argv);
793
794         try {
795                 init_package(internal_path(os::utf8_argv(0)), string(), string());
796         } catch (ExceptionMessage const & message) {
797                 cerr << to_utf8(message.title_) << ":\n"
798                      << to_utf8(message.details_) << endl;
799                 if (message.type_ == ErrorException)
800                         return EXIT_FAILURE;
801         }
802
803         easyParse(argc, argv);
804
805         if (argc <= 1) 
806                 error_message("Not enough arguments.");
807
808         try {
809                 init_package(internal_path(os::utf8_argv(0)),
810                              cl_system_support, cl_user_support);
811         } catch (ExceptionMessage const & message) {
812                 cerr << to_utf8(message.title_) << ":\n"
813                      << to_utf8(message.details_) << endl;
814                 if (message.type_ == ErrorException)
815                         return EXIT_FAILURE;
816         }
817
818         // Now every known option is parsed. Look for input and output
819         // file name (the latter is optional).
820         string infilename = internal_path(os::utf8_argv(1));
821         infilename = makeAbsPath(infilename).absFileName();
822
823         string outfilename;
824         if (roundtrip) {
825                 if (argc > 2) {
826                         // Do not allow a user supplied output filename
827                         // (otherwise it could easily happen that LyX would
828                         // overwrite the original .tex file)
829                         cerr << "Error: output filename must not be given in roundtrip mode."
830                              << endl;
831                         return EXIT_FAILURE;
832                 }
833                 outfilename = changeExtension(infilename, ".lyx.lyx");
834         } else if (argc > 2) {
835                 outfilename = internal_path(os::utf8_argv(2));
836                 if (outfilename != "-")
837                         outfilename = makeAbsPath(outfilename).absFileName();
838         } else
839                 outfilename = changeExtension(infilename, ".lyx");
840
841         // Read the syntax tables
842         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
843         if (system_syntaxfile.empty()) {
844                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
845                 return EXIT_FAILURE;
846         }
847         read_syntaxfile(system_syntaxfile);
848         if (!syntaxfile.empty())
849                 read_syntaxfile(makeAbsPath(syntaxfile));
850
851         // Read the encodings table.
852         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
853         if (symbols_path.empty()) {
854                 cerr << "Error: Could not find file \"unicodesymbols\"." 
855                      << endl;
856                 return EXIT_FAILURE;
857         }
858         FileName const enc_path = libFileSearch(string(), "encodings");
859         if (enc_path.empty()) {
860                 cerr << "Error: Could not find file \"encodings\"." 
861                      << endl;
862                 return EXIT_FAILURE;
863         }
864         encodings.read(enc_path, symbols_path);
865         if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
866                 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
867
868         // Load the layouts
869         LayoutFileList::get().read();
870         //...and the modules
871         theModuleList.read();
872
873         // The real work now.
874         masterFilePath = onlyPath(infilename);
875         parentFilePath = masterFilePath;
876         if (outfilename == "-") {
877                 if (tex2lyx(FileName(infilename), cout, default_encoding))
878                         return EXIT_SUCCESS;
879         } else if (roundtrip) {
880                 if (tex2tex(infilename, FileName(outfilename), default_encoding))
881                         return EXIT_SUCCESS;
882         } else {
883                 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
884                         return EXIT_SUCCESS;
885         }
886         return EXIT_FAILURE;
887 }
888
889 // }])