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