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