3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
19 #include "lyxtextclass.h"
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"
29 #include <boost/function.hpp>
30 #include <boost/filesystem/operations.hpp>
31 #include <boost/filesystem/path.hpp>
48 using std::istringstream;
49 using std::ostringstream;
50 using std::stringstream;
55 using lyx::support::ChangeExtension;
56 using lyx::support::isStrUnsignedInt;
57 using lyx::support::ltrim;
58 using lyx::support::MakeAbsPath;
59 using lyx::support::OnlyPath;
60 using lyx::support::rtrim;
61 using lyx::support::IsFileReadable;
63 namespace fs = boost::filesystem;
66 // Hacks to allow the thing to link in the lyxlayout stuff
67 LyXErr lyxerr(std::cerr.rdbuf());
70 string const trim(string const & a, char const * p)
77 string::size_type r = a.find_last_not_of(p);
78 string::size_type l = a.find_first_not_of(p);
80 // Is this the minimal test? (lgb)
81 if (r == string::npos && l == string::npos)
84 return a.substr(l, r - l + 1);
88 void split(string const & s, vector<string> & result, char delim)
90 //cerr << "split 1: '" << s << "'\n";
93 while (getline(is, t, delim))
95 //cerr << "split 2\n";
99 string join(vector<string> const & input, char const * delim)
102 for (size_t i = 0; i < input.size(); ++i) {
111 char const * const * is_known(string const & str, char const * const * what)
113 for ( ; *what; ++what)
121 // current stack of nested environments
122 vector<string> active_environments;
125 string active_environment()
127 return active_environments.empty() ? string() : active_environments.back();
131 CommandMap known_commands;
132 CommandMap known_environments;
133 CommandMap known_math_environments;
136 void add_known_command(string const & command, string const & o1,
139 // We have to handle the following cases:
140 // definition o1 o2 invocation result
141 // \newcommand{\foo}{bar} "" false \foo bar
142 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
143 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
144 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
145 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
146 unsigned int nargs = 0;
147 vector<ArgumentType> arguments;
148 string const opt1 = rtrim(ltrim(o1, "["), "]");
149 if (isStrUnsignedInt(opt1)) {
150 // The command has arguments
151 nargs = convert<unsigned int>(opt1);
152 if (nargs > 0 && o2) {
153 // The first argument is optional
154 arguments.push_back(optional);
158 for (unsigned int i = 0; i < nargs; ++i)
159 arguments.push_back(required);
160 known_commands[command] = arguments;
168 * Read one command definition from the syntax file
170 void read_command(Parser & p, string command, CommandMap & commands) {
171 if (p.next_token().asInput() == "*") {
175 vector<ArgumentType> arguments;
176 while (p.next_token().cat() == catBegin ||
177 p.next_token().asInput() == "[") {
178 if (p.next_token().cat() == catBegin) {
179 string const arg = p.getArg('{', '}');
180 if (arg == "translate")
181 arguments.push_back(required);
183 arguments.push_back(verbatim);
186 arguments.push_back(optional);
189 commands[command] = arguments;
194 * Read a class of environments from the syntax file
196 void read_environment(Parser & p, string const & begin,
197 CommandMap & environments)
201 Token const & t = p.get_token();
202 if (t.cat() == catLetter)
203 environment += t.asInput();
204 else if (!environment.empty()) {
206 read_command(p, environment, environments);
209 if (t.cat() == catEscape && t.asInput() == "\\end") {
210 string const end = p.getArg('{', '}');
219 * Read a list of TeX commands from a reLyX compatible syntax file.
220 * Since this list is used after all commands that have a LyX counterpart
221 * are handled, it does not matter that the "syntax.default" file
222 * has almost all of them listed. For the same reason the reLyX-specific
223 * reLyXre environment is ignored.
225 void read_syntaxfile(string const & file_name)
227 ifstream is(file_name.c_str());
229 cerr << "Could not open syntax file \"" << file_name
230 << "\" for reading." << endl;
233 // We can use our TeX parser, since the syntax of the layout file is
234 // modeled after TeX.
235 // Unknown tokens are just silently ignored, this helps us to skip some
236 // reLyX specific things.
239 Token const & t = p.get_token();
240 if (t.cat() == catEscape) {
241 string const command = t.asInput();
242 if (command == "\\begin") {
243 string const name = p.getArg('{', '}');
244 if (name == "environments" || name == "reLyXre")
245 // We understand "reLyXre", but it is
246 // not as powerful as "environments".
247 read_environment(p, name,
249 else if (name == "mathenvironments")
250 read_environment(p, name,
251 known_math_environments);
253 read_command(p, command, known_commands);
260 string documentclass;
262 bool overwrite_files = false;
265 /// return the number of arguments consumed
266 typedef boost::function<int(string const &, string const &)> cmd_helper;
269 int parse_help(string const &, string const &)
271 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
272 "Command line switches (case sensitive):\n"
273 "\t-help summarize tex2lyx usage\n"
274 "\t-f Force creation of .lyx files even if they exist already\n"
275 "\t-userdir dir try to set user directory to dir\n"
276 "\t-sysdir dir try to set system directory to dir\n"
277 "\t-c textclass declare the textclass\n"
278 "\t-s syntaxfile read additional syntax file" << endl;
283 int parse_class(string const & arg, string const &)
286 cerr << "Missing textclass string after -c switch" << endl;
294 int parse_syntaxfile(string const & arg, string const &)
297 cerr << "Missing syntaxfile string after -s switch" << endl;
305 // Filled with the command line arguments "foo" of "-sysdir foo" or
307 string cl_system_support;
308 string cl_user_support;
311 int parse_sysdir(string const & arg, string const &)
314 cerr << "Missing directory for -sysdir switch" << endl;
317 cl_system_support = arg;
322 int parse_userdir(string const & arg, string const &)
325 cerr << "Missing directory for -userdir switch" << endl;
328 cl_user_support = arg;
333 int parse_force(string const &, string const &)
335 overwrite_files = true;
340 void easyParse(int & argc, char * argv[])
342 map<string, cmd_helper> cmdmap;
344 cmdmap["-c"] = parse_class;
345 cmdmap["-f"] = parse_force;
346 cmdmap["-s"] = parse_syntaxfile;
347 cmdmap["-help"] = parse_help;
348 cmdmap["--help"] = parse_help;
349 cmdmap["-sysdir"] = parse_sysdir;
350 cmdmap["-userdir"] = parse_userdir;
352 for (int i = 1; i < argc; ++i) {
353 std::map<string, cmd_helper>::const_iterator it
354 = cmdmap.find(argv[i]);
356 // don't complain if not found - may be parsed later
357 if (it == cmdmap.end())
360 string arg((i + 1 < argc) ? argv[i + 1] : "");
361 string arg2((i + 2 < argc) ? argv[i + 2] : "");
363 int const remove = 1 + it->second(arg, arg2);
365 // Now, remove used arguments by shifting
366 // the following ones remove places down.
368 for (int j = i; j < argc; ++j)
369 argv[j] = argv[j + remove];
375 // path of the first parsed file
376 string masterFilePath;
377 // path of the currently parsed file
378 string parentFilePath;
380 } // anonymous namespace
383 string getMasterFilePath()
385 return masterFilePath;
388 string getParentFilePath()
390 return parentFilePath;
397 * Reads tex input from \a is and writes lyx output to \a os.
398 * Uses some common settings for the preamble, so this should only
399 * be used more than once for included documents.
400 * Caution: Overwrites the existing preamble settings if the new document
401 * contains a preamble.
402 * You must ensure that \p parentFilePath is properly set before calling
405 void tex2lyx(std::istream &is, std::ostream &os)
411 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
413 active_environments.push_back("document");
414 Context context(true, textclass);
415 parse_text(p, ss, FLAG_END, true, context);
416 context.check_end_layout(ss);
417 ss << "\n\\end_body\n\\end_document\n";
418 active_environments.pop_back();
423 ofstream parsertest("parsertest.tex");
425 parsertest << p.get_token().asInput();
426 // <origfile> and parsertest.tex should now have identical content
431 /// convert TeX from \p infilename to LyX and write it to \p os
432 bool tex2lyx(string const &infilename, std::ostream &os)
434 BOOST_ASSERT(lyx::support::AbsolutePath(infilename));
435 ifstream is(infilename.c_str());
437 cerr << "Could not open input file \"" << infilename
438 << "\" for reading." << endl;
441 string const oldParentFilePath = parentFilePath;
442 parentFilePath = OnlyPath(infilename);
444 parentFilePath = oldParentFilePath;
448 } // anonymous namespace
451 bool tex2lyx(string const &infilename, string const &outfilename)
453 if (IsFileReadable(outfilename)) {
454 if (overwrite_files) {
455 cerr << "Overwriting existing file "
456 << outfilename << endl;
458 cerr << "Not overwriting existing file "
459 << outfilename << endl;
463 cerr << "Creating file " << outfilename << endl;
465 ofstream os(outfilename.c_str());
467 cerr << "Could not open output file \"" << outfilename
468 << "\" for writing." << endl;
472 cerr << "Input file: " << infilename << "\n";
473 cerr << "Output file: " << outfilename << "\n";
475 return tex2lyx(infilename, os);
479 int main(int argc, char * argv[])
481 fs::path::default_name_check(fs::no_check);
483 easyParse(argc, argv);
486 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
487 "See tex2lyx -help." << endl;
491 lyx::support::os::init(argc, argv);
492 lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
493 lyx::support::top_build_dir_is_two_levels_up);
495 // Now every known option is parsed. Look for input and output
496 // file name (the latter is optional).
497 string const infilename = MakeAbsPath(argv[1]);
500 outfilename = argv[2];
501 if (outfilename != "-")
502 outfilename = MakeAbsPath(argv[2]);
504 outfilename = ChangeExtension(infilename, ".lyx");
506 string const system_syntaxfile = lyx::support::LibFileSearch("", "syntax.default");
507 if (system_syntaxfile.empty()) {
508 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
511 read_syntaxfile(system_syntaxfile);
512 if (!syntaxfile.empty())
513 read_syntaxfile(syntaxfile);
515 masterFilePath = OnlyPath(infilename);
516 parentFilePath = masterFilePath;
518 if (outfilename == "-") {
519 if (tex2lyx(infilename, cout))
524 if (tex2lyx(infilename, outfilename))