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