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