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