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