]> git.lyx.org Git - features.git/blob - src/tex2lyx/tex2lyx.cpp
Add -skipchildren command line switch (bug #4435)
[features.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 is_nonCJKJapanese = 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 == "group")
359                                 arguments.push_back(req_group);
360                         else if (arg == "item")
361                                 arguments.push_back(item);
362                         else if (arg == "displaymath")
363                                 arguments.push_back(displaymath);
364                         else
365                                 arguments.push_back(verbatim);
366                 } else {
367                         string const arg = p.getArg('[', ']');
368                         if (arg == "group")
369                                 arguments.push_back(opt_group);
370                         else
371                                 arguments.push_back(optional);
372                 }
373         }
374         commands[command] = arguments;
375 }
376
377
378 /*!
379  * Read a class of environments from the syntax file
380  */
381 void read_environment(Parser & p, string const & begin,
382                       CommandMap & environments)
383 {
384         string environment;
385         while (p.good()) {
386                 Token const & t = p.get_token();
387                 if (t.cat() == catLetter)
388                         environment += t.asInput();
389                 else if (!environment.empty()) {
390                         p.putback();
391                         read_command(p, environment, environments);
392                         environment.erase();
393                 }
394                 if (t.cat() == catEscape && t.asInput() == "\\end") {
395                         string const end = p.getArg('{', '}');
396                         if (end == begin)
397                                 return;
398                 }
399         }
400 }
401
402
403 /*!
404  * Read a list of TeX commands from a reLyX compatible syntax file.
405  * Since this list is used after all commands that have a LyX counterpart
406  * are handled, it does not matter that the "syntax.default" file
407  * has almost all of them listed. For the same reason the reLyX-specific
408  * reLyXre environment is ignored.
409  */
410 void read_syntaxfile(FileName const & file_name)
411 {
412         ifdocstream is(file_name.toFilesystemEncoding().c_str());
413         if (!is.good()) {
414                 cerr << "Could not open syntax file \"" << file_name
415                      << "\" for reading." << endl;
416                 exit(2);
417         }
418         // We can use our TeX parser, since the syntax of the layout file is
419         // modeled after TeX.
420         // Unknown tokens are just silently ignored, this helps us to skip some
421         // reLyX specific things.
422         Parser p(is);
423         while (p.good()) {
424                 Token const & t = p.get_token();
425                 if (t.cat() == catEscape) {
426                         string const command = t.asInput();
427                         if (command == "\\begin") {
428                                 string const name = p.getArg('{', '}');
429                                 if (name == "environments" || name == "reLyXre")
430                                         // We understand "reLyXre", but it is
431                                         // not as powerful as "environments".
432                                         read_environment(p, name,
433                                                 known_environments);
434                                 else if (name == "mathenvironments")
435                                         read_environment(p, name,
436                                                 known_math_environments);
437                         } else {
438                                 read_command(p, command, known_commands);
439                         }
440                 }
441         }
442 }
443
444
445 string documentclass;
446 string default_encoding;
447 string syntaxfile;
448 bool copy_files = false;
449 bool overwrite_files = false;
450 bool skip_children = 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-copyfiles         Copy all included files to the directory of outfile.lyx.\n"
463                 "\t-e encoding        Set the default encoding (latex name).\n"
464                 "\t-f                 Force overwrite of .lyx files.\n"
465                 "\t-help              Print this message and quit.\n"
466                 "\t-n                 translate a noweb (aka literate programming) file.\n"
467                 "\t-skipchildren      Do not translate included child documents.\n"
468                 "\t-roundtrip         re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
469                 "\t-s syntaxfile      read additional syntax file.\n"
470                 "\t-sysdir SYSDIR     Set system directory to SYSDIR.\n"
471                 "\t                   Default: " << package().system_support() << "\n"
472                 "\t-userdir USERDIR   Set user directory to USERDIR.\n"
473                 "\t                   Default: " << package().user_support() << "\n"
474                 "\t-version           Summarize version and build info.\n"
475                 "Paths:\n"
476                 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
477                 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
478                 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
479                 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
480                 "Check the tex2lyx man page for more details."
481              << endl;
482         exit(error_code);
483 }
484
485
486 int parse_version(string const &, string const &)
487 {
488         lyxerr << "tex2lyx " << lyx_version
489                << " (" << lyx_release_date << ")" << endl;
490         lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
491
492         lyxerr << lyx_version_info << endl;
493         exit(error_code);
494 }
495
496
497 void error_message(string const & message)
498 {
499         cerr << "tex2lyx: " << message << "\n\n";
500         error_code = 1;
501         parse_help(string(), string());
502 }
503
504
505 int parse_class(string const & arg, string const &)
506 {
507         if (arg.empty())
508                 error_message("Missing textclass string after -c switch");
509         documentclass = arg;
510         return 1;
511 }
512
513
514 int parse_encoding(string const & arg, string const &)
515 {
516         if (arg.empty())
517                 error_message("Missing encoding string after -e switch");
518         default_encoding = arg;
519         return 1;
520 }
521
522
523 int parse_syntaxfile(string const & arg, string const &)
524 {
525         if (arg.empty())
526                 error_message("Missing syntaxfile string after -s switch");
527         syntaxfile = internal_path(arg);
528         return 1;
529 }
530
531
532 // Filled with the command line arguments "foo" of "-sysdir foo" or
533 // "-userdir foo".
534 string cl_system_support;
535 string cl_user_support;
536
537
538 int parse_sysdir(string const & arg, string const &)
539 {
540         if (arg.empty())
541                 error_message("Missing directory for -sysdir switch");
542         cl_system_support = internal_path(arg);
543         return 1;
544 }
545
546
547 int parse_userdir(string const & arg, string const &)
548 {
549         if (arg.empty())
550                 error_message("Missing directory for -userdir switch");
551         cl_user_support = internal_path(arg);
552         return 1;
553 }
554
555
556 int parse_force(string const &, string const &)
557 {
558         overwrite_files = true;
559         return 0;
560 }
561
562
563 int parse_noweb(string const &, string const &)
564 {
565         noweb_mode = true;
566         return 0;
567 }
568
569
570 int parse_skipchildren(string const &, string const &)
571 {
572         skip_children = true;
573         return 0;
574 }
575
576
577 int parse_roundtrip(string const &, string const &)
578 {
579         roundtrip = true;
580         return 0;
581 }
582
583
584 int parse_copyfiles(string const &, string const &)
585 {
586         copy_files = true;
587         return 0;
588 }
589
590
591 void easyParse(int & argc, char * argv[])
592 {
593         map<string, cmd_helper> cmdmap;
594
595         cmdmap["-h"] = parse_help;
596         cmdmap["-help"] = parse_help;
597         cmdmap["--help"] = parse_help;
598         cmdmap["-v"] = parse_version;
599         cmdmap["-version"] = parse_version;
600         cmdmap["--version"] = parse_version;
601         cmdmap["-c"] = parse_class;
602         cmdmap["-e"] = parse_encoding;
603         cmdmap["-f"] = parse_force;
604         cmdmap["-s"] = parse_syntaxfile;
605         cmdmap["-n"] = parse_noweb;
606         cmdmap["-skipchildren"] = parse_skipchildren;
607         cmdmap["-sysdir"] = parse_sysdir;
608         cmdmap["-userdir"] = parse_userdir;
609         cmdmap["-roundtrip"] = parse_roundtrip;
610         cmdmap["-copyfiles"] = parse_copyfiles;
611
612         for (int i = 1; i < argc; ++i) {
613                 map<string, cmd_helper>::const_iterator it
614                         = cmdmap.find(argv[i]);
615
616                 // don't complain if not found - may be parsed later
617                 if (it == cmdmap.end()) {
618                         if (argv[i][0] == '-')
619                                 error_message(string("Unknown option `") + argv[i] + "'.");
620                         else
621                                 continue;
622                 }
623
624                 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
625                 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
626
627                 int const remove = 1 + it->second(arg, arg2);
628
629                 // Now, remove used arguments by shifting
630                 // the following ones remove places down.
631                 os::remove_internal_args(i, remove);
632                 argc -= remove;
633                 for (int j = i; j < argc; ++j)
634                         argv[j] = argv[j + remove];
635                 --i;
636         }
637 }
638
639
640 // path of the first parsed file
641 string masterFilePathLyX;
642 string masterFilePathTeX;
643 // path of the currently parsed file
644 string parentFilePathTeX;
645
646 } // anonymous namespace
647
648
649 string getMasterFilePath(bool input)
650 {
651         return input ? masterFilePathTeX : masterFilePathLyX;
652 }
653
654 string getParentFilePath(bool input)
655 {
656         if (input)
657                 return parentFilePathTeX;
658         string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
659                                                from_utf8(parentFilePathTeX)));
660         if (rel.substr(0, 3) == "../") {
661                 // The parent is not below the master - keep the path
662                 return parentFilePathTeX;
663         }
664         return makeAbsPath(rel, masterFilePathLyX).absFileName();
665 }
666
667
668 bool copyFiles()
669 {
670         return copy_files;
671 }
672
673
674 bool overwriteFiles()
675 {
676         return overwrite_files;
677 }
678
679
680 bool skipChildren()
681 {
682         return skip_children;
683 }
684
685
686 namespace {
687
688 /*!
689  *  Reads tex input from \a is and writes lyx output to \a os.
690  *  Uses some common settings for the preamble, so this should only
691  *  be used more than once for included documents.
692  *  Caution: Overwrites the existing preamble settings if the new document
693  *  contains a preamble.
694  *  You must ensure that \p parentFilePathTeX is properly set before calling
695  *  this function!
696  */
697 bool tex2lyx(idocstream & is, ostream & os, string encoding)
698 {
699         // Set a sensible default encoding.
700         // This is used until an encoding command is found.
701         // For child documents use the encoding of the master, else latin1,
702         // since latin1 does not cause an iconv error if the actual encoding
703         // is different (bug 7509).
704         if (encoding.empty()) {
705                 if (preamble.inputencoding() == "auto")
706                         encoding = "latin1";
707                 else
708                         encoding = preamble.inputencoding();
709         }
710
711         Parser p(is);
712         p.setEncoding(encoding);
713         //p.dump();
714
715         preamble.parse(p, documentclass, textclass);
716
717         active_environments.push_back("document");
718         Context context(true, textclass);
719         stringstream ss;
720         // store the document language in the context to be able to handle the
721         // commands like \foreignlanguage and \textenglish etc.
722         context.font.language = preamble.defaultLanguage();
723         // parse the main text
724         parse_text(p, ss, FLAG_END, true, context);
725         if (Context::empty)
726                 // Empty document body. LyX needs at least one paragraph.
727                 context.check_layout(ss);
728         context.check_end_layout(ss);
729         ss << "\n\\end_body\n\\end_document\n";
730         active_environments.pop_back();
731
732         // We know the used modules only after parsing the full text
733         if (!used_modules.empty()) {
734                 LayoutModuleList::const_iterator const end = used_modules.end();
735                 LayoutModuleList::const_iterator it = used_modules.begin();
736                 for (; it != end; ++it)
737                         preamble.addModule(*it);
738         }
739         if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
740                 cerr << "Could write LyX file header." << endl;
741                 return false;
742         }
743
744         ss.seekg(0);
745         os << ss.str();
746 #ifdef TEST_PARSER
747         p.reset();
748         ofdocstream parsertest("parsertest.tex");
749         while (p.good())
750                 parsertest << p.get_token().asInput();
751         // <origfile> and parsertest.tex should now have identical content
752 #endif
753         return true;
754 }
755
756
757 /// convert TeX from \p infilename to LyX and write it to \p os
758 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
759 {
760         ifdocstream is;
761         // forbid buffering on this stream
762         is.rdbuf()->pubsetbuf(0,0);
763         is.open(infilename.toFilesystemEncoding().c_str());
764         if (!is.good()) {
765                 cerr << "Could not open input file \"" << infilename
766                      << "\" for reading." << endl;
767                 return false;
768         }
769         string const oldParentFilePath = parentFilePathTeX;
770         parentFilePathTeX = onlyPath(infilename.absFileName());
771         bool retval = tex2lyx(is, os, encoding);
772         parentFilePathTeX = oldParentFilePath;
773         return retval;
774 }
775
776 } // anonymous namespace
777
778
779 bool tex2lyx(string const & infilename, FileName const & outfilename, 
780              string const & encoding)
781 {
782         if (outfilename.isReadableFile()) {
783                 if (overwrite_files) {
784                         cerr << "Overwriting existing file "
785                              << outfilename << endl;
786                 } else {
787                         cerr << "Not overwriting existing file "
788                              << outfilename << endl;
789                         return false;
790                 }
791         } else {
792                 cerr << "Creating file " << outfilename << endl;
793         }
794         ofstream os(outfilename.toFilesystemEncoding().c_str());
795         if (!os.good()) {
796                 cerr << "Could not open output file \"" << outfilename
797                      << "\" for writing." << endl;
798                 return false;
799         }
800 #ifdef FILEDEBUG
801         cerr << "Input file: " << infilename << "\n";
802         cerr << "Output file: " << outfilename << "\n";
803 #endif
804         return tex2lyx(FileName(infilename), os, encoding);
805 }
806
807
808 bool tex2tex(string const & infilename, FileName const & outfilename,
809              string const & encoding)
810 {
811         if (!tex2lyx(infilename, outfilename, encoding))
812                 return false;
813         string command = quoteName(package().lyx_binary().toFilesystemEncoding());
814         if (overwrite_files)
815                 command += " -f main";
816         else
817                 command += " -f none";
818         if (pdflatex)
819                 command += " -e pdflatex ";
820         else if (xetex)
821                 command += " -e xetex ";
822         else
823                 command += " -e latex ";
824         command += quoteName(outfilename.toFilesystemEncoding());
825         Systemcall one;
826         if (one.startscript(Systemcall::Wait, command) == 0)
827                 return true;
828         cerr << "Error: Running '" << command << "' failed." << endl;
829         return false;
830 }
831
832 } // namespace lyx
833
834
835 int main(int argc, char * argv[])
836 {
837         using namespace lyx;
838
839         //setlocale(LC_CTYPE, "");
840
841         lyxerr.setStream(cerr);
842
843         os::init(argc, argv);
844
845         try {
846                 init_package(internal_path(os::utf8_argv(0)), string(), string());
847         } catch (ExceptionMessage const & message) {
848                 cerr << to_utf8(message.title_) << ":\n"
849                      << to_utf8(message.details_) << endl;
850                 if (message.type_ == ErrorException)
851                         return EXIT_FAILURE;
852         }
853
854         easyParse(argc, argv);
855
856         if (argc <= 1) 
857                 error_message("Not enough arguments.");
858
859         try {
860                 init_package(internal_path(os::utf8_argv(0)),
861                              cl_system_support, cl_user_support);
862         } catch (ExceptionMessage const & message) {
863                 cerr << to_utf8(message.title_) << ":\n"
864                      << to_utf8(message.details_) << endl;
865                 if (message.type_ == ErrorException)
866                         return EXIT_FAILURE;
867         }
868
869         // Now every known option is parsed. Look for input and output
870         // file name (the latter is optional).
871         string infilename = internal_path(os::utf8_argv(1));
872         infilename = makeAbsPath(infilename).absFileName();
873
874         string outfilename;
875         if (argc > 2) {
876                 outfilename = internal_path(os::utf8_argv(2));
877                 if (outfilename != "-")
878                         outfilename = makeAbsPath(outfilename).absFileName();
879                 if (roundtrip) {
880                         if (outfilename == "-") {
881                                 cerr << "Error: Writing to standard output is "
882                                         "not supported in roundtrip mode."
883                                      << endl;
884                                 return EXIT_FAILURE;
885                         }
886                         string texfilename = changeExtension(outfilename, ".tex");
887                         if (equivalent(FileName(infilename), FileName(texfilename))) {
888                                 cerr << "Error: The input file `" << infilename
889                                      << "´ would be overwritten by the TeX file exported from `"
890                                      << outfilename << "´ in roundtrip mode." << endl;
891                                 return EXIT_FAILURE;
892                         }
893                 }
894         } else if (roundtrip) {
895                 // avoid overwriting the input file
896                 outfilename = changeExtension(infilename, ".lyx.lyx");
897         } else
898                 outfilename = changeExtension(infilename, ".lyx");
899
900         // Read the syntax tables
901         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
902         if (system_syntaxfile.empty()) {
903                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
904                 return EXIT_FAILURE;
905         }
906         read_syntaxfile(system_syntaxfile);
907         if (!syntaxfile.empty())
908                 read_syntaxfile(makeAbsPath(syntaxfile));
909
910         // Read the encodings table.
911         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
912         if (symbols_path.empty()) {
913                 cerr << "Error: Could not find file \"unicodesymbols\"." 
914                      << endl;
915                 return EXIT_FAILURE;
916         }
917         FileName const enc_path = libFileSearch(string(), "encodings");
918         if (enc_path.empty()) {
919                 cerr << "Error: Could not find file \"encodings\"." 
920                      << endl;
921                 return EXIT_FAILURE;
922         }
923         encodings.read(enc_path, symbols_path);
924         if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
925                 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
926
927         // Load the layouts
928         LayoutFileList::get().read();
929         //...and the modules
930         theModuleList.read();
931
932         // The real work now.
933         masterFilePathTeX = onlyPath(infilename);
934         parentFilePathTeX = masterFilePathTeX;
935         if (outfilename == "-") {
936                 // assume same directory as input file
937                 masterFilePathLyX = masterFilePathTeX;
938                 if (tex2lyx(FileName(infilename), cout, default_encoding))
939                         return EXIT_SUCCESS;
940         } else {
941                 masterFilePathLyX = onlyPath(outfilename);
942                 if (roundtrip) {
943                         if (tex2tex(infilename, FileName(outfilename), default_encoding))
944                                 return EXIT_SUCCESS;
945                 } else {
946                         if (tex2lyx(infilename, FileName(outfilename), default_encoding))
947                                 return EXIT_SUCCESS;
948                 }
949         }
950         return EXIT_FAILURE;
951 }
952
953 // }])