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