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