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