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