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