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