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