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