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 map<string, vector<ArgumentType> > known_commands;
133 void add_known_command(string const & command, string const & o1,
136 // We have to handle the following cases:
137 // definition o1 o2 invocation result
138 // \newcommand{\foo}{bar} "" false \foo bar
139 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
140 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
141 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
142 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
143 unsigned int nargs = 0;
144 vector<ArgumentType> arguments;
145 string const opt1 = rtrim(ltrim(o1, "["), "]");
146 if (isStrUnsignedInt(opt1)) {
147 // The command has arguments
148 nargs = convert<unsigned int>(opt1);
149 if (nargs > 0 && o2) {
150 // The first argument is optional
151 arguments.push_back(optional);
155 for (unsigned int i = 0; i < nargs; ++i)
156 arguments.push_back(required);
157 known_commands[command] = arguments;
165 * Read a list of TeX commands from a reLyX compatible syntax file.
166 * Since this list is used after all commands that have a LyX counterpart
167 * are handled, it does not matter that the "syntax.default" file from reLyX
168 * has almost all of them listed. For the same reason the reLyX-specific
169 * reLyXre environment is ignored.
171 void read_syntaxfile(string const & file_name)
173 ifstream is(file_name.c_str());
175 cerr << "Could not open syntax file \"" << file_name
176 << "\" for reading." << endl;
179 // We can use our TeX parser, since the syntax of the layout file is
180 // modeled after TeX.
181 // Unknown tokens are just silently ignored, this helps us to skip some
182 // reLyX specific things.
185 Token const & t = p.get_token();
186 if (t.cat() == catEscape) {
187 string command = t.asInput();
188 if (p.next_token().asInput() == "*") {
193 vector<ArgumentType> arguments;
194 while (p.next_token().cat() == catBegin ||
195 p.next_token().asInput() == "[") {
196 if (p.next_token().cat() == catBegin) {
197 string const arg = p.getArg('{', '}');
198 if (arg == "translate")
199 arguments.push_back(required);
201 arguments.push_back(verbatim);
204 arguments.push_back(optional);
207 known_commands[command] = arguments;
213 string documentclass;
215 bool overwrite_files = false;
218 /// return the number of arguments consumed
219 typedef boost::function<int(string const &, string const &)> cmd_helper;
222 int parse_help(string const &, string const &)
224 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
225 "Command line switches (case sensitive):\n"
226 "\t-help summarize tex2lyx usage\n"
227 "\t-f Force creation of .lyx files even if they exist already\n"
228 "\t-userdir dir try to set user directory to dir\n"
229 "\t-sysdir dir try to set system directory to dir\n"
230 "\t-c textclass declare the textclass\n"
231 "\t-s syntaxfile read additional syntax file" << endl;
236 int parse_class(string const & arg, string const &)
239 cerr << "Missing textclass string after -c switch" << endl;
247 int parse_syntaxfile(string const & arg, string const &)
250 cerr << "Missing syntaxfile string after -s switch" << endl;
258 // Filled with the command line arguments "foo" of "-sysdir foo" or
260 string cl_system_support;
261 string cl_user_support;
264 int parse_sysdir(string const & arg, string const &)
267 cerr << "Missing directory for -sysdir switch" << endl;
270 cl_system_support = arg;
275 int parse_userdir(string const & arg, string const &)
278 cerr << "Missing directory for -userdir switch" << endl;
281 cl_user_support = arg;
286 int parse_force(string const &, string const &)
288 overwrite_files = true;
293 void easyParse(int & argc, char * argv[])
295 map<string, cmd_helper> cmdmap;
297 cmdmap["-c"] = parse_class;
298 cmdmap["-f"] = parse_force;
299 cmdmap["-s"] = parse_syntaxfile;
300 cmdmap["-help"] = parse_help;
301 cmdmap["--help"] = parse_help;
302 cmdmap["-sysdir"] = parse_sysdir;
303 cmdmap["-userdir"] = parse_userdir;
305 for (int i = 1; i < argc; ++i) {
306 std::map<string, cmd_helper>::const_iterator it
307 = cmdmap.find(argv[i]);
309 // don't complain if not found - may be parsed later
310 if (it == cmdmap.end())
313 string arg((i + 1 < argc) ? argv[i + 1] : "");
314 string arg2((i + 2 < argc) ? argv[i + 2] : "");
316 int const remove = 1 + it->second(arg, arg2);
318 // Now, remove used arguments by shifting
319 // the following ones remove places down.
321 for (int j = i; j < argc; ++j)
322 argv[j] = argv[j + remove];
328 // path of the first parsed file
329 string masterFilePath;
330 // path of the currently parsed file
331 string parentFilePath;
333 } // anonymous namespace
336 string getMasterFilePath()
338 return masterFilePath;
341 string getParentFilePath()
343 return parentFilePath;
350 * Reads tex input from \a is and writes lyx output to \a os.
351 * Uses some common settings for the preamble, so this should only
352 * be used more than once for included documents.
353 * Caution: Overwrites the existing preamble settings if the new document
354 * contains a preamble.
355 * You must ensure that \p parentFilePath is properly set before calling
358 void tex2lyx(std::istream &is, std::ostream &os)
364 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
366 active_environments.push_back("document");
367 Context context(true, textclass);
368 parse_text(p, ss, FLAG_END, true, context);
369 context.check_end_layout(ss);
370 ss << "\n\\end_body\n\\end_document\n";
371 active_environments.pop_back();
376 ofstream parsertest("parsertest.tex");
378 parsertest << p.get_token().asInput();
379 // <origfile> and parsertest.tex should now have identical content
384 /// convert TeX from \p infilename to LyX and write it to \p os
385 bool tex2lyx(string const &infilename, std::ostream &os)
387 BOOST_ASSERT(lyx::support::AbsolutePath(infilename));
388 ifstream is(infilename.c_str());
390 cerr << "Could not open input file \"" << infilename
391 << "\" for reading." << endl;
394 string const oldParentFilePath = parentFilePath;
395 parentFilePath = OnlyPath(infilename);
397 parentFilePath = oldParentFilePath;
401 } // anonymous namespace
404 bool tex2lyx(string const &infilename, string const &outfilename)
406 if (IsFileReadable(outfilename)) {
407 if (overwrite_files) {
408 cerr << "Overwriting existing file "
409 << outfilename << endl;
411 cerr << "Not overwriting existing file "
412 << outfilename << endl;
416 cerr << "Creating file " << outfilename << endl;
418 ofstream os(outfilename.c_str());
420 cerr << "Could not open output file \"" << outfilename
421 << "\" for writing." << endl;
425 cerr << "Input file: " << infilename << "\n";
426 cerr << "Output file: " << outfilename << "\n";
428 return tex2lyx(infilename, os);
432 int main(int argc, char * argv[])
434 fs::path::default_name_check(fs::no_check);
436 easyParse(argc, argv);
439 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
440 "See tex2lyx -help." << endl;
444 lyx::support::os::init(argc, argv);
445 lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
446 lyx::support::top_build_dir_is_two_levels_up);
448 string const system_syntaxfile = lyx::support::LibFileSearch("reLyX", "syntax.default");
449 if (system_syntaxfile.empty()) {
450 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
453 read_syntaxfile(system_syntaxfile);
454 if (!syntaxfile.empty())
455 read_syntaxfile(syntaxfile);
457 string const infilename = MakeAbsPath(argv[1]);
458 masterFilePath = OnlyPath(infilename);
459 parentFilePath = masterFilePath;
461 if (tex2lyx(infilename, cout))