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