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