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