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