]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
rename getExtFromContents() to getFormatFromContents()
[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 "format.h"
20 #include "lyxtextclass.h"
21 #include "support/path_defines.h"
22 #include "support/filetools.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::system_lyxdir;
51 using lyx::support::user_lyxdir;
52 using lyx::support::IsFileReadable;
53 using lyx::support::IsFileWriteable;
54
55 // Hacks to allow the thing to link in the lyxlayout stuff
56 LyXErr lyxerr(std::cerr.rdbuf());
57
58
59 // hack to link in libsupport
60 Formats formats;
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 namespace {
128
129
130 /*!
131  * Read a list of TeX commands from a reLyX compatible syntax file.
132  * Since this list is used after all commands that have a LyX counterpart
133  * are handled, it does not matter that the "syntax.default" file from reLyX
134  * has almost all of them listed. For the same reason the reLyX-specific
135  * reLyXre environment is ignored.
136  */
137 void read_syntaxfile(string const & file_name)
138 {
139         if (!IsFileReadable(file_name)) {
140                 cerr << "Could not open syntax file \"" << file_name
141                      << "\" for reading." << endl;
142                 exit(2);
143         }
144         ifstream is(file_name.c_str());
145         // We can use our TeX parser, since the syntax of the layout file is
146         // modeled after TeX.
147         // Unknown tokens are just silently ignored, this helps us to skip some
148         // reLyX specific things.
149         Parser p(is);
150         while (p.good()) {
151                 Token const & t = p.get_token();
152                 if (t.cat() == catEscape) {
153                         string command = t.asInput();
154                         if (p.next_token().asInput() == "*") {
155                                 p.get_token();
156                                 command += '*';
157                         }
158                         p.skip_spaces();
159                         vector<ArgumentType> arguments;
160                         while (p.next_token().cat() == catBegin ||
161                                p.next_token().asInput() == "[") {
162                                 if (p.next_token().cat() == catBegin) {
163                                         string const arg = p.getArg('{', '}');
164                                         if (arg == "translate")
165                                                 arguments.push_back(required);
166                                         else
167                                                 arguments.push_back(verbatim);
168                                 } else {
169                                         p.getArg('[', ']');
170                                         arguments.push_back(optional);
171                                 }
172                         }
173                         known_commands[command] = arguments;
174                 }
175         }
176 }
177
178
179 string documentclass;
180 string syntaxfile;
181 bool overwrite_files = false;
182
183
184 /// return the number of arguments consumed
185 typedef boost::function<int(string const &, string const &)> cmd_helper;
186
187
188 int parse_help(string const &, string const &)
189 {
190         cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
191                 "Command line switches (case sensitive):\n"
192                 "\t-help              summarize tex2lyx usage\n"
193                 "\t-f                 Force creation of .lyx files even if they exist already\n"
194                 "\t-userdir dir       try to set user directory to dir\n"
195                 "\t-sysdir dir        try to set system directory to dir\n"
196                 "\t-c textclass       declare the textclass\n"
197                 "\t-s syntaxfile      read additional syntax file" << endl;
198         exit(0);
199 }
200
201
202 int parse_class(string const & arg, string const &)
203 {
204         if (arg.empty()) {
205                 cerr << "Missing textclass string after -c switch" << endl;
206                 exit(1);
207         }
208         documentclass = arg;
209         return 1;
210 }
211
212
213 int parse_syntaxfile(string const & arg, string const &)
214 {
215         if (arg.empty()) {
216                 cerr << "Missing syntaxfile string after -s switch" << endl;
217                 exit(1);
218         }
219         syntaxfile = arg;
220         return 1;
221 }
222
223
224 int parse_sysdir(string const & arg, string const &)
225 {
226         if (arg.empty()) {
227                 cerr << "Missing directory for -sysdir switch" << endl;
228                 exit(1);
229         }
230         system_lyxdir(arg);
231         return 1;
232 }
233
234
235 int parse_userdir(string const & arg, string const &)
236 {
237         if (arg.empty()) {
238                 cerr << "Missing directory for -userdir switch" << endl;
239                 exit(1);
240         }
241         user_lyxdir(arg);
242         return 1;
243 }
244
245
246 int parse_force(string const &, string const &)
247 {
248         overwrite_files = true;
249         return 0;
250 }
251
252
253 void easyParse(int & argc, char * argv[])
254 {
255         map<string, cmd_helper> cmdmap;
256
257         cmdmap["-c"] = parse_class;
258         cmdmap["-f"] = parse_force;
259         cmdmap["-s"] = parse_syntaxfile;
260         cmdmap["-help"] = parse_help;
261         cmdmap["--help"] = parse_help;
262         cmdmap["-sysdir"] = parse_sysdir;
263         cmdmap["-userdir"] = parse_userdir;
264
265         for (int i = 1; i < argc; ++i) {
266                 std::map<string, cmd_helper>::const_iterator it
267                         = cmdmap.find(argv[i]);
268
269                 // don't complain if not found - may be parsed later
270                 if (it == cmdmap.end())
271                         continue;
272
273                 string arg((i + 1 < argc) ? argv[i + 1] : "");
274                 string arg2((i + 2 < argc) ? argv[i + 2] : "");
275
276                 int const remove = 1 + it->second(arg, arg2);
277
278                 // Now, remove used arguments by shifting
279                 // the following ones remove places down.
280                 argc -= remove;
281                 for (int j = i; j < argc; ++j)
282                         argv[j] = argv[j + remove];
283                 --i;
284         }
285 }
286
287
288 // path of the parsed file
289 string masterFilePath;
290
291 } // anonymous namespace
292
293
294 string getMasterFilePath()
295 {
296         return masterFilePath;
297 }
298
299
300 void tex2lyx(std::istream &is, std::ostream &os)
301 {
302         Parser p(is);
303         //p.dump();
304
305         stringstream ss;
306         LyXTextClass textclass = parse_preamble(p, ss, documentclass);
307
308         active_environments.push_back("document");
309         Context context(true, textclass);
310         parse_text(p, ss, FLAG_END, true, context);
311         context.check_end_layout(ss);
312         ss << "\n\\end_body\n\\end_document\n";
313         active_environments.pop_back();
314         ss.seekg(0);
315         os << ss.str();
316 #ifdef TEST_PARSER
317         p.reset();
318         ofstream parsertest("parsertest.tex");
319         while (p.good())
320                 parsertest << p.get_token().asInput();
321         // <origfile> and parsertest.tex should now have identical content
322 #endif
323 }
324
325
326 bool tex2lyx(string const &infilename, string const &outfilename)
327 {
328         if (!(IsFileReadable(infilename) && IsFileWriteable(outfilename))) {
329                 return false;
330         }
331         if (!overwrite_files && IsFileReadable(outfilename)) {
332                 cerr << "Not overwriting existing file " << outfilename << "\n";
333                 return false;
334         }
335         ifstream is(infilename.c_str());
336         ofstream os(outfilename.c_str());
337 #ifdef FILEDEBUG
338         cerr << "File: " << infilename << "\n";
339 #endif
340         tex2lyx(is, os);
341         return true;
342 }
343
344
345 int main(int argc, char * argv[])
346 {
347         easyParse(argc, argv);
348
349         if (argc <= 1) {
350                 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
351                           "See tex2lyx -help." << endl;
352                 return 2;
353         }
354
355         lyx::support::os::init(&argc, &argv);
356         lyx::support::setLyxPaths();
357
358         string const system_syntaxfile = lyx::support::LibFileSearch("reLyX", "syntax.default");
359         if (system_syntaxfile.empty()) {
360                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
361                 exit(1);
362         }
363         read_syntaxfile(system_syntaxfile);
364         if (!syntaxfile.empty())
365                 read_syntaxfile(syntaxfile);
366
367         if (!IsFileReadable(argv[1])) {
368                 cerr << "Could not open input file \"" << argv[1]
369                      << "\" for reading." << endl;
370                 return 2;
371         }
372
373         if (lyx::support::AbsolutePath(argv[1]))
374                 masterFilePath = lyx::support::OnlyPath(argv[1]);
375         else
376                 masterFilePath = lyx::support::getcwd();
377
378         ifstream is(argv[1]);
379         tex2lyx(is, cout);
380
381         return 0;
382 }
383
384 // }])