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