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