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