]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
81afdaec6f03648678be8b3b2677d0c479df7ca6
[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
15 #include "tex2lyx.h"
16 #include "Context.h"
17
18 #include "debug.h"
19 #include "LyXTextClass.h"
20
21 #include "support/convert.h"
22 #include "support/filetools.h"
23 #include "support/fs_extras.h"
24 #include "support/lstrings.h"
25 #include "support/lyxlib.h"
26 #include "support/ExceptionMessage.h"
27 #include "support/os.h"
28 #include "support/package.h"
29 #include "support/unicode.h"
30
31 #include <boost/function.hpp>
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/filesystem/path.hpp>
34
35 #include <fstream>
36 #include <iostream>
37 #include <string>
38 #include <sstream>
39 #include <vector>
40 #include <map>
41
42
43 namespace lyx {
44
45 using std::endl;
46 using std::cout;
47 using std::cerr;
48 using std::getline;
49
50 using std::ifstream;
51 using std::ofstream;
52 using std::istringstream;
53 using std::ostringstream;
54 using std::stringstream;
55 using std::string;
56 using std::vector;
57 using std::map;
58
59 using support::changeExtension;
60 using support::FileName;
61 using support::isStrUnsignedInt;
62 using support::ltrim;
63 using support::makeAbsPath;
64 using support::onlyPath;
65 using support::rtrim;
66 using support::isFileReadable;
67
68 namespace fs = boost::filesystem;
69
70
71 // Hacks to allow the thing to link in the lyxlayout stuff
72 LyXErr lyxerr(std::cerr.rdbuf());
73
74
75 string const trim(string const & a, char const * p)
76 {
77         // BOOST_ASSERT(p);
78
79         if (a.empty() || !*p)
80                 return a;
81
82         string::size_type r = a.find_last_not_of(p);
83         string::size_type l = a.find_first_not_of(p);
84
85         // Is this the minimal test? (lgb)
86         if (r == string::npos && l == string::npos)
87                 return string();
88
89         return a.substr(l, r - l + 1);
90 }
91
92
93 void split(string const & s, vector<string> & result, char delim)
94 {
95         //cerr << "split 1: '" << s << "'\n";
96         istringstream is(s);
97         string t;
98         while (getline(is, t, delim))
99                 result.push_back(t);
100         //cerr << "split 2\n";
101 }
102
103
104 string join(vector<string> const & input, char const * delim)
105 {
106         ostringstream os;
107         for (size_t i = 0; i < input.size(); ++i) {
108                 if (i)
109                         os << delim;
110                 os << input[i];
111         }
112         return os.str();
113 }
114
115
116 char const * const * is_known(string const & str, char const * const * what)
117 {
118         for ( ; *what; ++what)
119                 if (str == *what)
120                         return what;
121         return 0;
122 }
123
124
125
126 // current stack of nested environments
127 vector<string> active_environments;
128
129
130 string active_environment()
131 {
132         return active_environments.empty() ? string() : active_environments.back();
133 }
134
135
136 CommandMap known_commands;
137 CommandMap known_environments;
138 CommandMap known_math_environments;
139
140
141 void add_known_command(string const & command, string const & o1,
142                        bool o2)
143 {
144         // We have to handle the following cases:
145         // definition                      o1    o2    invocation result
146         // \newcommand{\foo}{bar}          ""    false \foo       bar
147         // \newcommand{\foo}[1]{bar #1}    "[1]" false \foo{x}    bar x
148         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo       bar
149         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo[x]    bar x
150         // \newcommand{\foo}[1][x]{bar #1} "[1]" true  \foo[x]    bar x
151         unsigned int nargs = 0;
152         vector<ArgumentType> arguments;
153         string const opt1 = rtrim(ltrim(o1, "["), "]");
154         if (isStrUnsignedInt(opt1)) {
155                 // The command has arguments
156                 nargs = convert<unsigned int>(opt1);
157                 if (nargs > 0 && o2) {
158                         // The first argument is optional
159                         arguments.push_back(optional);
160                         --nargs;
161                 }
162         }
163         for (unsigned int i = 0; i < nargs; ++i)
164                 arguments.push_back(required);
165         known_commands[command] = arguments;
166 }
167
168
169 bool noweb_mode = false;
170
171
172 namespace {
173
174
175 /*!
176  * Read one command definition from the syntax file
177  */
178 void read_command(Parser & p, string command, CommandMap & commands) {
179         if (p.next_token().asInput() == "*") {
180                 p.get_token();
181                 command += '*';
182         }
183         vector<ArgumentType> arguments;
184         while (p.next_token().cat() == catBegin ||
185                p.next_token().asInput() == "[") {
186                 if (p.next_token().cat() == catBegin) {
187                         string const arg = p.getArg('{', '}');
188                         if (arg == "translate")
189                                 arguments.push_back(required);
190                         else
191                                 arguments.push_back(verbatim);
192                 } else {
193                         p.getArg('[', ']');
194                         arguments.push_back(optional);
195                 }
196         }
197         commands[command] = arguments;
198 }
199
200
201 /*!
202  * Read a class of environments from the syntax file
203  */
204 void read_environment(Parser & p, string const & begin,
205                       CommandMap & environments)
206 {
207         string environment;
208         while (p.good()) {
209                 Token const & t = p.get_token();
210                 if (t.cat() == catLetter)
211                         environment += t.asInput();
212                 else if (!environment.empty()) {
213                         p.putback();
214                         read_command(p, environment, environments);
215                         environment.erase();
216                 }
217                 if (t.cat() == catEscape && t.asInput() == "\\end") {
218                         string const end = p.getArg('{', '}');
219                         if (end == begin)
220                                 return;
221                 }
222         }
223 }
224
225
226 /*!
227  * Read a list of TeX commands from a reLyX compatible syntax file.
228  * Since this list is used after all commands that have a LyX counterpart
229  * are handled, it does not matter that the "syntax.default" file
230  * has almost all of them listed. For the same reason the reLyX-specific
231  * reLyXre environment is ignored.
232  */
233 void read_syntaxfile(FileName const & file_name)
234 {
235         ifstream is(file_name.toFilesystemEncoding().c_str());
236         if (!is.good()) {
237                 cerr << "Could not open syntax file \"" << file_name
238                      << "\" for reading." << endl;
239                 exit(2);
240         }
241         // We can use our TeX parser, since the syntax of the layout file is
242         // modeled after TeX.
243         // Unknown tokens are just silently ignored, this helps us to skip some
244         // reLyX specific things.
245         Parser p(is);
246         while (p.good()) {
247                 Token const & t = p.get_token();
248                 if (t.cat() == catEscape) {
249                         string const command = t.asInput();
250                         if (command == "\\begin") {
251                                 string const name = p.getArg('{', '}');
252                                 if (name == "environments" || name == "reLyXre")
253                                         // We understand "reLyXre", but it is
254                                         // not as powerful as "environments".
255                                         read_environment(p, name,
256                                                 known_environments);
257                                 else if (name == "mathenvironments")
258                                         read_environment(p, name,
259                                                 known_math_environments);
260                         } else {
261                                 read_command(p, command, known_commands);
262                         }
263                 }
264         }
265 }
266
267
268 string documentclass;
269 string syntaxfile;
270 bool overwrite_files = false;
271
272
273 /// return the number of arguments consumed
274 typedef boost::function<int(string const &, string const &)> cmd_helper;
275
276
277 int parse_help(string const &, string const &)
278 {
279         cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
280                 "Command line switches (case sensitive):\n"
281                 "\t-help              summarize tex2lyx usage\n"
282                 "\t-f                 Force creation of .lyx files even if they exist already\n"
283                 "\t-userdir dir       try to set user directory to dir\n"
284                 "\t-sysdir dir        try to set system directory to dir\n"
285                 "\t-c textclass       declare the textclass\n"
286                 "\t-n                 translate a noweb (aka literate programming) file.\n"
287                 "\t-s syntaxfile      read additional syntax file" << endl;
288         exit(0);
289 }
290
291
292 int parse_class(string const & arg, string const &)
293 {
294         if (arg.empty()) {
295                 cerr << "Missing textclass string after -c switch" << endl;
296                 exit(1);
297         }
298         documentclass = arg;
299         return 1;
300 }
301
302
303 int parse_syntaxfile(string const & arg, string const &)
304 {
305         if (arg.empty()) {
306                 cerr << "Missing syntaxfile string after -s switch" << endl;
307                 exit(1);
308         }
309         syntaxfile = arg;
310         return 1;
311 }
312
313
314 // Filled with the command line arguments "foo" of "-sysdir foo" or
315 // "-userdir foo".
316 string cl_system_support;
317 string cl_user_support;
318
319
320 int parse_sysdir(string const & arg, string const &)
321 {
322         if (arg.empty()) {
323                 cerr << "Missing directory for -sysdir switch" << endl;
324                 exit(1);
325         }
326         cl_system_support = arg;
327         return 1;
328 }
329
330
331 int parse_userdir(string const & arg, string const &)
332 {
333         if (arg.empty()) {
334                 cerr << "Missing directory for -userdir switch" << endl;
335                 exit(1);
336         }
337         cl_user_support = arg;
338         return 1;
339 }
340
341
342 int parse_force(string const &, string const &)
343 {
344         overwrite_files = true;
345         return 0;
346 }
347
348
349 int parse_noweb(string const &, string const &)
350 {
351         noweb_mode = true;
352         return 0;
353 }
354
355
356 void easyParse(int & argc, char * argv[])
357 {
358         map<string, cmd_helper> cmdmap;
359
360         cmdmap["-c"] = parse_class;
361         cmdmap["-f"] = parse_force;
362         cmdmap["-s"] = parse_syntaxfile;
363         cmdmap["-help"] = parse_help;
364         cmdmap["--help"] = parse_help;
365         cmdmap["-n"] = parse_noweb;
366         cmdmap["-sysdir"] = parse_sysdir;
367         cmdmap["-userdir"] = parse_userdir;
368
369         for (int i = 1; i < argc; ++i) {
370                 std::map<string, cmd_helper>::const_iterator it
371                         = cmdmap.find(argv[i]);
372
373                 // don't complain if not found - may be parsed later
374                 if (it == cmdmap.end())
375                         continue;
376
377                 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
378                 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
379
380                 int const remove = 1 + it->second(arg, arg2);
381
382                 // Now, remove used arguments by shifting
383                 // the following ones remove places down.
384                 argc -= remove;
385                 for (int j = i; j < argc; ++j)
386                         argv[j] = argv[j + remove];
387                 --i;
388         }
389 }
390
391
392 // path of the first parsed file
393 string masterFilePath;
394 // path of the currently parsed file
395 string parentFilePath;
396
397 } // anonymous namespace
398
399
400 string getMasterFilePath()
401 {
402         return masterFilePath;
403 }
404
405 string getParentFilePath()
406 {
407         return parentFilePath;
408 }
409
410
411 namespace {
412
413 /*!
414  *  Reads tex input from \a is and writes lyx output to \a os.
415  *  Uses some common settings for the preamble, so this should only
416  *  be used more than once for included documents.
417  *  Caution: Overwrites the existing preamble settings if the new document
418  *  contains a preamble.
419  *  You must ensure that \p parentFilePath is properly set before calling
420  *  this function!
421  */
422 void tex2lyx(std::istream &is, std::ostream &os)
423 {
424         Parser p(is);
425         //p.dump();
426
427         stringstream ss;
428         LyXTextClass textclass = parse_preamble(p, ss, documentclass);
429
430         active_environments.push_back("document");
431         Context context(true, textclass);
432         parse_text(p, ss, FLAG_END, true, context);
433         if (Context::empty)
434                 // Empty document body. LyX needs at least one paragraph.
435                 context.check_layout(ss);
436         context.check_end_layout(ss);
437         ss << "\n\\end_body\n\\end_document\n";
438         active_environments.pop_back();
439         ss.seekg(0);
440         os << ss.str();
441 #ifdef TEST_PARSER
442         p.reset();
443         ofstream parsertest("parsertest.tex");
444         while (p.good())
445                 parsertest << p.get_token().asInput();
446         // <origfile> and parsertest.tex should now have identical content
447 #endif
448 }
449
450
451 /// convert TeX from \p infilename to LyX and write it to \p os
452 bool tex2lyx(FileName const & infilename, std::ostream &os)
453 {
454         ifstream is(infilename.toFilesystemEncoding().c_str());
455         if (!is.good()) {
456                 cerr << "Could not open input file \"" << infilename
457                      << "\" for reading." << endl;
458                 return false;
459         }
460         string const oldParentFilePath = parentFilePath;
461         parentFilePath = onlyPath(infilename.absFilename());
462         tex2lyx(is, os);
463         parentFilePath = oldParentFilePath;
464         return true;
465 }
466
467 } // anonymous namespace
468
469
470 bool tex2lyx(string const &infilename, FileName const &outfilename)
471 {
472         if (isFileReadable(outfilename)) {
473                 if (overwrite_files) {
474                         cerr << "Overwriting existing file "
475                              << outfilename << endl;
476                 } else {
477                         cerr << "Not overwriting existing file "
478                              << outfilename << endl;
479                         return false;
480                 }
481         } else {
482                 cerr << "Creating file " << outfilename << endl;
483         }
484         ofstream os(outfilename.toFilesystemEncoding().c_str());
485         if (!os.good()) {
486                 cerr << "Could not open output file \"" << outfilename
487                      << "\" for writing." << endl;
488                 return false;
489         }
490 #ifdef FILEDEBUG
491         cerr << "Input file: " << infilename << "\n";
492         cerr << "Output file: " << outfilename << "\n";
493 #endif
494         return tex2lyx(FileName(infilename), os);
495 }
496
497 } // namespace lyx
498
499
500 int main(int argc, char * argv[])
501 {
502         using namespace lyx;
503         fs::path::default_name_check(fs::no_check);
504
505         easyParse(argc, argv);
506
507         if (argc <= 1) {
508                 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
509                           "See tex2lyx -help." << endl;
510                 return 2;
511         }
512
513         lyx::support::os::init(argc, argv);
514
515         try { support::init_package(to_utf8(from_local8bit(argv[0])),
516                 cl_system_support, cl_user_support,
517                 support::top_build_dir_is_two_levels_up);
518         } catch (support::ExceptionMessage const & message) {
519                 cerr << to_utf8(message.title_) << ":\n"
520                         << to_utf8(message.details_) << endl;
521                 if (message.type_ == support::ErrorException)
522                         exit(1);
523         }
524
525         // Now every known option is parsed. Look for input and output
526         // file name (the latter is optional).
527         string const infilename = makeAbsPath(to_utf8(from_local8bit(argv[1]))).absFilename();
528         string outfilename;
529         if (argc > 2) {
530                 outfilename = to_utf8(from_local8bit(argv[2]));
531                 if (outfilename != "-")
532                         outfilename = makeAbsPath(to_utf8(from_local8bit(argv[2]))).absFilename();
533         } else
534                 outfilename = changeExtension(infilename, ".lyx");
535
536         FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
537         if (system_syntaxfile.empty()) {
538                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
539                 exit(1);
540         }
541         read_syntaxfile(system_syntaxfile);
542         if (!syntaxfile.empty())
543                 read_syntaxfile(makeAbsPath(syntaxfile));
544
545         masterFilePath = onlyPath(infilename);
546         parentFilePath = masterFilePath;
547
548         if (outfilename == "-") {
549                 if (tex2lyx(FileName(infilename), cout))
550                         return EXIT_SUCCESS;
551                 else
552                         return EXIT_FAILURE;
553         } else {
554                 if (tex2lyx(infilename, FileName(outfilename)))
555                         return EXIT_SUCCESS;
556                 else
557                         return EXIT_FAILURE;
558         }
559 }
560
561 // }])