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