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