]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.C
add config.h
[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/ExceptionMessage.h"
27 #include "support/os.h"
28 #include "support/package.h"
29 #include "support/unicode.h"
30
31 #include <boost/function.hpp>
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/filesystem/path.hpp>
34
35 #include <cctype>
36 #include <fstream>
37 #include <iostream>
38 #include <string>
39 #include <sstream>
40 #include <vector>
41 #include <map>
42
43
44 namespace lyx {
45
46 using std::endl;
47 using std::cout;
48 using std::cerr;
49 using std::getline;
50
51 using std::ifstream;
52 using std::ofstream;
53 using std::istringstream;
54 using std::ostringstream;
55 using std::stringstream;
56 using std::string;
57 using std::vector;
58 using std::map;
59
60 using support::changeExtension;
61 using support::FileName;
62 using support::isStrUnsignedInt;
63 using support::ltrim;
64 using support::makeAbsPath;
65 using support::onlyPath;
66 using support::rtrim;
67 using support::isFileReadable;
68
69 namespace fs = boost::filesystem;
70
71
72 IconvProcessor & utf8ToUcs4()
73 {
74         static IconvProcessor iconv(ucs4_codeset, "UTF-8");
75         return iconv;
76 }
77
78
79 // Hacks to allow the thing to link in the lyxlayout stuff
80 LyXErr lyxerr(std::cerr.rdbuf());
81
82
83 string const trim(string const & a, char const * p)
84 {
85         // BOOST_ASSERT(p);
86
87         if (a.empty() || !*p)
88                 return a;
89
90         string::size_type r = a.find_last_not_of(p);
91         string::size_type l = a.find_first_not_of(p);
92
93         // Is this the minimal test? (lgb)
94         if (r == string::npos && l == string::npos)
95                 return string();
96
97         return a.substr(l, r - l + 1);
98 }
99
100
101 void split(string const & s, vector<string> & result, char delim)
102 {
103         //cerr << "split 1: '" << s << "'\n";
104         istringstream is(s);
105         string t;
106         while (getline(is, t, delim))
107                 result.push_back(t);
108         //cerr << "split 2\n";
109 }
110
111
112 string join(vector<string> const & input, char const * delim)
113 {
114         ostringstream os;
115         for (size_t i = 0; i < input.size(); ++i) {
116                 if (i)
117                         os << delim;
118                 os << input[i];
119         }
120         return os.str();
121 }
122
123
124 char const * const * is_known(string const & str, char const * const * what)
125 {
126         for ( ; *what; ++what)
127                 if (str == *what)
128                         return what;
129         return 0;
130 }
131
132
133
134 // current stack of nested environments
135 vector<string> active_environments;
136
137
138 string active_environment()
139 {
140         return active_environments.empty() ? string() : active_environments.back();
141 }
142
143
144 CommandMap known_commands;
145 CommandMap known_environments;
146 CommandMap known_math_environments;
147
148
149 void add_known_command(string const & command, string const & o1,
150                        bool o2)
151 {
152         // We have to handle the following cases:
153         // definition                      o1    o2    invocation result
154         // \newcommand{\foo}{bar}          ""    false \foo       bar
155         // \newcommand{\foo}[1]{bar #1}    "[1]" false \foo{x}    bar x
156         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo       bar
157         // \newcommand{\foo}[1][]{bar #1}  "[1]" true  \foo[x]    bar x
158         // \newcommand{\foo}[1][x]{bar #1} "[1]" true  \foo[x]    bar x
159         unsigned int nargs = 0;
160         vector<ArgumentType> arguments;
161         string const opt1 = rtrim(ltrim(o1, "["), "]");
162         if (isStrUnsignedInt(opt1)) {
163                 // The command has arguments
164                 nargs = convert<unsigned int>(opt1);
165                 if (nargs > 0 && o2) {
166                         // The first argument is optional
167                         arguments.push_back(optional);
168                         --nargs;
169                 }
170         }
171         for (unsigned int i = 0; i < nargs; ++i)
172                 arguments.push_back(required);
173         known_commands[command] = arguments;
174 }
175
176
177 bool noweb_mode = false;
178
179
180 namespace {
181
182
183 /*!
184  * Read one command definition from the syntax file
185  */
186 void read_command(Parser & p, string command, CommandMap & commands) {
187         if (p.next_token().asInput() == "*") {
188                 p.get_token();
189                 command += '*';
190         }
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         commands[command] = arguments;
206 }
207
208
209 /*!
210  * Read a class of environments from the syntax file
211  */
212 void read_environment(Parser & p, string const & begin,
213                       CommandMap & environments)
214 {
215         string environment;
216         while (p.good()) {
217                 Token const & t = p.get_token();
218                 if (t.cat() == catLetter)
219                         environment += t.asInput();
220                 else if (!environment.empty()) {
221                         p.putback();
222                         read_command(p, environment, environments);
223                         environment.erase();
224                 }
225                 if (t.cat() == catEscape && t.asInput() == "\\end") {
226                         string const end = p.getArg('{', '}');
227                         if (end == begin)
228                                 return;
229                 }
230         }
231 }
232
233
234 /*!
235  * Read a list of TeX commands from a reLyX compatible syntax file.
236  * Since this list is used after all commands that have a LyX counterpart
237  * are handled, it does not matter that the "syntax.default" file
238  * has almost all of them listed. For the same reason the reLyX-specific
239  * reLyXre environment is ignored.
240  */
241 void read_syntaxfile(FileName const & file_name)
242 {
243         ifstream is(file_name.toFilesystemEncoding().c_str());
244         if (!is.good()) {
245                 cerr << "Could not open syntax file \"" << file_name
246                      << "\" for reading." << endl;
247                 exit(2);
248         }
249         // We can use our TeX parser, since the syntax of the layout file is
250         // modeled after TeX.
251         // Unknown tokens are just silently ignored, this helps us to skip some
252         // reLyX specific things.
253         Parser p(is);
254         while (p.good()) {
255                 Token const & t = p.get_token();
256                 if (t.cat() == catEscape) {
257                         string const command = t.asInput();
258                         if (command == "\\begin") {
259                                 string const name = p.getArg('{', '}');
260                                 if (name == "environments" || name == "reLyXre")
261                                         // We understand "reLyXre", but it is
262                                         // not as powerful as "environments".
263                                         read_environment(p, name,
264                                                 known_environments);
265                                 else if (name == "mathenvironments")
266                                         read_environment(p, name,
267                                                 known_math_environments);
268                         } else {
269                                 read_command(p, command, known_commands);
270                         }
271                 }
272         }
273 }
274
275
276 string documentclass;
277 string syntaxfile;
278 bool overwrite_files = false;
279
280
281 /// return the number of arguments consumed
282 typedef boost::function<int(string const &, string const &)> cmd_helper;
283
284
285 int parse_help(string const &, string const &)
286 {
287         cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
288                 "Command line switches (case sensitive):\n"
289                 "\t-help              summarize tex2lyx usage\n"
290                 "\t-f                 Force creation of .lyx files even if they exist already\n"
291                 "\t-userdir dir       try to set user directory to dir\n"
292                 "\t-sysdir dir        try to set system directory to dir\n"
293                 "\t-c textclass       declare the textclass\n"
294                 "\t-n                 translate a noweb (aka literate programming) file.\n"
295                 "\t-s syntaxfile      read additional syntax file" << endl;
296         exit(0);
297 }
298
299
300 int parse_class(string const & arg, string const &)
301 {
302         if (arg.empty()) {
303                 cerr << "Missing textclass string after -c switch" << endl;
304                 exit(1);
305         }
306         documentclass = arg;
307         return 1;
308 }
309
310
311 int parse_syntaxfile(string const & arg, string const &)
312 {
313         if (arg.empty()) {
314                 cerr << "Missing syntaxfile string after -s switch" << endl;
315                 exit(1);
316         }
317         syntaxfile = arg;
318         return 1;
319 }
320
321
322 // Filled with the command line arguments "foo" of "-sysdir foo" or
323 // "-userdir foo".
324 string cl_system_support;
325 string cl_user_support;
326
327
328 int parse_sysdir(string const & arg, string const &)
329 {
330         if (arg.empty()) {
331                 cerr << "Missing directory for -sysdir switch" << endl;
332                 exit(1);
333         }
334         cl_system_support = arg;
335         return 1;
336 }
337
338
339 int parse_userdir(string const & arg, string const &)
340 {
341         if (arg.empty()) {
342                 cerr << "Missing directory for -userdir switch" << endl;
343                 exit(1);
344         }
345         cl_user_support = arg;
346         return 1;
347 }
348
349
350 int parse_force(string const &, string const &)
351 {
352         overwrite_files = true;
353         return 0;
354 }
355
356
357 int parse_noweb(string const &, string const &)
358 {
359         noweb_mode = true;
360         return 0;
361 }
362
363
364 void easyParse(int & argc, char * argv[])
365 {
366         map<string, cmd_helper> cmdmap;
367
368         cmdmap["-c"] = parse_class;
369         cmdmap["-f"] = parse_force;
370         cmdmap["-s"] = parse_syntaxfile;
371         cmdmap["-help"] = parse_help;
372         cmdmap["--help"] = parse_help;
373         cmdmap["-n"] = parse_noweb;
374         cmdmap["-sysdir"] = parse_sysdir;
375         cmdmap["-userdir"] = parse_userdir;
376
377         for (int i = 1; i < argc; ++i) {
378                 std::map<string, cmd_helper>::const_iterator it
379                         = cmdmap.find(argv[i]);
380
381                 // don't complain if not found - may be parsed later
382                 if (it == cmdmap.end())
383                         continue;
384
385                 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
386                 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
387
388                 int const remove = 1 + it->second(arg, arg2);
389
390                 // Now, remove used arguments by shifting
391                 // the following ones remove places down.
392                 argc -= remove;
393                 for (int j = i; j < argc; ++j)
394                         argv[j] = argv[j + remove];
395                 --i;
396         }
397 }
398
399
400 // path of the first parsed file
401 string masterFilePath;
402 // path of the currently parsed file
403 string parentFilePath;
404
405 } // anonymous namespace
406
407
408 string getMasterFilePath()
409 {
410         return masterFilePath;
411 }
412
413 string getParentFilePath()
414 {
415         return parentFilePath;
416 }
417
418
419 namespace {
420
421 /*!
422  *  Reads tex input from \a is and writes lyx output to \a os.
423  *  Uses some common settings for the preamble, so this should only
424  *  be used more than once for included documents.
425  *  Caution: Overwrites the existing preamble settings if the new document
426  *  contains a preamble.
427  *  You must ensure that \p parentFilePath is properly set before calling
428  *  this function!
429  */
430 void tex2lyx(std::istream &is, std::ostream &os)
431 {
432         Parser p(is);
433         //p.dump();
434
435         stringstream ss;
436         LyXTextClass textclass = parse_preamble(p, ss, documentclass);
437
438         active_environments.push_back("document");
439         Context context(true, textclass);
440         parse_text(p, ss, FLAG_END, true, context);
441         if (Context::empty)
442                 // Empty document body. LyX needs at least one paragraph.
443                 context.check_layout(ss);
444         context.check_end_layout(ss);
445         ss << "\n\\end_body\n\\end_document\n";
446         active_environments.pop_back();
447         ss.seekg(0);
448         os << ss.str();
449 #ifdef TEST_PARSER
450         p.reset();
451         ofstream parsertest("parsertest.tex");
452         while (p.good())
453                 parsertest << p.get_token().asInput();
454         // <origfile> and parsertest.tex should now have identical content
455 #endif
456 }
457
458
459 /// convert TeX from \p infilename to LyX and write it to \p os
460 bool tex2lyx(FileName const & infilename, std::ostream &os)
461 {
462         ifstream is(infilename.toFilesystemEncoding().c_str());
463         if (!is.good()) {
464                 cerr << "Could not open input file \"" << infilename
465                      << "\" for reading." << endl;
466                 return false;
467         }
468         string const oldParentFilePath = parentFilePath;
469         parentFilePath = onlyPath(infilename.absFilename());
470         tex2lyx(is, os);
471         parentFilePath = oldParentFilePath;
472         return true;
473 }
474
475 } // anonymous namespace
476
477
478 bool tex2lyx(string const &infilename, FileName const &outfilename)
479 {
480         if (isFileReadable(outfilename)) {
481                 if (overwrite_files) {
482                         cerr << "Overwriting existing file "
483                              << outfilename << endl;
484                 } else {
485                         cerr << "Not overwriting existing file "
486                              << outfilename << endl;
487                         return false;
488                 }
489         } else {
490                 cerr << "Creating file " << outfilename << endl;
491         }
492         ofstream os(outfilename.toFilesystemEncoding().c_str());
493         if (!os.good()) {
494                 cerr << "Could not open output file \"" << outfilename
495                      << "\" for writing." << endl;
496                 return false;
497         }
498 #ifdef FILEDEBUG
499         cerr << "Input file: " << infilename << "\n";
500         cerr << "Output file: " << outfilename << "\n";
501 #endif
502         return tex2lyx(FileName(infilename), os);
503 }
504
505 } // namespace lyx
506
507
508 int main(int argc, char * argv[])
509 {
510         using namespace lyx;
511         fs::path::default_name_check(fs::no_check);
512
513         easyParse(argc, argv);
514
515         if (argc <= 1) {
516                 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
517                           "See tex2lyx -help." << endl;
518                 return 2;
519         }
520
521         lyx::support::os::init(argc, argv);
522
523         try { support::init_package(to_utf8(from_local8bit(argv[0])),
524                 cl_system_support, cl_user_support,
525                 support::top_build_dir_is_two_levels_up);
526         } catch (support::ExceptionMessage const & message) {
527                 cerr << to_utf8(message.title_) << ":\n"
528                         << to_utf8(message.details_) << endl;
529                 if (message.type_ == support::ErrorException)
530                         exit(1);
531         }
532
533         // Now every known option is parsed. Look for input and output
534         // file name (the latter is optional).
535         string const infilename = makeAbsPath(to_utf8(from_local8bit(argv[1]))).absFilename();
536         string outfilename;
537         if (argc > 2) {
538                 outfilename = to_utf8(from_local8bit(argv[2]));
539                 if (outfilename != "-")
540                         outfilename = makeAbsPath(to_utf8(from_local8bit(argv[2]))).absFilename();
541         } else
542                 outfilename = changeExtension(infilename, ".lyx");
543
544         FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
545         if (system_syntaxfile.empty()) {
546                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
547                 exit(1);
548         }
549         read_syntaxfile(system_syntaxfile);
550         if (!syntaxfile.empty())
551                 read_syntaxfile(makeAbsPath(syntaxfile));
552
553         masterFilePath = onlyPath(infilename);
554         parentFilePath = masterFilePath;
555
556         if (outfilename == "-") {
557                 if (tex2lyx(FileName(infilename), cout))
558                         return EXIT_SUCCESS;
559                 else
560                         return EXIT_FAILURE;
561         } else {
562                 if (tex2lyx(infilename, FileName(outfilename)))
563                         return EXIT_SUCCESS;
564                 else
565                         return EXIT_FAILURE;
566         }
567 }
568
569 // }])