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