]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
Some more oxygen svg icon fixes
[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         cout << "Built on " << lyx_build_date << ", " << lyx_build_time
610              << endl;
611
612         cout << lyx_version_info << endl;
613         throw StopException(error_code);
614 }
615
616
617 void error_message(string const & message)
618 {
619         cerr << "tex2lyx: " << message << "\n\n";
620         error_code = EXIT_FAILURE;
621         parse_help(string(), string());
622 }
623
624
625 int parse_class(string const & arg, string const &)
626 {
627         if (arg.empty())
628                 error_message("Missing textclass string after -c switch");
629         documentclass = arg;
630         return 1;
631 }
632
633
634 int parse_module(string const & arg, string const &)
635 {
636         if (arg.empty())
637                 error_message("Missing modules string after -m switch");
638         split(arg, preloaded_modules, ',');
639         return 1;
640 }
641
642
643 int parse_encoding(string const & arg, string const &)
644 {
645         if (arg.empty())
646                 error_message("Missing encoding string after -e switch");
647         default_encoding = arg;
648         return 1;
649 }
650
651
652 int parse_fixed_encoding(string const & arg, string const &)
653 {
654         if (arg.empty())
655                 error_message("Missing encoding string after -fixedenc switch");
656         default_encoding = arg;
657         fixed_encoding = true;
658         return 1;
659 }
660
661
662 int parse_syntaxfile(string const & arg, string const &)
663 {
664         if (arg.empty())
665                 error_message("Missing syntaxfile string after -s switch");
666         syntaxfile = internal_path(arg);
667         return 1;
668 }
669
670
671 // Filled with the command line arguments "foo" of "-sysdir foo" or
672 // "-userdir foo".
673 string cl_system_support;
674 string cl_user_support;
675
676
677 int parse_sysdir(string const & arg, string const &)
678 {
679         if (arg.empty())
680                 error_message("Missing directory for -sysdir switch");
681         cl_system_support = internal_path(arg);
682         return 1;
683 }
684
685
686 int parse_userdir(string const & arg, string const &)
687 {
688         if (arg.empty())
689                 error_message("Missing directory for -userdir switch");
690         cl_user_support = internal_path(arg);
691         return 1;
692 }
693
694
695 int parse_force(string const &, string const &)
696 {
697         overwrite_files = true;
698         return 0;
699 }
700
701
702 int parse_noweb(string const &, string const &)
703 {
704         noweb_mode = true;
705         return 0;
706 }
707
708
709 int parse_skipchildren(string const &, string const &)
710 {
711         skip_children = true;
712         return 0;
713 }
714
715
716 int parse_roundtrip(string const &, string const &)
717 {
718         roundtrip = true;
719         return 0;
720 }
721
722
723 int parse_copyfiles(string const &, string const &)
724 {
725         copy_files = true;
726         return 0;
727 }
728
729
730 void TeX2LyXApp::easyParse()
731 {
732         map<string, cmd_helper> cmdmap;
733
734         cmdmap["-h"] = parse_help;
735         cmdmap["-help"] = parse_help;
736         cmdmap["--help"] = parse_help;
737         cmdmap["-v"] = parse_version;
738         cmdmap["-version"] = parse_version;
739         cmdmap["--version"] = parse_version;
740         cmdmap["-c"] = parse_class;
741         cmdmap["-m"] = parse_module;
742         cmdmap["-e"] = parse_encoding;
743         cmdmap["-fixedenc"] = parse_fixed_encoding;
744         cmdmap["-f"] = parse_force;
745         cmdmap["-s"] = parse_syntaxfile;
746         cmdmap["-n"] = parse_noweb;
747         cmdmap["-skipchildren"] = parse_skipchildren;
748         cmdmap["-sysdir"] = parse_sysdir;
749         cmdmap["-userdir"] = parse_userdir;
750         cmdmap["-roundtrip"] = parse_roundtrip;
751         cmdmap["-copyfiles"] = parse_copyfiles;
752
753         for (int i = 1; i < argc_; ++i) {
754                 map<string, cmd_helper>::const_iterator it
755                         = cmdmap.find(argv_[i]);
756
757                 // don't complain if not found - may be parsed later
758                 if (it == cmdmap.end()) {
759                         if (argv_[i][0] == '-')
760                                 error_message(string("Unknown option `") + argv_[i] + "'.");
761                         else
762                                 continue;
763                 }
764
765                 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
766                 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
767
768                 int const remove = 1 + it->second(arg, arg2);
769
770                 // Now, remove used arguments by shifting
771                 // the following ones remove places down.
772                 os::remove_internal_args(i, remove);
773                 argc_ -= remove;
774                 for (int j = i; j < argc_; ++j)
775                         argv_[j] = argv_[j + remove];
776                 --i;
777         }
778 }
779
780
781 // path of the first parsed file
782 string masterFilePathLyX;
783 string masterFilePathTeX;
784 // path of the currently parsed file
785 string parentFilePathTeX;
786
787 } // anonymous namespace
788
789
790 string getMasterFilePath(bool input)
791 {
792         return input ? masterFilePathTeX : masterFilePathLyX;
793 }
794
795 string getParentFilePath(bool input)
796 {
797         if (input)
798                 return parentFilePathTeX;
799         string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
800                                                from_utf8(parentFilePathTeX)));
801         if (rel.substr(0, 3) == "../") {
802                 // The parent is not below the master - keep the path
803                 return parentFilePathTeX;
804         }
805         return makeAbsPath(rel, masterFilePathLyX).absFileName();
806 }
807
808
809 bool copyFiles()
810 {
811         return copy_files;
812 }
813
814
815 bool overwriteFiles()
816 {
817         return overwrite_files;
818 }
819
820
821 bool skipChildren()
822 {
823         return skip_children;
824 }
825
826
827 bool roundtripMode()
828 {
829         return roundtrip;
830 }
831
832
833 namespace {
834
835 /*!
836  *  Reads tex input from \a is and writes lyx output to \a os.
837  *  Uses some common settings for the preamble, so this should only
838  *  be used more than once for included documents.
839  *  Caution: Overwrites the existing preamble settings if the new document
840  *  contains a preamble.
841  *  You must ensure that \p parentFilePathTeX is properly set before calling
842  *  this function!
843  */
844 bool tex2lyx(idocstream & is, ostream & os, string encoding)
845 {
846         // Set a sensible default encoding.
847         // This is used until an encoding command is found.
848         // For child documents use the encoding of the master, else ISO8859-1,
849         // (formerly known by its latex name latin1), since ISO8859-1 does not
850         // cause an iconv error if the actual encoding is different (bug 7509).
851         if (encoding.empty()) {
852                 if (preamble.inputencoding() == "auto")
853                         encoding = "ISO8859-1";
854                 else {
855                         Encoding const * const enc = encodings.fromLyXName(
856                                 preamble.inputencoding(), true);
857                         encoding = enc->iconvName();
858                 }
859         }
860
861         Parser p(is, fixed_encoding ? default_encoding : string());
862         p.setEncoding(encoding);
863         //p.dump();
864
865         preamble.parse(p, documentclass, textclass);
866         list<string> removed_modules;
867         LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
868         if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
869                 cerr << "Could not load default modules for text class." << endl;
870                 return false;
871         }
872
873         // Load preloaded modules.
874         // This needs to be done after the preamble is parsed, since the text
875         // class may not be known before. It neds to be done before parsing
876         // body, since otherwise the commands/environments provided by the
877         // modules would be parsed as ERT.
878         for (size_t i = 0; i < preloaded_modules.size(); ++i) {
879                 if (!addModule(preloaded_modules[i])) {
880                         cerr << "Error: Could not load module \""
881                              << preloaded_modules[i] << "\"." << endl;
882                         return false;
883                 }
884         }
885         // Ensure that the modules are not loaded again for included files
886         preloaded_modules.clear();
887
888         active_environments.push_back("document");
889         Context context(true, textclass);
890         stringstream ss;
891         // store the document language in the context to be able to handle the
892         // commands like \foreignlanguage and \textenglish etc.
893         context.font.language = preamble.defaultLanguage();
894         // parse the main text
895         parse_text(p, ss, FLAG_END, true, context);
896         if (Context::empty)
897                 // Empty document body. LyX needs at least one paragraph.
898                 context.check_layout(ss);
899         context.check_end_layout(ss);
900         ss << "\n\\end_body\n\\end_document\n";
901         active_environments.pop_back();
902
903         // We know the used modules only after parsing the full text
904         if (!used_modules.empty()) {
905                 LayoutModuleList::const_iterator const end = used_modules.end();
906                 LayoutModuleList::const_iterator it = used_modules.begin();
907                 for (; it != end; ++it)
908                         preamble.addModule(*it);
909         }
910         if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
911                 cerr << "Could not write LyX file header." << endl;
912                 return false;
913         }
914
915         ss.seekg(0);
916         os << ss.str();
917 #ifdef TEST_PARSER
918         p.reset();
919         ofdocstream parsertest("parsertest.tex");
920         while (p.good())
921                 parsertest << p.get_token().asInput();
922         // <origfile> and parsertest.tex should now have identical content
923 #endif
924         return true;
925 }
926
927
928 /// convert TeX from \p infilename to LyX and write it to \p os
929 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
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);
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 }
977
978
979 bool tex2tex(string const & infilename, FileName const & outfilename,
980              string const & encoding)
981 {
982         if (!tex2lyx(infilename, outfilename, encoding))
983                 return false;
984         string command = quoteName(package().lyx_binary().toFilesystemEncoding());
985         if (overwrite_files)
986                 command += " -f main";
987         else
988                 command += " -f none";
989         if (pdflatex)
990                 command += " -e pdflatex ";
991         else if (xetex)
992                 command += " -e xetex ";
993         else
994                 command += " -e latex ";
995         command += quoteName(outfilename.toFilesystemEncoding());
996         Systemcall one;
997         if (one.startscript(Systemcall::Wait, command) == 0)
998                 return true;
999         cerr << "Error: Running '" << command << "' failed." << endl;
1000         return false;
1001 }
1002
1003
1004 namespace {
1005
1006 int TeX2LyXApp::run()
1007 {
1008         // qt changes this, and our numeric conversions require the C locale
1009         setlocale(LC_NUMERIC, "C");
1010
1011         try {
1012                 init_package(internal_path(os::utf8_argv(0)), string(), string());
1013         } catch (ExceptionMessage const & message) {
1014                 cerr << to_utf8(message.title_) << ":\n"
1015                      << to_utf8(message.details_) << endl;
1016                 if (message.type_ == ErrorException)
1017                         return EXIT_FAILURE;
1018         }
1019
1020         easyParse();
1021
1022         if (argc_ <= 1)
1023                 error_message("Not enough arguments.");
1024
1025         try {
1026                 init_package(internal_path(os::utf8_argv(0)),
1027                              cl_system_support, cl_user_support);
1028         } catch (ExceptionMessage const & message) {
1029                 cerr << to_utf8(message.title_) << ":\n"
1030                      << to_utf8(message.details_) << endl;
1031                 if (message.type_ == ErrorException)
1032                         return EXIT_FAILURE;
1033         }
1034
1035         // Check that user LyX directory is ok.
1036         FileName const sup = package().user_support();
1037         if (sup.exists() && sup.isDirectory()) {
1038                 string const lock_file = package().getConfigureLockName();
1039                 int fd = fileLock(lock_file.c_str());
1040                 if (configFileNeedsUpdate("lyxrc.defaults") ||
1041                     configFileNeedsUpdate("lyxmodules.lst") ||
1042                     configFileNeedsUpdate("textclass.lst") ||
1043                     configFileNeedsUpdate("packages.lst"))
1044                         package().reconfigureUserLyXDir("");
1045                 fileUnlock(fd, lock_file.c_str());
1046         } else
1047                 error_message("User directory does not exist.");
1048
1049         // Now every known option is parsed. Look for input and output
1050         // file name (the latter is optional).
1051         string infilename = internal_path(os::utf8_argv(1));
1052         infilename = makeAbsPath(infilename).absFileName();
1053
1054         string outfilename;
1055         if (argc_ > 2) {
1056                 outfilename = internal_path(os::utf8_argv(2));
1057                 if (outfilename != "-")
1058                         outfilename = makeAbsPath(outfilename).absFileName();
1059                 if (roundtrip) {
1060                         if (outfilename == "-") {
1061                                 cerr << "Error: Writing to standard output is "
1062                                         "not supported in roundtrip mode."
1063                                      << endl;
1064                                 return EXIT_FAILURE;
1065                         }
1066                         string texfilename = changeExtension(outfilename, ".tex");
1067                         if (equivalent(FileName(infilename), FileName(texfilename))) {
1068                                 cerr << "Error: The input file `" << infilename
1069                                      << "´ would be overwritten by the TeX file exported from `"
1070                                      << outfilename << "´ in roundtrip mode." << endl;
1071                                 return EXIT_FAILURE;
1072                         }
1073                 }
1074         } else if (roundtrip) {
1075                 // avoid overwriting the input file
1076                 outfilename = changeExtension(infilename, ".lyx.lyx");
1077         } else
1078                 outfilename = changeExtension(infilename, ".lyx");
1079
1080         // Read the syntax tables
1081         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1082         if (system_syntaxfile.empty()) {
1083                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1084                 return EXIT_FAILURE;
1085         }
1086         if (!read_syntaxfile(system_syntaxfile))
1087                 return 2;
1088         if (!syntaxfile.empty())
1089                 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1090                         return 2;
1091
1092         // Read the encodings table.
1093         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1094         if (symbols_path.empty()) {
1095                 cerr << "Error: Could not find file \"unicodesymbols\"."
1096                      << endl;
1097                 return EXIT_FAILURE;
1098         }
1099         FileName const enc_path = libFileSearch(string(), "encodings");
1100         if (enc_path.empty()) {
1101                 cerr << "Error: Could not find file \"encodings\"."
1102                      << endl;
1103                 return EXIT_FAILURE;
1104         }
1105         encodings.read(enc_path, symbols_path);
1106         if (!default_encoding.empty()) {
1107                 Encoding const * const enc = encodings.fromLaTeXName(
1108                         default_encoding, Encoding::any, true);
1109                 if (!enc)
1110                         error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1111                 default_encoding = enc->iconvName();
1112                 if (fixed_encoding)
1113                         preamble.setInputencoding(enc->name());
1114         }
1115
1116         // Load the layouts
1117         LayoutFileList::get().read();
1118         //...and the modules
1119         theModuleList.read();
1120
1121         // The real work now.
1122         masterFilePathTeX = onlyPath(infilename);
1123         parentFilePathTeX = masterFilePathTeX;
1124         if (outfilename == "-") {
1125                 // assume same directory as input file
1126                 masterFilePathLyX = masterFilePathTeX;
1127                 if (tex2lyx(FileName(infilename), cout, default_encoding))
1128                         return EXIT_SUCCESS;
1129         } else {
1130                 masterFilePathLyX = onlyPath(outfilename);
1131                 if (copy_files) {
1132                         FileName const path(masterFilePathLyX);
1133                         if (!path.isDirectory()) {
1134                                 if (!path.createPath()) {
1135                                         cerr << "Warning: Could not create directory for file `"
1136                                              << masterFilePathLyX << "´." << endl;
1137                                         return EXIT_FAILURE;
1138                                 }
1139                         }
1140                 }
1141                 if (roundtrip) {
1142                         if (tex2tex(infilename, FileName(outfilename), default_encoding))
1143                                 return EXIT_SUCCESS;
1144                 } else {
1145                         if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1146                                 return EXIT_SUCCESS;
1147                 }
1148         }
1149         return EXIT_FAILURE;
1150 }
1151
1152 } // anonymous namespace
1153 } // namespace lyx
1154
1155
1156 int main(int argc, char * argv[])
1157 {
1158         //setlocale(LC_CTYPE, "");
1159
1160         lyx::lyxerr.setStream(cerr);
1161
1162         os::init(argc, argv);
1163
1164         lyx::TeX2LyXApp app(argc, argv);
1165         return app.exec();
1166 }
1167
1168 // }])