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