]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
05fe8e31cbba6583cee74a2e22037cdb6e26fddf
[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 if (arg == "item")
193                                 arguments.push_back(item);
194                         else
195                                 arguments.push_back(verbatim);
196                 } else {
197                         p.getArg('[', ']');
198                         arguments.push_back(optional);
199                 }
200         }
201         commands[command] = arguments;
202 }
203
204
205 /*!
206  * Read a class of environments from the syntax file
207  */
208 void read_environment(Parser & p, string const & begin,
209                       CommandMap & environments)
210 {
211         string environment;
212         while (p.good()) {
213                 Token const & t = p.get_token();
214                 if (t.cat() == catLetter)
215                         environment += t.asInput();
216                 else if (!environment.empty()) {
217                         p.putback();
218                         read_command(p, environment, environments);
219                         environment.erase();
220                 }
221                 if (t.cat() == catEscape && t.asInput() == "\\end") {
222                         string const end = p.getArg('{', '}');
223                         if (end == begin)
224                                 return;
225                 }
226         }
227 }
228
229
230 /*!
231  * Read a list of TeX commands from a reLyX compatible syntax file.
232  * Since this list is used after all commands that have a LyX counterpart
233  * are handled, it does not matter that the "syntax.default" file
234  * has almost all of them listed. For the same reason the reLyX-specific
235  * reLyXre environment is ignored.
236  */
237 void read_syntaxfile(FileName const & file_name)
238 {
239         ifdocstream is(file_name.toFilesystemEncoding().c_str());
240         if (!is.good()) {
241                 cerr << "Could not open syntax file \"" << file_name
242                      << "\" for reading." << endl;
243                 exit(2);
244         }
245         // We can use our TeX parser, since the syntax of the layout file is
246         // modeled after TeX.
247         // Unknown tokens are just silently ignored, this helps us to skip some
248         // reLyX specific things.
249         Parser p(is);
250         while (p.good()) {
251                 Token const & t = p.get_token();
252                 if (t.cat() == catEscape) {
253                         string const command = t.asInput();
254                         if (command == "\\begin") {
255                                 string const name = p.getArg('{', '}');
256                                 if (name == "environments" || name == "reLyXre")
257                                         // We understand "reLyXre", but it is
258                                         // not as powerful as "environments".
259                                         read_environment(p, name,
260                                                 known_environments);
261                                 else if (name == "mathenvironments")
262                                         read_environment(p, name,
263                                                 known_math_environments);
264                         } else {
265                                 read_command(p, command, known_commands);
266                         }
267                 }
268         }
269 }
270
271
272 string documentclass;
273 string default_encoding;
274 string syntaxfile;
275 bool overwrite_files = false;
276 int error_code = 0;
277
278 /// return the number of arguments consumed
279 typedef int (*cmd_helper)(string const &, string const &);
280
281
282 int parse_help(string const &, string const &)
283 {
284         cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
285                 "Options:\n"
286                 "\t-c textclass       Declare the textclass.\n"
287                 "\t-e encoding        Set the default encoding (latex name).\n"
288                 "\t-f                 Force overwrite of .lyx files.\n"
289                 "\t-help              Print this message and quit.\n"
290                 "\t-n                 translate a noweb (aka literate programming) file.\n"
291                 "\t-s syntaxfile      read additional syntax file.\n" 
292                 "\t-sysdir dir        Set system directory to DIR.\n"
293                 "\t-userdir DIR       Set user directory to DIR."
294              << endl;
295         exit(error_code);
296 }
297
298
299 void error_message(string const & message)
300 {
301         cerr << "tex2lyx: " << message << "\n\n";
302         error_code = 1;
303         parse_help(string(), string());
304 }
305
306
307 int parse_class(string const & arg, string const &)
308 {
309         if (arg.empty())
310                 error_message("Missing textclass string after -c switch");
311         documentclass = arg;
312         return 1;
313 }
314
315
316 int parse_encoding(string const & arg, string const &)
317 {
318         if (arg.empty())
319                 error_message("Missing encoding string after -e switch");
320         default_encoding = arg;
321         return 1;
322 }
323
324
325 int parse_syntaxfile(string const & arg, string const &)
326 {
327         if (arg.empty())
328                 error_message("Missing syntaxfile string after -s switch");
329         syntaxfile = internal_path(arg);
330         return 1;
331 }
332
333
334 // Filled with the command line arguments "foo" of "-sysdir foo" or
335 // "-userdir foo".
336 string cl_system_support;
337 string cl_user_support;
338
339
340 int parse_sysdir(string const & arg, string const &)
341 {
342         if (arg.empty())
343                 error_message("Missing directory for -sysdir switch");
344         cl_system_support = internal_path(arg);
345         return 1;
346 }
347
348
349 int parse_userdir(string const & arg, string const &)
350 {
351         if (arg.empty())
352                 error_message("Missing directory for -userdir switch");
353         cl_user_support = internal_path(arg);
354         return 1;
355 }
356
357
358 int parse_force(string const &, string const &)
359 {
360         overwrite_files = true;
361         return 0;
362 }
363
364
365 int parse_noweb(string const &, string const &)
366 {
367         noweb_mode = true;
368         return 0;
369 }
370
371
372 void easyParse(int & argc, char * argv[])
373 {
374         map<string, cmd_helper> cmdmap;
375
376         cmdmap["-c"] = parse_class;
377         cmdmap["-e"] = parse_encoding;
378         cmdmap["-f"] = parse_force;
379         cmdmap["-s"] = parse_syntaxfile;
380         cmdmap["-help"] = parse_help;
381         cmdmap["--help"] = parse_help;
382         cmdmap["-n"] = parse_noweb;
383         cmdmap["-sysdir"] = parse_sysdir;
384         cmdmap["-userdir"] = parse_userdir;
385
386         for (int i = 1; i < argc; ++i) {
387                 map<string, cmd_helper>::const_iterator it
388                         = cmdmap.find(argv[i]);
389
390                 // don't complain if not found - may be parsed later
391                 if (it == cmdmap.end()) {
392                         if (argv[i][0] == '-')
393                                 error_message(string("Unknown option `") + argv[i] + "'.");
394                         else
395                                 continue;
396                 }
397
398                 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
399                 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
400
401                 int const remove = 1 + it->second(arg, arg2);
402
403                 // Now, remove used arguments by shifting
404                 // the following ones remove places down.
405                 os::remove_internal_args(i, remove);
406                 argc -= remove;
407                 for (int j = i; j < argc; ++j)
408                         argv[j] = argv[j + remove];
409                 --i;
410         }
411 }
412
413
414 // path of the first parsed file
415 string masterFilePath;
416 // path of the currently parsed file
417 string parentFilePath;
418
419 } // anonymous namespace
420
421
422 string getMasterFilePath()
423 {
424         return masterFilePath;
425 }
426
427 string getParentFilePath()
428 {
429         return parentFilePath;
430 }
431
432
433 namespace {
434
435 /*!
436  *  Reads tex input from \a is and writes lyx output to \a os.
437  *  Uses some common settings for the preamble, so this should only
438  *  be used more than once for included documents.
439  *  Caution: Overwrites the existing preamble settings if the new document
440  *  contains a preamble.
441  *  You must ensure that \p parentFilePath is properly set before calling
442  *  this function!
443  */
444 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
445 {
446         Parser p(is);
447         if (!encoding.empty())
448                 p.setEncoding(encoding);
449         //p.dump();
450
451         stringstream ss;
452         TeX2LyXDocClass textclass;
453         parse_preamble(p, ss, documentclass, textclass);
454
455         active_environments.push_back("document");
456         Context context(true, textclass);
457         parse_text(p, ss, FLAG_END, true, context);
458         if (Context::empty)
459                 // Empty document body. LyX needs at least one paragraph.
460                 context.check_layout(ss);
461         context.check_end_layout(ss);
462         ss << "\n\\end_body\n\\end_document\n";
463         active_environments.pop_back();
464         ss.seekg(0);
465         os << ss.str();
466 #ifdef TEST_PARSER
467         p.reset();
468         ofdocstream parsertest("parsertest.tex");
469         while (p.good())
470                 parsertest << p.get_token().asInput();
471         // <origfile> and parsertest.tex should now have identical content
472 #endif
473 }
474
475
476 /// convert TeX from \p infilename to LyX and write it to \p os
477 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
478 {
479         ifdocstream is;
480         // forbid buffering on this stream
481         is.rdbuf()->pubsetbuf(0,0);
482         is.open(infilename.toFilesystemEncoding().c_str());
483         if (!is.good()) {
484                 cerr << "Could not open input file \"" << infilename
485                      << "\" for reading." << endl;
486                 return false;
487         }
488         string const oldParentFilePath = parentFilePath;
489         parentFilePath = onlyPath(infilename.absFileName());
490         tex2lyx(is, os, encoding);
491         parentFilePath = oldParentFilePath;
492         return true;
493 }
494
495 } // anonymous namespace
496
497
498 bool tex2lyx(string const & infilename, FileName const & outfilename, 
499              string const & encoding)
500 {
501         if (outfilename.isReadableFile()) {
502                 if (overwrite_files) {
503                         cerr << "Overwriting existing file "
504                              << outfilename << endl;
505                 } else {
506                         cerr << "Not overwriting existing file "
507                              << outfilename << endl;
508                         return false;
509                 }
510         } else {
511                 cerr << "Creating file " << outfilename << endl;
512         }
513         ofstream os(outfilename.toFilesystemEncoding().c_str());
514         if (!os.good()) {
515                 cerr << "Could not open output file \"" << outfilename
516                      << "\" for writing." << endl;
517                 return false;
518         }
519 #ifdef FILEDEBUG
520         cerr << "Input file: " << infilename << "\n";
521         cerr << "Output file: " << outfilename << "\n";
522 #endif
523         return tex2lyx(FileName(infilename), os, encoding);
524 }
525
526 } // namespace lyx
527
528
529 int main(int argc, char * argv[])
530 {
531         using namespace lyx;
532
533         //setlocale(LC_CTYPE, "");
534
535         lyxerr.setStream(cerr);
536
537         os::init(argc, argv);
538
539         easyParse(argc, argv);
540
541         if (argc <= 1) 
542                 error_message("Not enough arguments.");
543
544         try {
545                 init_package(internal_path(os::utf8_argv(0)),
546                              cl_system_support, cl_user_support,
547                              top_build_dir_is_two_levels_up);
548         } catch (ExceptionMessage const & message) {
549                 cerr << to_utf8(message.title_) << ":\n"
550                      << to_utf8(message.details_) << endl;
551                 if (message.type_ == ErrorException)
552                         exit(1);
553         }
554
555         // Now every known option is parsed. Look for input and output
556         // file name (the latter is optional).
557         string infilename = internal_path(os::utf8_argv(1));
558         infilename = makeAbsPath(infilename).absFileName();
559
560         string outfilename;
561         if (argc > 2) {
562                 outfilename = internal_path(os::utf8_argv(2));
563                 if (outfilename != "-")
564                         outfilename = makeAbsPath(outfilename).absFileName();
565         } else
566                 outfilename = changeExtension(infilename, ".lyx");
567
568         // Read the syntax tables
569         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
570         if (system_syntaxfile.empty()) {
571                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
572                 exit(1);
573         }
574         read_syntaxfile(system_syntaxfile);
575         if (!syntaxfile.empty())
576                 read_syntaxfile(makeAbsPath(syntaxfile));
577
578         // Read the encodings table.
579         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
580         if (symbols_path.empty()) {
581                 cerr << "Error: Could not find file \"unicodesymbols\"." 
582                      << endl;
583                 exit(1);
584         }
585         FileName const enc_path = libFileSearch(string(), "encodings");
586         if (enc_path.empty()) {
587                 cerr << "Error: Could not find file \"encodings\"." 
588                      << endl;
589                 exit(1);
590         }
591         encodings.read(enc_path, symbols_path);
592         if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
593                 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
594
595         // The real work now.
596         masterFilePath = onlyPath(infilename);
597         parentFilePath = masterFilePath;
598         if (outfilename == "-") {
599                 if (tex2lyx(FileName(infilename), cout, default_encoding))
600                         return EXIT_SUCCESS;
601                 else
602                         return EXIT_FAILURE;
603         } else {
604                 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
605                         return EXIT_SUCCESS;
606                 else
607                         return EXIT_FAILURE;
608         }
609 }
610
611 // }])