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