]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
08b8a0cacb879d563127ae3249dd82aaa29eb5bc
[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
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::os::internal_path;
66 using support::rtrim;
67 using support::isFileReadable;
68
69 namespace fs = boost::filesystem;
70
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
431         active_environments.push_back("document");
432         Context context(true, textclass);
433         parse_text(p, ss, FLAG_END, true, context);
434         if (Context::empty)
435                 // Empty document body. LyX needs at least one paragraph.
436                 context.check_layout(ss);
437         context.check_end_layout(ss);
438         ss << "\n\\end_body\n\\end_document\n";
439         active_environments.pop_back();
440         ss.seekg(0);
441         os << ss.str();
442 #ifdef TEST_PARSER
443         p.reset();
444         ofstream parsertest("parsertest.tex");
445         while (p.good())
446                 parsertest << p.get_token().asInput();
447         // <origfile> and parsertest.tex should now have identical content
448 #endif
449 }
450
451
452 /// convert TeX from \p infilename to LyX and write it to \p os
453 bool tex2lyx(FileName const & infilename, std::ostream &os)
454 {
455         ifstream is(infilename.toFilesystemEncoding().c_str());
456         if (!is.good()) {
457                 cerr << "Could not open input file \"" << infilename
458                      << "\" for reading." << endl;
459                 return false;
460         }
461         string const oldParentFilePath = parentFilePath;
462         parentFilePath = onlyPath(infilename.absFilename());
463         tex2lyx(is, os);
464         parentFilePath = oldParentFilePath;
465         return true;
466 }
467
468 } // anonymous namespace
469
470
471 bool tex2lyx(string const &infilename, FileName const &outfilename)
472 {
473         if (isFileReadable(outfilename)) {
474                 if (overwrite_files) {
475                         cerr << "Overwriting existing file "
476                              << outfilename << endl;
477                 } else {
478                         cerr << "Not overwriting existing file "
479                              << outfilename << endl;
480                         return false;
481                 }
482         } else {
483                 cerr << "Creating file " << outfilename << endl;
484         }
485         ofstream os(outfilename.toFilesystemEncoding().c_str());
486         if (!os.good()) {
487                 cerr << "Could not open output file \"" << outfilename
488                      << "\" for writing." << endl;
489                 return false;
490         }
491 #ifdef FILEDEBUG
492         cerr << "Input file: " << infilename << "\n";
493         cerr << "Output file: " << outfilename << "\n";
494 #endif
495         return tex2lyx(FileName(infilename), os);
496 }
497
498 } // namespace lyx
499
500
501 int main(int argc, char * argv[])
502 {
503         using namespace lyx;
504         fs::path::default_name_check(fs::no_check);
505
506         easyParse(argc, argv);
507
508         if (argc <= 1) {
509                 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
510                           "See tex2lyx -help." << endl;
511                 return 2;
512         }
513
514         lyx::support::os::init(argc, argv);
515
516         try { support::init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
517                 cl_system_support, cl_user_support,
518                 support::top_build_dir_is_two_levels_up);
519         } catch (support::ExceptionMessage const & message) {
520                 cerr << to_utf8(message.title_) << ":\n"
521                         << to_utf8(message.details_) << endl;
522                 if (message.type_ == support::ErrorException)
523                         exit(1);
524         }
525         
526         // Now every known option is parsed. Look for input and output
527         // file name (the latter is optional).
528         string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
529         infilename = makeAbsPath(infilename).absFilename();
530         
531         string outfilename;
532         if (argc > 2) {
533                 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
534                 if (outfilename != "-")
535                         outfilename = makeAbsPath(outfilename).absFilename();
536         } else
537                 outfilename = changeExtension(infilename, ".lyx");
538
539         FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
540         if (system_syntaxfile.empty()) {
541                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
542                 exit(1);
543         }
544         read_syntaxfile(system_syntaxfile);
545         if (!syntaxfile.empty())
546                 read_syntaxfile(makeAbsPath(syntaxfile));
547
548         masterFilePath = onlyPath(infilename);
549         parentFilePath = masterFilePath;
550
551         if (outfilename == "-") {
552                 if (tex2lyx(FileName(infilename), cout))
553                         return EXIT_SUCCESS;
554                 else
555                         return EXIT_FAILURE;
556         } else {
557                 if (tex2lyx(infilename, FileName(outfilename)))
558                         return EXIT_SUCCESS;
559                 else
560                         return EXIT_FAILURE;
561         }
562 }
563
564 // }])