]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
add diagnostic messages by Jean-Pierre Chr��tien and skip some more {} pairs
[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 map<string, vector<ArgumentType> > known_commands;
131
132
133 void add_known_command(string const & command, string const & o1,
134                        bool o2)
135 {
136         // We have to handle the following cases:
137         // definition                      o1    o2    invocation result
138         // \newcommand{\foo}{bar}          ""    false \foo       bar
139         // \newcommand{\foo}[1]{bar #1}    "[1]" false \foo{x}    bar x
140         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo       bar
141         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo[x]    bar x
142         // \newcommand{\foo}[1][x]{bar #1} "[1]" true  \foo[x]    bar x
143         unsigned int nargs = 0;
144         vector<ArgumentType> arguments;
145         string const opt1 = rtrim(ltrim(o1, "["), "]");
146         if (isStrUnsignedInt(opt1)) {
147                 // The command has arguments
148                 nargs = convert<unsigned int>(opt1);
149                 if (nargs > 0 && o2) {
150                         // The first argument is optional
151                         arguments.push_back(optional);
152                         --nargs;
153                 }
154         }
155         for (unsigned int i = 0; i < nargs; ++i)
156                 arguments.push_back(required);
157         known_commands[command] = arguments;
158 }
159
160
161 namespace {
162
163
164 /*!
165  * Read a list of TeX commands from a reLyX compatible syntax file.
166  * Since this list is used after all commands that have a LyX counterpart
167  * are handled, it does not matter that the "syntax.default" file from reLyX
168  * has almost all of them listed. For the same reason the reLyX-specific
169  * reLyXre environment is ignored.
170  */
171 void read_syntaxfile(string const & file_name)
172 {
173         ifstream is(file_name.c_str());
174         if (!is.good()) {
175                 cerr << "Could not open syntax file \"" << file_name
176                      << "\" for reading." << endl;
177                 exit(2);
178         }
179         // We can use our TeX parser, since the syntax of the layout file is
180         // modeled after TeX.
181         // Unknown tokens are just silently ignored, this helps us to skip some
182         // reLyX specific things.
183         Parser p(is);
184         while (p.good()) {
185                 Token const & t = p.get_token();
186                 if (t.cat() == catEscape) {
187                         string command = t.asInput();
188                         if (p.next_token().asInput() == "*") {
189                                 p.get_token();
190                                 command += '*';
191                         }
192                         p.skip_spaces();
193                         vector<ArgumentType> arguments;
194                         while (p.next_token().cat() == catBegin ||
195                                p.next_token().asInput() == "[") {
196                                 if (p.next_token().cat() == catBegin) {
197                                         string const arg = p.getArg('{', '}');
198                                         if (arg == "translate")
199                                                 arguments.push_back(required);
200                                         else
201                                                 arguments.push_back(verbatim);
202                                 } else {
203                                         p.getArg('[', ']');
204                                         arguments.push_back(optional);
205                                 }
206                         }
207                         known_commands[command] = arguments;
208                 }
209         }
210 }
211
212
213 string documentclass;
214 string syntaxfile;
215 bool overwrite_files = false;
216
217
218 /// return the number of arguments consumed
219 typedef boost::function<int(string const &, string const &)> cmd_helper;
220
221
222 int parse_help(string const &, string const &)
223 {
224         cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
225                 "Command line switches (case sensitive):\n"
226                 "\t-help              summarize tex2lyx usage\n"
227                 "\t-f                 Force creation of .lyx files even if they exist already\n"
228                 "\t-userdir dir       try to set user directory to dir\n"
229                 "\t-sysdir dir        try to set system directory to dir\n"
230                 "\t-c textclass       declare the textclass\n"
231                 "\t-s syntaxfile      read additional syntax file" << endl;
232         exit(0);
233 }
234
235
236 int parse_class(string const & arg, string const &)
237 {
238         if (arg.empty()) {
239                 cerr << "Missing textclass string after -c switch" << endl;
240                 exit(1);
241         }
242         documentclass = arg;
243         return 1;
244 }
245
246
247 int parse_syntaxfile(string const & arg, string const &)
248 {
249         if (arg.empty()) {
250                 cerr << "Missing syntaxfile string after -s switch" << endl;
251                 exit(1);
252         }
253         syntaxfile = arg;
254         return 1;
255 }
256
257
258 // Filled with the command line arguments "foo" of "-sysdir foo" or
259 // "-userdir foo".
260 string cl_system_support;
261 string cl_user_support;
262
263
264 int parse_sysdir(string const & arg, string const &)
265 {
266         if (arg.empty()) {
267                 cerr << "Missing directory for -sysdir switch" << endl;
268                 exit(1);
269         }
270         cl_system_support = arg;
271         return 1;
272 }
273
274
275 int parse_userdir(string const & arg, string const &)
276 {
277         if (arg.empty()) {
278                 cerr << "Missing directory for -userdir switch" << endl;
279                 exit(1);
280         }
281         cl_user_support = arg;
282         return 1;
283 }
284
285
286 int parse_force(string const &, string const &)
287 {
288         overwrite_files = true;
289         return 0;
290 }
291
292
293 void easyParse(int & argc, char * argv[])
294 {
295         map<string, cmd_helper> cmdmap;
296
297         cmdmap["-c"] = parse_class;
298         cmdmap["-f"] = parse_force;
299         cmdmap["-s"] = parse_syntaxfile;
300         cmdmap["-help"] = parse_help;
301         cmdmap["--help"] = parse_help;
302         cmdmap["-sysdir"] = parse_sysdir;
303         cmdmap["-userdir"] = parse_userdir;
304
305         for (int i = 1; i < argc; ++i) {
306                 std::map<string, cmd_helper>::const_iterator it
307                         = cmdmap.find(argv[i]);
308
309                 // don't complain if not found - may be parsed later
310                 if (it == cmdmap.end())
311                         continue;
312
313                 string arg((i + 1 < argc) ? argv[i + 1] : "");
314                 string arg2((i + 2 < argc) ? argv[i + 2] : "");
315
316                 int const remove = 1 + it->second(arg, arg2);
317
318                 // Now, remove used arguments by shifting
319                 // the following ones remove places down.
320                 argc -= remove;
321                 for (int j = i; j < argc; ++j)
322                         argv[j] = argv[j + remove];
323                 --i;
324         }
325 }
326
327
328 // path of the first parsed file
329 string masterFilePath;
330 // path of the currently parsed file
331 string parentFilePath;
332
333 } // anonymous namespace
334
335
336 string getMasterFilePath()
337 {
338         return masterFilePath;
339 }
340
341 string getParentFilePath()
342 {
343         return parentFilePath;
344 }
345
346
347 namespace {
348
349 /*!
350  *  Reads tex input from \a is and writes lyx output to \a os.
351  *  Uses some common settings for the preamble, so this should only
352  *  be used more than once for included documents.
353  *  Caution: Overwrites the existing preamble settings if the new document
354  *  contains a preamble.
355  *  You must ensure that \p parentFilePath is properly set before calling
356  *  this function!
357  */
358 void tex2lyx(std::istream &is, std::ostream &os)
359 {
360         Parser p(is);
361         //p.dump();
362
363         stringstream ss;
364         LyXTextClass textclass = parse_preamble(p, ss, documentclass);
365
366         active_environments.push_back("document");
367         Context context(true, textclass);
368         parse_text(p, ss, FLAG_END, true, context);
369         context.check_end_layout(ss);
370         ss << "\n\\end_body\n\\end_document\n";
371         active_environments.pop_back();
372         ss.seekg(0);
373         os << ss.str();
374 #ifdef TEST_PARSER
375         p.reset();
376         ofstream parsertest("parsertest.tex");
377         while (p.good())
378                 parsertest << p.get_token().asInput();
379         // <origfile> and parsertest.tex should now have identical content
380 #endif
381 }
382
383
384 /// convert TeX from \p infilename to LyX and write it to \p os
385 bool tex2lyx(string const &infilename, std::ostream &os)
386 {
387         BOOST_ASSERT(lyx::support::AbsolutePath(infilename));
388         ifstream is(infilename.c_str());
389         if (!is.good()) {
390                 cerr << "Could not open input file \"" << infilename
391                      << "\" for reading." << endl;
392                 return false;
393         }
394         string const oldParentFilePath = parentFilePath;
395         parentFilePath = OnlyPath(infilename);
396         tex2lyx(is, os);
397         parentFilePath = oldParentFilePath;
398         return true;
399 }
400
401 } // anonymous namespace
402
403
404 bool tex2lyx(string const &infilename, string const &outfilename)
405 {
406         if (IsFileReadable(outfilename)) {
407                 if (overwrite_files) {
408                         cerr << "Overwriting existing file "
409                              << outfilename << endl;
410                 } else {
411                         cerr << "Not overwriting existing file "
412                              << outfilename << endl;
413                         return false;
414                 }
415         } else {
416                 cerr << "Creating file " << outfilename << endl;
417         }
418         ofstream os(outfilename.c_str());
419         if (!os.good()) {
420                 cerr << "Could not open output file \"" << outfilename
421                      << "\" for writing." << endl;
422                 return false;
423         }
424 #ifdef FILEDEBUG
425         cerr << "Input file: " << infilename << "\n";
426         cerr << "Output file: " << outfilename << "\n";
427 #endif
428         return tex2lyx(infilename, os);
429 }
430
431
432 int main(int argc, char * argv[])
433 {
434         fs::path::default_name_check(fs::no_check);
435
436         easyParse(argc, argv);
437
438         if (argc <= 1) {
439                 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
440                           "See tex2lyx -help." << endl;
441                 return 2;
442         }
443
444         lyx::support::os::init(argc, argv);
445         lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
446                                    lyx::support::top_build_dir_is_two_levels_up);
447
448         string const system_syntaxfile = lyx::support::LibFileSearch("reLyX", "syntax.default");
449         if (system_syntaxfile.empty()) {
450                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
451                 exit(1);
452         }
453         read_syntaxfile(system_syntaxfile);
454         if (!syntaxfile.empty())
455                 read_syntaxfile(syntaxfile);
456
457         string const infilename = MakeAbsPath(argv[1]);
458         masterFilePath = OnlyPath(infilename);
459         parentFilePath = masterFilePath;
460
461         if (tex2lyx(infilename, cout))
462                 return EXIT_SUCCESS;
463         else
464                 return EXIT_FAILURE;
465 }
466
467 // }])