]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
Dispay pre- and posttext widgets if non-empty also if unapplied
[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                         vector<string> v;
391                         LayoutModuleList mods;
392                         // addModule is necessary in order to catch required modules
393                         // as well (see #11156)
394                         if (!addModule(module, baseClass, mods, v))
395                                 return false;
396                         for (auto const & mod : mods) {
397                                 if (!used_modules.moduleCanBeAdded(mod, &baseClass))
398                                         return false;
399                                 FileName layout_file = libFileSearch("layouts", mod, "module");
400                                 if (textclass.read(layout_file, TextClass::MODULE)) {
401                                         used_modules.push_back(mod);
402                                         // speed up further searches:
403                                         // the module does not need to be checked anymore.
404                                         ModuleMap::iterator const it = modules.find(mod);
405                                         if (it != modules.end())
406                                                 modules.erase(it);
407                                         return true;
408                                 }
409                         }
410                 }
411         }
412         failed[command].insert(name);
413         return false;
414 }
415
416
417 bool isProvided(string const & name)
418 {
419         // This works only for features that are named like the LaTeX packages
420         return textclass.provides(name) || preamble.isPackageUsed(name);
421 }
422
423
424 bool noweb_mode = false;
425 bool pdflatex = false;
426 bool xetex = false;
427 bool is_nonCJKJapanese = false;
428 bool roundtrip = false;
429
430
431 namespace {
432
433
434 /*!
435  * Read one command definition from the syntax file
436  */
437 void read_command(Parser & p, string command, CommandMap & commands)
438 {
439         if (p.next_token().asInput() == "*") {
440                 p.get_token();
441                 command += '*';
442         }
443         vector<ArgumentType> arguments;
444         while (p.next_token().cat() == catBegin ||
445                p.next_token().asInput() == "[") {
446                 if (p.next_token().cat() == catBegin) {
447                         string const arg = p.getArg('{', '}');
448                         if (arg == "translate")
449                                 arguments.push_back(required);
450                         else if (arg == "group")
451                                 arguments.push_back(req_group);
452                         else if (arg == "item")
453                                 arguments.push_back(item);
454                         else if (arg == "displaymath")
455                                 arguments.push_back(displaymath);
456                         else
457                                 arguments.push_back(verbatim);
458                 } else {
459                         string const arg = p.getArg('[', ']');
460                         if (arg == "group")
461                                 arguments.push_back(opt_group);
462                         else
463                                 arguments.push_back(optional);
464                 }
465         }
466         commands[command] = arguments;
467 }
468
469
470 /*!
471  * Read a class of environments from the syntax file
472  */
473 void read_environment(Parser & p, string const & begin,
474                       CommandMap & environments)
475 {
476         string environment;
477         while (p.good()) {
478                 Token const & t = p.get_token();
479                 if (t.cat() == catLetter)
480                         environment += t.asInput();
481                 else if (!environment.empty()) {
482                         p.putback();
483                         read_command(p, environment, environments);
484                         environment.erase();
485                 }
486                 if (t.cat() == catEscape && t.asInput() == "\\end") {
487                         string const end = p.getArg('{', '}');
488                         if (end == begin)
489                                 return;
490                 }
491         }
492 }
493
494
495 /*!
496  * Read a list of TeX commands from a reLyX compatible syntax file.
497  * Since this list is used after all commands that have a LyX counterpart
498  * are handled, it does not matter that the "syntax.default" file
499  * has almost all of them listed. For the same reason the reLyX-specific
500  * reLyXre environment is ignored.
501  */
502 bool read_syntaxfile(FileName const & file_name)
503 {
504         ifdocstream is(file_name.toFilesystemEncoding().c_str());
505         if (!is.good()) {
506                 cerr << "Could not open syntax file \"" << file_name
507                      << "\" for reading." << endl;
508                 return false;
509         }
510         // We can use our TeX parser, since the syntax of the layout file is
511         // modeled after TeX.
512         // Unknown tokens are just silently ignored, this helps us to skip some
513         // reLyX specific things.
514         Parser p(is, string());
515         while (p.good()) {
516                 Token const & t = p.get_token();
517                 if (t.cat() == catEscape) {
518                         string const command = t.asInput();
519                         if (command == "\\begin") {
520                                 string const name = p.getArg('{', '}');
521                                 if (name == "environments" || name == "reLyXre")
522                                         // We understand "reLyXre", but it is
523                                         // not as powerful as "environments".
524                                         read_environment(p, name,
525                                                 known_environments);
526                                 else if (name == "mathenvironments")
527                                         read_environment(p, name,
528                                                 known_math_environments);
529                         } else {
530                                 read_command(p, command, known_commands);
531                         }
532                 }
533         }
534         return true;
535 }
536
537
538 string documentclass;
539 string default_encoding;
540 bool fixed_encoding = false;
541 string syntaxfile;
542 bool copy_files = false;
543 bool overwrite_files = false;
544 bool skip_children = false;
545 int error_code = 0;
546
547 /// return the number of arguments consumed
548 typedef int (*cmd_helper)(string const &, string const &);
549
550
551 class StopException : public exception
552 {
553         public:
554                 StopException(int status) : status_(status) {}
555                 int status() const { return status_; }
556         private:
557                 int status_;
558 };
559
560
561 /// The main application class
562 class TeX2LyXApp : public ConsoleApplication
563 {
564 public:
565         TeX2LyXApp(int & argc, char * argv[])
566                 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
567                   argc_(argc), argv_(argv)
568         {
569         }
570         void doExec()
571         {
572                 try {
573                         int const exit_status = run();
574                         exit(exit_status);
575                 }
576                 catch (StopException & e) {
577                         exit(e.status());
578                 }
579         }
580 private:
581         void easyParse();
582         /// Do the real work
583         int run();
584         int & argc_;
585         char ** argv_;
586 };
587
588
589 int parse_help(string const &, string const &)
590 {
591         cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
592                 "Options:\n"
593                 "\t-c textclass       Declare the textclass.\n"
594                 "\t-m mod1[,mod2...]  Load the given modules.\n"
595                 "\t-copyfiles         Copy all included files to the directory of outfile.lyx.\n"
596                 "\t-e encoding        Set the default encoding (latex name).\n"
597                 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
598                 "\t-f                 Force overwrite of .lyx files.\n"
599                 "\t-help              Print this message and quit.\n"
600                 "\t-n                 translate literate programming (noweb, sweave,... ) file.\n"
601                 "\t-skipchildren      Do not translate included child documents.\n"
602                 "\t-roundtrip         re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
603                 "\t-s syntaxfile      read additional syntax file.\n"
604                 "\t-sysdir SYSDIR     Set system directory to SYSDIR.\n"
605                 "\t                   Default: " << package().system_support() << "\n"
606                 "\t-userdir USERDIR   Set user directory to USERDIR.\n"
607                 "\t                   Default: " << package().user_support() << "\n"
608                 "\t-version           Summarize version and build info.\n"
609                 "Paths:\n"
610                 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
611                 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
612                 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
613                 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
614                 "Check the tex2lyx man page for more details."
615              << endl;
616         throw StopException(error_code);
617 }
618
619
620 int parse_version(string const &, string const &)
621 {
622         cout << "tex2lyx " << lyx_version
623              << " (" << lyx_release_date << ")" << endl;
624
625         cout << lyx_version_info << endl;
626         throw StopException(error_code);
627 }
628
629
630 void error_message(string const & message)
631 {
632         cerr << "tex2lyx: " << message << "\n\n";
633         error_code = EXIT_FAILURE;
634         parse_help(string(), string());
635 }
636
637
638 int parse_class(string const & arg, string const &)
639 {
640         if (arg.empty())
641                 error_message("Missing textclass string after -c switch");
642         documentclass = arg;
643         return 1;
644 }
645
646
647 int parse_module(string const & arg, string const &)
648 {
649         if (arg.empty())
650                 error_message("Missing modules string after -m switch");
651         split(arg, preloaded_modules, ',');
652         return 1;
653 }
654
655
656 int parse_encoding(string const & arg, string const &)
657 {
658         if (arg.empty())
659                 error_message("Missing encoding string after -e switch");
660         default_encoding = arg;
661         return 1;
662 }
663
664
665 int parse_fixed_encoding(string const & arg, string const &)
666 {
667         if (arg.empty())
668                 error_message("Missing encoding string after -fixedenc switch");
669         default_encoding = arg;
670         fixed_encoding = true;
671         return 1;
672 }
673
674
675 int parse_syntaxfile(string const & arg, string const &)
676 {
677         if (arg.empty())
678                 error_message("Missing syntaxfile string after -s switch");
679         syntaxfile = internal_path(arg);
680         return 1;
681 }
682
683
684 // Filled with the command line arguments "foo" of "-sysdir foo" or
685 // "-userdir foo".
686 string cl_system_support;
687 string cl_user_support;
688
689
690 int parse_sysdir(string const & arg, string const &)
691 {
692         if (arg.empty())
693                 error_message("Missing directory for -sysdir switch");
694         cl_system_support = internal_path(arg);
695         return 1;
696 }
697
698
699 int parse_userdir(string const & arg, string const &)
700 {
701         if (arg.empty())
702                 error_message("Missing directory for -userdir switch");
703         cl_user_support = internal_path(arg);
704         return 1;
705 }
706
707
708 int parse_force(string const &, string const &)
709 {
710         overwrite_files = true;
711         return 0;
712 }
713
714
715 int parse_noweb(string const &, string const &)
716 {
717         noweb_mode = true;
718         return 0;
719 }
720
721
722 int parse_skipchildren(string const &, string const &)
723 {
724         skip_children = true;
725         return 0;
726 }
727
728
729 int parse_roundtrip(string const &, string const &)
730 {
731         roundtrip = true;
732         return 0;
733 }
734
735
736 int parse_copyfiles(string const &, string const &)
737 {
738         copy_files = true;
739         return 0;
740 }
741
742
743 void TeX2LyXApp::easyParse()
744 {
745         map<string, cmd_helper> cmdmap;
746
747         cmdmap["-h"] = parse_help;
748         cmdmap["-help"] = parse_help;
749         cmdmap["--help"] = parse_help;
750         cmdmap["-v"] = parse_version;
751         cmdmap["-version"] = parse_version;
752         cmdmap["--version"] = parse_version;
753         cmdmap["-c"] = parse_class;
754         cmdmap["-m"] = parse_module;
755         cmdmap["-e"] = parse_encoding;
756         cmdmap["-fixedenc"] = parse_fixed_encoding;
757         cmdmap["-f"] = parse_force;
758         cmdmap["-s"] = parse_syntaxfile;
759         cmdmap["-n"] = parse_noweb;
760         cmdmap["-skipchildren"] = parse_skipchildren;
761         cmdmap["-sysdir"] = parse_sysdir;
762         cmdmap["-userdir"] = parse_userdir;
763         cmdmap["-roundtrip"] = parse_roundtrip;
764         cmdmap["-copyfiles"] = parse_copyfiles;
765
766         for (int i = 1; i < argc_; ++i) {
767                 map<string, cmd_helper>::const_iterator it
768                         = cmdmap.find(argv_[i]);
769
770                 // don't complain if not found - may be parsed later
771                 if (it == cmdmap.end()) {
772                         if (argv_[i][0] == '-')
773                                 error_message(string("Unknown option `") + argv_[i] + "'.");
774                         else
775                                 continue;
776                 }
777
778                 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
779                 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
780
781                 int const remove = 1 + it->second(arg, arg2);
782
783                 // Now, remove used arguments by shifting
784                 // the following ones remove places down.
785                 os::remove_internal_args(i, remove);
786                 argc_ -= remove;
787                 for (int j = i; j < argc_; ++j)
788                         argv_[j] = argv_[j + remove];
789                 --i;
790         }
791 }
792
793
794 // path of the first parsed file
795 string masterFilePathLyX;
796 string masterFilePathTeX;
797 // path of the currently parsed file
798 string parentFilePathTeX;
799
800 } // anonymous namespace
801
802
803 string getMasterFilePath(bool input)
804 {
805         return input ? masterFilePathTeX : masterFilePathLyX;
806 }
807
808 string getParentFilePath(bool input)
809 {
810         if (input)
811                 return parentFilePathTeX;
812         string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
813                                                from_utf8(parentFilePathTeX)));
814         if (rel.substr(0, 3) == "../") {
815                 // The parent is not below the master - keep the path
816                 return parentFilePathTeX;
817         }
818         return makeAbsPath(rel, masterFilePathLyX).absFileName();
819 }
820
821
822 bool copyFiles()
823 {
824         return copy_files;
825 }
826
827
828 bool overwriteFiles()
829 {
830         return overwrite_files;
831 }
832
833
834 bool skipChildren()
835 {
836         return skip_children;
837 }
838
839
840 bool roundtripMode()
841 {
842         return roundtrip;
843 }
844
845
846 namespace {
847
848 /*!
849  *  Reads tex input from \a is and writes lyx output to \a os.
850  *  Uses some common settings for the preamble, so this should only
851  *  be used more than once for included documents.
852  *  Caution: Overwrites the existing preamble settings if the new document
853  *  contains a preamble.
854  *  You must ensure that \p parentFilePathTeX is properly set before calling
855  *  this function!
856  */
857 bool tex2lyx(idocstream & is, ostream & os, string const & encoding,
858              string const & outfiledir)
859 {
860         Parser p(is, fixed_encoding ? default_encoding : string());
861         p.setEncoding(encoding);
862         //p.dump();
863
864         preamble.parse(p, documentclass, textclass);
865         list<string> removed_modules;
866         LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
867         if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
868                 cerr << "Could not load default modules for text class." << endl;
869                 return false;
870         }
871
872         // Load preloaded modules.
873         // This needs to be done after the preamble is parsed, since the text
874         // class may not be known before. It neds to be done before parsing
875         // body, since otherwise the commands/environments provided by the
876         // modules would be parsed as ERT.
877         for (size_t i = 0; i < preloaded_modules.size(); ++i) {
878                 if (!addModule(preloaded_modules[i])) {
879                         cerr << "Error: Could not load module \""
880                              << preloaded_modules[i] << "\"." << endl;
881                         return false;
882                 }
883         }
884         // Ensure that the modules are not loaded again for included files
885         preloaded_modules.clear();
886
887         active_environments.push_back("document");
888         Context context(true, textclass);
889         stringstream ss;
890         // store the document language in the context to be able to handle the
891         // commands like \foreignlanguage and \textenglish etc.
892         context.font.language = preamble.defaultLanguage();
893         // parse the main text
894         parse_text(p, ss, FLAG_END, true, context);
895         // check if we need a commented bibtex inset (biblatex)
896         check_comment_bib(ss, context);
897         if (Context::empty)
898                 // Empty document body. LyX needs at least one paragraph.
899                 context.check_layout(ss);
900         context.check_end_layout(ss);
901         ss << "\n\\end_body\n\\end_document\n";
902         active_environments.pop_back();
903
904         // We know the used modules only after parsing the full text
905         if (!used_modules.empty()) {
906                 LayoutModuleList::const_iterator const end = used_modules.end();
907                 LayoutModuleList::const_iterator it = used_modules.begin();
908                 for (; it != end; ++it)
909                         preamble.addModule(*it);
910         }
911         if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
912                 cerr << "Could not write LyX file header." << endl;
913                 return false;
914         }
915
916         ss.seekg(0);
917         os << ss.str();
918 #ifdef TEST_PARSER
919         p.reset();
920         ofdocstream parsertest("parsertest.tex");
921         while (p.good())
922                 parsertest << p.get_token().asInput();
923         // <origfile> and parsertest.tex should now have identical content
924 #endif
925         return true;
926 }
927
928
929 /// convert TeX from \p infilename to LyX and write it to \p os
930 bool tex2lyx(FileName const & infilename, ostream & os, string encoding,
931              string const & outfiledir)
932 {
933         // Set a sensible default encoding.
934         // This is used until an encoding command is found.
935         // For child documents use the encoding of the master, else try to
936         // detect it from the preamble, since setting an encoding of an open
937         // fstream does currently not work on OS X.
938         // Always start with ISO-8859-1, (formerly known by its latex name
939         // latin1), since ISO-8859-1 does not cause an iconv error if the
940         // actual encoding is different (bug 7509).
941         if (encoding.empty()) {
942                 Encoding const * enc = 0;
943                 if (preamble.inputencoding() == "auto") {
944                         ifdocstream is(setEncoding("ISO-8859-1"));
945                         // forbid buffering on this stream
946                         is.rdbuf()->pubsetbuf(0, 0);
947                         is.open(infilename.toFilesystemEncoding().c_str());
948                         if (is.good()) {
949                                 Parser ep(is, string());
950                                 ep.setEncoding("ISO-8859-1");
951                                 Preamble encodingpreamble;
952                                 string const e = encodingpreamble
953                                         .parseEncoding(ep, documentclass);
954                                 if (!e.empty())
955                                         enc = encodings.fromLyXName(e, true);
956                         }
957                 } else
958                         enc = encodings.fromLyXName(
959                                         preamble.inputencoding(), true);
960                 if (enc)
961                         encoding = enc->iconvName();
962                 else
963                         encoding = "ISO-8859-1";
964         }
965
966         ifdocstream is(setEncoding(encoding));
967         // forbid buffering on this stream
968         is.rdbuf()->pubsetbuf(0, 0);
969         is.open(infilename.toFilesystemEncoding().c_str());
970         if (!is.good()) {
971                 cerr << "Could not open input file \"" << infilename
972                      << "\" for reading." << endl;
973                 return false;
974         }
975         string const oldParentFilePath = parentFilePathTeX;
976         parentFilePathTeX = onlyPath(infilename.absFileName());
977         bool retval = tex2lyx(is, os, encoding, outfiledir);
978         parentFilePathTeX = oldParentFilePath;
979         return retval;
980 }
981
982 } // anonymous namespace
983
984
985 bool tex2lyx(string const & infilename, FileName const & outfilename,
986              string const & encoding)
987 {
988         if (outfilename.isReadableFile()) {
989                 if (overwrite_files) {
990                         cerr << "Overwriting existing file "
991                              << outfilename << endl;
992                 } else {
993                         cerr << "Not overwriting existing file "
994                              << outfilename << endl;
995                         return false;
996                 }
997         } else {
998                 cerr << "Creating file " << outfilename << endl;
999         }
1000         ofstream os(outfilename.toFilesystemEncoding().c_str());
1001         if (!os.good()) {
1002                 cerr << "Could not open output file \"" << outfilename
1003                      << "\" for writing." << endl;
1004                 return false;
1005         }
1006 #ifdef FILEDEBUG
1007         cerr << "Input file: " << infilename << "\n";
1008         cerr << "Output file: " << outfilename << "\n";
1009 #endif
1010         return tex2lyx(FileName(infilename), os, encoding,
1011                        outfilename.onlyPath().absFileName() + '/');
1012 }
1013
1014
1015 bool tex2tex(string const & infilename, FileName const & outfilename,
1016              string const & encoding)
1017 {
1018         if (!tex2lyx(infilename, outfilename, encoding))
1019                 return false;
1020         string command = quoteName(package().lyx_binary().toFilesystemEncoding());
1021         if (overwrite_files)
1022                 command += " -f main";
1023         else
1024                 command += " -f none";
1025         if (pdflatex)
1026                 command += " -e pdflatex ";
1027         else if (xetex)
1028                 command += " -e xetex ";
1029         else
1030                 command += " -e latex ";
1031         command += quoteName(outfilename.toFilesystemEncoding());
1032         Systemcall one;
1033         if (one.startscript(Systemcall::Wait, command) == 0)
1034                 return true;
1035         cerr << "Error: Running '" << command << "' failed." << endl;
1036         return false;
1037 }
1038
1039
1040 namespace {
1041
1042 int TeX2LyXApp::run()
1043 {
1044         // qt changes this, and our numeric conversions require the C locale
1045         setlocale(LC_NUMERIC, "C");
1046
1047         try {
1048                 init_package(internal_path(os::utf8_argv(0)), string(), string());
1049         } catch (ExceptionMessage const & message) {
1050                 cerr << to_utf8(message.title_) << ":\n"
1051                      << to_utf8(message.details_) << endl;
1052                 if (message.type_ == ErrorException)
1053                         return EXIT_FAILURE;
1054         }
1055
1056         easyParse();
1057
1058         if (argc_ <= 1)
1059                 error_message("Not enough arguments.");
1060
1061         try {
1062                 init_package(internal_path(os::utf8_argv(0)),
1063                              cl_system_support, cl_user_support);
1064         } catch (ExceptionMessage const & message) {
1065                 cerr << to_utf8(message.title_) << ":\n"
1066                      << to_utf8(message.details_) << endl;
1067                 if (message.type_ == ErrorException)
1068                         return EXIT_FAILURE;
1069         }
1070
1071         // Check that user LyX directory is ok.
1072         FileName const sup = package().user_support();
1073         if (sup.exists() && sup.isDirectory()) {
1074                 string const lock_file = package().getConfigureLockName();
1075                 int fd = fileLock(lock_file.c_str());
1076                 if (configFileNeedsUpdate("lyxrc.defaults") ||
1077                     configFileNeedsUpdate("lyxmodules.lst") ||
1078                     configFileNeedsUpdate("textclass.lst") ||
1079                     configFileNeedsUpdate("packages.lst") ||
1080                     configFileNeedsUpdate("lyxciteengines.lst") ||
1081                     configFileNeedsUpdate("xtemplates.lst"))
1082                         package().reconfigureUserLyXDir("");
1083                 fileUnlock(fd, lock_file.c_str());
1084         } else
1085                 error_message("User directory does not exist.");
1086
1087         // Now every known option is parsed. Look for input and output
1088         // file name (the latter is optional).
1089         string infilename = internal_path(os::utf8_argv(1));
1090         infilename = makeAbsPath(infilename).absFileName();
1091
1092         string outfilename;
1093         if (argc_ > 2) {
1094                 outfilename = internal_path(os::utf8_argv(2));
1095                 if (outfilename != "-")
1096                         outfilename = makeAbsPath(outfilename).absFileName();
1097                 if (roundtrip) {
1098                         if (outfilename == "-") {
1099                                 cerr << "Error: Writing to standard output is "
1100                                         "not supported in roundtrip mode."
1101                                      << endl;
1102                                 return EXIT_FAILURE;
1103                         }
1104                         string texfilename = changeExtension(outfilename, ".tex");
1105                         if (equivalent(FileName(infilename), FileName(texfilename))) {
1106                                 cerr << "Error: The input file `" << infilename
1107                                      << "´ would be overwritten by the TeX file exported from `"
1108                                      << outfilename << "´ in roundtrip mode." << endl;
1109                                 return EXIT_FAILURE;
1110                         }
1111                 }
1112         } else if (roundtrip) {
1113                 // avoid overwriting the input file
1114                 outfilename = changeExtension(infilename, ".lyx.lyx");
1115         } else
1116                 outfilename = changeExtension(infilename, ".lyx");
1117
1118         // Read the syntax tables
1119         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1120         if (system_syntaxfile.empty()) {
1121                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1122                 return EXIT_FAILURE;
1123         }
1124         if (!read_syntaxfile(system_syntaxfile))
1125                 return 2;
1126         if (!syntaxfile.empty())
1127                 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1128                         return 2;
1129
1130         // Read the encodings table.
1131         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1132         if (symbols_path.empty()) {
1133                 cerr << "Error: Could not find file \"unicodesymbols\"."
1134                      << endl;
1135                 return EXIT_FAILURE;
1136         }
1137         FileName const enc_path = libFileSearch(string(), "encodings");
1138         if (enc_path.empty()) {
1139                 cerr << "Error: Could not find file \"encodings\"."
1140                      << endl;
1141                 return EXIT_FAILURE;
1142         }
1143         encodings.read(enc_path, symbols_path);
1144         if (!default_encoding.empty()) {
1145                 Encoding const * const enc = encodings.fromLaTeXName(
1146                         default_encoding, Encoding::any, true);
1147                 if (!enc)
1148                         error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1149                 default_encoding = enc->iconvName();
1150                 if (fixed_encoding)
1151                         preamble.setInputencoding(enc->name());
1152         }
1153
1154         // Load the layouts
1155         LayoutFileList::get().read();
1156         //...and the modules
1157         theModuleList.read();
1158
1159         // The real work now.
1160         masterFilePathTeX = onlyPath(infilename);
1161         parentFilePathTeX = masterFilePathTeX;
1162         if (outfilename == "-") {
1163                 // assume same directory as input file
1164                 masterFilePathLyX = masterFilePathTeX;
1165                 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1166                         return EXIT_SUCCESS;
1167         } else {
1168                 masterFilePathLyX = onlyPath(outfilename);
1169                 if (copy_files) {
1170                         FileName const path(masterFilePathLyX);
1171                         if (!path.isDirectory()) {
1172                                 if (!path.createPath()) {
1173                                         cerr << "Warning: Could not create directory for file `"
1174                                              << masterFilePathLyX << "´." << endl;
1175                                         return EXIT_FAILURE;
1176                                 }
1177                         }
1178                 }
1179                 if (roundtrip) {
1180                         if (tex2tex(infilename, FileName(outfilename), default_encoding))
1181                                 return EXIT_SUCCESS;
1182                 } else {
1183                         if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1184                                 return EXIT_SUCCESS;
1185                 }
1186         }
1187         return EXIT_FAILURE;
1188 }
1189
1190 } // anonymous namespace
1191 } // namespace lyx
1192
1193
1194 int main(int argc, char * argv[])
1195 {
1196         //setlocale(LC_CTYPE, "");
1197
1198         lyx::lyxerr.setStream(cerr);
1199
1200         os::init(argc, &argv);
1201
1202         lyx::TeX2LyXApp app(argc, argv);
1203         return app.exec();
1204 }
1205
1206 // }])