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