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