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