]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/tex2lyx.cpp
Get rid of all-insets-toggle and explain how to replace it with inset-forall.
[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 const & getMessages(std::string const &)
48 {
49         return messages_;
50 }
51
52
53 Messages const & getGuiMessages()
54 {
55         return messages_;
56 }
57
58
59 // Keep the linker happy on Windows
60 void lyx_exit(int)
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 = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
385                 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
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                 os::remove_internal_args(i, remove);
392                 argc -= remove;
393                 for (int j = i; j < argc; ++j)
394                         argv[j] = argv[j + remove];
395                 --i;
396         }
397 }
398
399
400 // path of the first parsed file
401 string masterFilePath;
402 // path of the currently parsed file
403 string parentFilePath;
404
405 } // anonymous namespace
406
407
408 string getMasterFilePath()
409 {
410         return masterFilePath;
411 }
412
413 string getParentFilePath()
414 {
415         return parentFilePath;
416 }
417
418
419 namespace {
420
421 /*!
422  *  Reads tex input from \a is and writes lyx output to \a os.
423  *  Uses some common settings for the preamble, so this should only
424  *  be used more than once for included documents.
425  *  Caution: Overwrites the existing preamble settings if the new document
426  *  contains a preamble.
427  *  You must ensure that \p parentFilePath is properly set before calling
428  *  this function!
429  */
430 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
431 {
432         Parser p(is);
433         if (!encoding.empty())
434                 p.setEncoding(encoding);
435         //p.dump();
436
437         stringstream ss;
438         TeX2LyXDocClass textclass;
439         parse_preamble(p, ss, documentclass, textclass);
440
441         active_environments.push_back("document");
442         Context context(true, textclass);
443         parse_text(p, ss, FLAG_END, true, context);
444         if (Context::empty)
445                 // Empty document body. LyX needs at least one paragraph.
446                 context.check_layout(ss);
447         context.check_end_layout(ss);
448         ss << "\n\\end_body\n\\end_document\n";
449         active_environments.pop_back();
450         ss.seekg(0);
451         os << ss.str();
452 #ifdef TEST_PARSER
453         p.reset();
454         ofdocstream parsertest("parsertest.tex");
455         while (p.good())
456                 parsertest << p.get_token().asInput();
457         // <origfile> and parsertest.tex should now have identical content
458 #endif
459 }
460
461
462 /// convert TeX from \p infilename to LyX and write it to \p os
463 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
464 {
465         ifdocstream is;
466         // forbid buffering on this stream
467         is.rdbuf()->pubsetbuf(0,0);
468         is.open(infilename.toFilesystemEncoding().c_str());
469         if (!is.good()) {
470                 cerr << "Could not open input file \"" << infilename
471                      << "\" for reading." << endl;
472                 return false;
473         }
474         string const oldParentFilePath = parentFilePath;
475         parentFilePath = onlyPath(infilename.absFilename());
476         tex2lyx(is, os, encoding);
477         parentFilePath = oldParentFilePath;
478         return true;
479 }
480
481 } // anonymous namespace
482
483
484 bool tex2lyx(string const & infilename, FileName const & outfilename, 
485              string const & encoding)
486 {
487         if (outfilename.isReadableFile()) {
488                 if (overwrite_files) {
489                         cerr << "Overwriting existing file "
490                              << outfilename << endl;
491                 } else {
492                         cerr << "Not overwriting existing file "
493                              << outfilename << endl;
494                         return false;
495                 }
496         } else {
497                 cerr << "Creating file " << outfilename << endl;
498         }
499         ofstream os(outfilename.toFilesystemEncoding().c_str());
500         if (!os.good()) {
501                 cerr << "Could not open output file \"" << outfilename
502                      << "\" for writing." << endl;
503                 return false;
504         }
505 #ifdef FILEDEBUG
506         cerr << "Input file: " << infilename << "\n";
507         cerr << "Output file: " << outfilename << "\n";
508 #endif
509         return tex2lyx(FileName(infilename), os, encoding);
510 }
511
512 } // namespace lyx
513
514
515 int main(int argc, char * argv[])
516 {
517         using namespace lyx;
518
519         //setlocale(LC_CTYPE, "");
520
521         lyxerr.setStream(cerr);
522
523         os::init(argc, argv);
524
525         easyParse(argc, argv);
526
527         if (argc <= 1) 
528                 error_message("Not enough arguments.");
529
530         try {
531                 init_package(internal_path(os::utf8_argv(0)),
532                              cl_system_support, cl_user_support,
533                              top_build_dir_is_two_levels_up);
534         } catch (ExceptionMessage const & message) {
535                 cerr << to_utf8(message.title_) << ":\n"
536                      << to_utf8(message.details_) << endl;
537                 if (message.type_ == ErrorException)
538                         exit(1);
539         }
540
541         // Now every known option is parsed. Look for input and output
542         // file name (the latter is optional).
543         string infilename = internal_path(os::utf8_argv(1));
544         infilename = makeAbsPath(infilename).absFilename();
545
546         string outfilename;
547         if (argc > 2) {
548                 outfilename = internal_path(os::utf8_argv(2));
549                 if (outfilename != "-")
550                         outfilename = makeAbsPath(outfilename).absFilename();
551         } else
552                 outfilename = changeExtension(infilename, ".lyx");
553
554         // Read the syntax tables
555         FileName const system_syntaxfile = libFileSearch("", "syntax.default");
556         if (system_syntaxfile.empty()) {
557                 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
558                 exit(1);
559         }
560         read_syntaxfile(system_syntaxfile);
561         if (!syntaxfile.empty())
562                 read_syntaxfile(makeAbsPath(syntaxfile));
563
564         // Read the encodings table.
565         FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
566         if (symbols_path.empty()) {
567                 cerr << "Error: Could not find file \"unicodesymbols\"." 
568                      << endl;
569                 exit(1);
570         }
571         FileName const enc_path = libFileSearch(string(), "encodings");
572         if (enc_path.empty()) {
573                 cerr << "Error: Could not find file \"encodings\"." 
574                      << endl;
575                 exit(1);
576         }
577         encodings.read(enc_path, symbols_path);
578         if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
579                 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
580
581         // The real work now.
582         masterFilePath = onlyPath(infilename);
583         parentFilePath = masterFilePath;
584         if (outfilename == "-") {
585                 if (tex2lyx(FileName(infilename), cout, default_encoding))
586                         return EXIT_SUCCESS;
587                 else
588                         return EXIT_FAILURE;
589         } else {
590                 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
591                         return EXIT_SUCCESS;
592                 else
593                         return EXIT_FAILURE;
594         }
595 }
596
597 // }])