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