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