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