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::isStrUnsignedInt;
56 using lyx::support::ltrim;
57 using lyx::support::MakeAbsPath;
58 using lyx::support::OnlyPath;
59 using lyx::support::rtrim;
60 using lyx::support::IsFileReadable;
62 namespace fs = boost::filesystem;
65 // Hacks to allow the thing to link in the lyxlayout stuff
66 LyXErr lyxerr(std::cerr.rdbuf());
69 string const trim(string const & a, char const * p)
76 string::size_type r = a.find_last_not_of(p);
77 string::size_type l = a.find_first_not_of(p);
79 // Is this the minimal test? (lgb)
80 if (r == string::npos && l == string::npos)
83 return a.substr(l, r - l + 1);
87 void split(string const & s, vector<string> & result, char delim)
89 //cerr << "split 1: '" << s << "'\n";
92 while (getline(is, t, delim))
94 //cerr << "split 2\n";
98 string join(vector<string> const & input, char const * delim)
101 for (size_t i = 0; i < input.size(); ++i) {
110 char const * const * is_known(string const & str, char const * const * what)
112 for ( ; *what; ++what)
120 // current stack of nested environments
121 vector<string> active_environments;
124 string active_environment()
126 return active_environments.empty() ? string() : active_environments.back();
130 CommandMap known_commands;
131 CommandMap known_environments;
132 CommandMap known_math_environments;
135 void add_known_command(string const & command, string const & o1,
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);
157 for (unsigned int i = 0; i < nargs; ++i)
158 arguments.push_back(required);
159 known_commands[command] = arguments;
167 * Read one command definition from the syntax file
169 void read_command(Parser & p, string command, CommandMap & commands) {
170 if (p.next_token().asInput() == "*") {
174 vector<ArgumentType> arguments;
175 while (p.next_token().cat() == catBegin ||
176 p.next_token().asInput() == "[") {
177 if (p.next_token().cat() == catBegin) {
178 string const arg = p.getArg('{', '}');
179 if (arg == "translate")
180 arguments.push_back(required);
182 arguments.push_back(verbatim);
185 arguments.push_back(optional);
188 commands[command] = arguments;
193 * Read a class of environments from the syntax file
195 void read_environment(Parser & p, string const & begin,
196 CommandMap & environments)
200 Token const & t = p.get_token();
201 if (t.cat() == catLetter)
202 environment += t.asInput();
203 else if (!environment.empty()) {
205 read_command(p, environment, environments);
208 if (t.cat() == catEscape && t.asInput() == "\\end") {
209 string const end = p.getArg('{', '}');
218 * Read a list of TeX commands from a reLyX compatible syntax file.
219 * Since this list is used after all commands that have a LyX counterpart
220 * are handled, it does not matter that the "syntax.default" file
221 * has almost all of them listed. For the same reason the reLyX-specific
222 * reLyXre environment is ignored.
224 void read_syntaxfile(string const & file_name)
226 ifstream is(file_name.c_str());
228 cerr << "Could not open syntax file \"" << file_name
229 << "\" for reading." << endl;
232 // We can use our TeX parser, since the syntax of the layout file is
233 // modeled after TeX.
234 // Unknown tokens are just silently ignored, this helps us to skip some
235 // reLyX specific things.
238 Token const & t = p.get_token();
239 if (t.cat() == catEscape) {
240 string const command = t.asInput();
241 if (command == "\\begin") {
242 string const name = p.getArg('{', '}');
243 if (name == "environments" || name == "reLyXre")
244 // We understand "reLyXre", but it is
245 // not as powerful as "environments".
246 read_environment(p, name,
248 else if (name == "mathenvironments")
249 read_environment(p, name,
250 known_math_environments);
252 read_command(p, command, known_commands);
259 string documentclass;
261 bool overwrite_files = false;
264 /// return the number of arguments consumed
265 typedef boost::function<int(string const &, string const &)> cmd_helper;
268 int parse_help(string const &, string const &)
270 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
271 "Command line switches (case sensitive):\n"
272 "\t-help summarize tex2lyx usage\n"
273 "\t-f Force creation of .lyx files even if they exist already\n"
274 "\t-userdir dir try to set user directory to dir\n"
275 "\t-sysdir dir try to set system directory to dir\n"
276 "\t-c textclass declare the textclass\n"
277 "\t-s syntaxfile read additional syntax file" << endl;
282 int parse_class(string const & arg, string const &)
285 cerr << "Missing textclass string after -c switch" << endl;
293 int parse_syntaxfile(string const & arg, string const &)
296 cerr << "Missing syntaxfile string after -s switch" << endl;
304 // Filled with the command line arguments "foo" of "-sysdir foo" or
306 string cl_system_support;
307 string cl_user_support;
310 int parse_sysdir(string const & arg, string const &)
313 cerr << "Missing directory for -sysdir switch" << endl;
316 cl_system_support = arg;
321 int parse_userdir(string const & arg, string const &)
324 cerr << "Missing directory for -userdir switch" << endl;
327 cl_user_support = arg;
332 int parse_force(string const &, string const &)
334 overwrite_files = true;
339 void easyParse(int & argc, char * argv[])
341 map<string, cmd_helper> cmdmap;
343 cmdmap["-c"] = parse_class;
344 cmdmap["-f"] = parse_force;
345 cmdmap["-s"] = parse_syntaxfile;
346 cmdmap["-help"] = parse_help;
347 cmdmap["--help"] = parse_help;
348 cmdmap["-sysdir"] = parse_sysdir;
349 cmdmap["-userdir"] = parse_userdir;
351 for (int i = 1; i < argc; ++i) {
352 std::map<string, cmd_helper>::const_iterator it
353 = cmdmap.find(argv[i]);
355 // don't complain if not found - may be parsed later
356 if (it == cmdmap.end())
359 string arg((i + 1 < argc) ? argv[i + 1] : "");
360 string arg2((i + 2 < argc) ? argv[i + 2] : "");
362 int const remove = 1 + it->second(arg, arg2);
364 // Now, remove used arguments by shifting
365 // the following ones remove places down.
367 for (int j = i; j < argc; ++j)
368 argv[j] = argv[j + remove];
374 // path of the first parsed file
375 string masterFilePath;
376 // path of the currently parsed file
377 string parentFilePath;
379 } // anonymous namespace
382 string getMasterFilePath()
384 return masterFilePath;
387 string getParentFilePath()
389 return parentFilePath;
396 * Reads tex input from \a is and writes lyx output to \a os.
397 * Uses some common settings for the preamble, so this should only
398 * be used more than once for included documents.
399 * Caution: Overwrites the existing preamble settings if the new document
400 * contains a preamble.
401 * You must ensure that \p parentFilePath is properly set before calling
404 void tex2lyx(std::istream &is, std::ostream &os)
410 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
412 active_environments.push_back("document");
413 Context context(true, textclass);
414 parse_text(p, ss, FLAG_END, true, context);
415 context.check_end_layout(ss);
416 ss << "\n\\end_body\n\\end_document\n";
417 active_environments.pop_back();
422 ofstream parsertest("parsertest.tex");
424 parsertest << p.get_token().asInput();
425 // <origfile> and parsertest.tex should now have identical content
430 /// convert TeX from \p infilename to LyX and write it to \p os
431 bool tex2lyx(string const &infilename, std::ostream &os)
433 BOOST_ASSERT(lyx::support::AbsolutePath(infilename));
434 ifstream is(infilename.c_str());
436 cerr << "Could not open input file \"" << infilename
437 << "\" for reading." << endl;
440 string const oldParentFilePath = parentFilePath;
441 parentFilePath = OnlyPath(infilename);
443 parentFilePath = oldParentFilePath;
447 } // anonymous namespace
450 bool tex2lyx(string const &infilename, string const &outfilename)
452 if (IsFileReadable(outfilename)) {
453 if (overwrite_files) {
454 cerr << "Overwriting existing file "
455 << outfilename << endl;
457 cerr << "Not overwriting existing file "
458 << outfilename << endl;
462 cerr << "Creating file " << outfilename << endl;
464 ofstream os(outfilename.c_str());
466 cerr << "Could not open output file \"" << outfilename
467 << "\" for writing." << endl;
471 cerr << "Input file: " << infilename << "\n";
472 cerr << "Output file: " << outfilename << "\n";
474 return tex2lyx(infilename, os);
478 int main(int argc, char * argv[])
480 fs::path::default_name_check(fs::no_check);
482 easyParse(argc, argv);
485 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
486 "See tex2lyx -help." << endl;
490 lyx::support::os::init(argc, argv);
491 lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
492 lyx::support::top_build_dir_is_two_levels_up);
494 // Now every known option is parsed. Look for input and output
495 // file name (the latter is optional).
496 string const infilename = MakeAbsPath(argv[1]);
499 outfilename = MakeAbsPath(argv[2]);
501 string const system_syntaxfile = lyx::support::LibFileSearch("", "syntax.default");
502 if (system_syntaxfile.empty()) {
503 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
506 read_syntaxfile(system_syntaxfile);
507 if (!syntaxfile.empty())
508 read_syntaxfile(syntaxfile);
510 masterFilePath = OnlyPath(infilename);
511 parentFilePath = masterFilePath;
513 if (outfilename.empty() || outfilename == "-") {
514 if (tex2lyx(infilename, cout))
519 if (tex2lyx(infilename, outfilename))