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