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