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