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