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