]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
cleanup after svn hang-up, #undef CursorShape. Should be compilable ganin now.
[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 bool noweb_mode = false;
165
166
167 namespace {
168
169
170 /*!
171  * Read one command definition from the syntax file
172  */
173 void read_command(Parser & p, string command, CommandMap & commands) {
174         if (p.next_token().asInput() == "*") {
175                 p.get_token();
176                 command += '*';
177         }
178         vector<ArgumentType> arguments;
179         while (p.next_token().cat() == catBegin ||
180                p.next_token().asInput() == "[") {
181                 if (p.next_token().cat() == catBegin) {
182                         string const arg = p.getArg('{', '}');
183                         if (arg == "translate")
184                                 arguments.push_back(required);
185                         else
186                                 arguments.push_back(verbatim);
187                 } else {
188                         p.getArg('[', ']');
189                         arguments.push_back(optional);
190                 }
191         }
192         commands[command] = arguments;
193 }
194
195
196 /*!
197  * Read a class of environments from the syntax file
198  */
199 void read_environment(Parser & p, string const & begin,
200                       CommandMap & environments)
201 {
202         string environment;
203         while (p.good()) {
204                 Token const & t = p.get_token();
205                 if (t.cat() == catLetter)
206                         environment += t.asInput();
207                 else if (!environment.empty()) {
208                         p.putback();
209                         read_command(p, environment, environments);
210                         environment.erase();
211                 }
212                 if (t.cat() == catEscape && t.asInput() == "\\end") {
213                         string const end = p.getArg('{', '}');
214                         if (end == begin)
215                                 return;
216                 }
217         }
218 }
219
220
221 /*!
222  * Read a list of TeX commands from a reLyX compatible syntax file.
223  * Since this list is used after all commands that have a LyX counterpart
224  * are handled, it does not matter that the "syntax.default" file
225  * has almost all of them listed. For the same reason the reLyX-specific
226  * reLyXre environment is ignored.
227  */
228 void read_syntaxfile(string const & file_name)
229 {
230         ifstream is(file_name.c_str());
231         if (!is.good()) {
232                 cerr << "Could not open syntax file \"" << file_name
233                      << "\" for reading." << endl;
234                 exit(2);
235         }
236         // We can use our TeX parser, since the syntax of the layout file is
237         // modeled after TeX.
238         // Unknown tokens are just silently ignored, this helps us to skip some
239         // reLyX specific things.
240         Parser p(is);
241         while (p.good()) {
242                 Token const & t = p.get_token();
243                 if (t.cat() == catEscape) {
244                         string const command = t.asInput();
245                         if (command == "\\begin") {
246                                 string const name = p.getArg('{', '}');
247                                 if (name == "environments" || name == "reLyXre")
248                                         // We understand "reLyXre", but it is
249                                         // not as powerful as "environments".
250                                         read_environment(p, name,
251                                                 known_environments);
252                                 else if (name == "mathenvironments")
253                                         read_environment(p, name,
254                                                 known_math_environments);
255                         } else {
256                                 read_command(p, command, known_commands);
257                         }
258                 }
259         }
260 }
261
262
263 string documentclass;
264 string syntaxfile;
265 bool overwrite_files = false;
266
267
268 /// return the number of arguments consumed
269 typedef boost::function<int(string const &, string const &)> cmd_helper;
270
271
272 int parse_help(string const &, string const &)
273 {
274         cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
275                 "Command line switches (case sensitive):\n"
276                 "\t-help              summarize tex2lyx usage\n"
277                 "\t-f                 Force creation of .lyx files even if they exist already\n"
278                 "\t-userdir dir       try to set user directory to dir\n"
279                 "\t-sysdir dir        try to set system directory to dir\n"
280                 "\t-c textclass       declare the textclass\n"
281                 "\t-n                 translate a noweb (aka literate programming) file.\n"
282                 "\t-s syntaxfile      read additional syntax file" << endl;
283         exit(0);
284 }
285
286
287 int parse_class(string const & arg, string const &)
288 {
289         if (arg.empty()) {
290                 cerr << "Missing textclass string after -c switch" << endl;
291                 exit(1);
292         }
293         documentclass = arg;
294         return 1;
295 }
296
297
298 int parse_syntaxfile(string const & arg, string const &)
299 {
300         if (arg.empty()) {
301                 cerr << "Missing syntaxfile string after -s switch" << endl;
302                 exit(1);
303         }
304         syntaxfile = arg;
305         return 1;
306 }
307
308
309 // Filled with the command line arguments "foo" of "-sysdir foo" or
310 // "-userdir foo".
311 string cl_system_support;
312 string cl_user_support;
313
314
315 int parse_sysdir(string const & arg, string const &)
316 {
317         if (arg.empty()) {
318                 cerr << "Missing directory for -sysdir switch" << endl;
319                 exit(1);
320         }
321         cl_system_support = arg;
322         return 1;
323 }
324
325
326 int parse_userdir(string const & arg, string const &)
327 {
328         if (arg.empty()) {
329                 cerr << "Missing directory for -userdir switch" << endl;
330                 exit(1);
331         }
332         cl_user_support = arg;
333         return 1;
334 }
335
336
337 int parse_force(string const &, string const &)
338 {
339         overwrite_files = true;
340         return 0;
341 }
342
343
344 int parse_noweb(string const &, string const &)
345 {
346         noweb_mode = true;
347         return 0;
348 }
349
350
351 void easyParse(int & argc, char * argv[])
352 {
353         map<string, cmd_helper> cmdmap;
354
355         cmdmap["-c"] = parse_class;
356         cmdmap["-f"] = parse_force;
357         cmdmap["-s"] = parse_syntaxfile;
358         cmdmap["-help"] = parse_help;
359         cmdmap["--help"] = parse_help;
360         cmdmap["-n"] = parse_noweb;
361         cmdmap["-sysdir"] = parse_sysdir;
362         cmdmap["-userdir"] = parse_userdir;
363
364         for (int i = 1; i < argc; ++i) {
365                 std::map<string, cmd_helper>::const_iterator it
366                         = cmdmap.find(argv[i]);
367
368                 // don't complain if not found - may be parsed later
369                 if (it == cmdmap.end())
370                         continue;
371
372                 string arg((i + 1 < argc) ? argv[i + 1] : "");
373                 string arg2((i + 2 < argc) ? argv[i + 2] : "");
374
375                 int const remove = 1 + it->second(arg, arg2);
376
377                 // Now, remove used arguments by shifting
378                 // the following ones remove places down.
379                 argc -= remove;
380                 for (int j = i; j < argc; ++j)
381                         argv[j] = argv[j + remove];
382                 --i;
383         }
384 }
385
386
387 // path of the first parsed file
388 string masterFilePath;
389 // path of the currently parsed file
390 string parentFilePath;
391
392 } // anonymous namespace
393
394
395 string getMasterFilePath()
396 {
397         return masterFilePath;
398 }
399
400 string getParentFilePath()
401 {
402         return parentFilePath;
403 }
404
405
406 namespace {
407
408 /*!
409  *  Reads tex input from \a is and writes lyx output to \a os.
410  *  Uses some common settings for the preamble, so this should only
411  *  be used more than once for included documents.
412  *  Caution: Overwrites the existing preamble settings if the new document
413  *  contains a preamble.
414  *  You must ensure that \p parentFilePath is properly set before calling
415  *  this function!
416  */
417 void tex2lyx(std::istream &is, std::ostream &os)
418 {
419         Parser p(is);
420         //p.dump();
421
422         stringstream ss;
423         LyXTextClass textclass = parse_preamble(p, ss, documentclass);
424
425         active_environments.push_back("document");
426         Context context(true, textclass);
427         parse_text(p, ss, FLAG_END, true, context);
428         if (Context::empty)
429                 // Empty document body. LyX needs at least one paragraph.
430                 context.check_layout(ss);
431         context.check_end_layout(ss);
432         ss << "\n\\end_body\n\\end_document\n";
433         active_environments.pop_back();
434         ss.seekg(0);
435         os << ss.str();
436 #ifdef TEST_PARSER
437         p.reset();
438         ofstream parsertest("parsertest.tex");
439         while (p.good())
440                 parsertest << p.get_token().asInput();
441         // <origfile> and parsertest.tex should now have identical content
442 #endif
443 }
444
445
446 /// convert TeX from \p infilename to LyX and write it to \p os
447 bool tex2lyx(string const &infilename, std::ostream &os)
448 {
449         BOOST_ASSERT(lyx::support::absolutePath(infilename));
450         ifstream is(infilename.c_str());
451         if (!is.good()) {
452                 cerr << "Could not open input file \"" << infilename
453                      << "\" for reading." << endl;
454                 return false;
455         }
456         string const oldParentFilePath = parentFilePath;
457         parentFilePath = onlyPath(infilename);
458         tex2lyx(is, os);
459         parentFilePath = oldParentFilePath;
460         return true;
461 }
462
463 } // anonymous namespace
464
465
466 bool tex2lyx(string const &infilename, string const &outfilename)
467 {
468         if (isFileReadable(outfilename)) {
469                 if (overwrite_files) {
470                         cerr << "Overwriting existing file "
471                              << outfilename << endl;
472                 } else {
473                         cerr << "Not overwriting existing file "
474                              << outfilename << endl;
475                         return false;
476                 }
477         } else {
478                 cerr << "Creating file " << outfilename << endl;
479         }
480         ofstream os(outfilename.c_str());
481         if (!os.good()) {
482                 cerr << "Could not open output file \"" << outfilename
483                      << "\" for writing." << endl;
484                 return false;
485         }
486 #ifdef FILEDEBUG
487         cerr << "Input file: " << infilename << "\n";
488         cerr << "Output file: " << outfilename << "\n";
489 #endif
490         return tex2lyx(infilename, os);
491 }
492
493
494 int main(int argc, char * argv[])
495 {
496         fs::path::default_name_check(fs::no_check);
497
498         easyParse(argc, argv);
499
500         if (argc <= 1) {
501                 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
502                           "See tex2lyx -help." << endl;
503                 return 2;
504         }
505
506         lyx::support::os::init(argc, argv);
507         lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
508                                    lyx::support::top_build_dir_is_two_levels_up);
509
510         // Now every known option is parsed. Look for input and output
511         // file name (the latter is optional).
512         string const infilename = makeAbsPath(argv[1]);
513         string outfilename;
514         if (argc > 2) {
515                 outfilename = argv[2];
516                 if (outfilename != "-")
517                         outfilename = makeAbsPath(argv[2]);
518         } else
519                 outfilename = changeExtension(infilename, ".lyx");
520
521         string const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
522         if (system_syntaxfile.empty()) {
523                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
524                 exit(1);
525         }
526         read_syntaxfile(system_syntaxfile);
527         if (!syntaxfile.empty())
528                 read_syntaxfile(syntaxfile);
529
530         masterFilePath = onlyPath(infilename);
531         parentFilePath = masterFilePath;
532
533         if (outfilename == "-") {
534                 if (tex2lyx(infilename, cout))
535                         return EXIT_SUCCESS;
536                 else
537                         return EXIT_FAILURE;
538         } else {
539                 if (tex2lyx(infilename, outfilename))
540                         return EXIT_SUCCESS;
541                 else
542                         return EXIT_FAILURE;
543         }
544 }
545
546 // }])