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