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>
51 using std::istringstream;
52 using std::ostringstream;
53 using std::stringstream;
58 using lyx::support::changeExtension;
59 using lyx::support::isStrUnsignedInt;
60 using lyx::support::ltrim;
61 using lyx::support::makeAbsPath;
62 using lyx::support::onlyPath;
63 using lyx::support::rtrim;
64 using lyx::support::isFileReadable;
66 namespace fs = boost::filesystem;
69 // Hacks to allow the thing to link in the lyxlayout stuff
70 LyXErr lyxerr(std::cerr.rdbuf());
73 string const trim(string const & a, char const * p)
80 string::size_type r = a.find_last_not_of(p);
81 string::size_type l = a.find_first_not_of(p);
83 // Is this the minimal test? (lgb)
84 if (r == string::npos && l == string::npos)
87 return a.substr(l, r - l + 1);
91 void split(string const & s, vector<string> & result, char delim)
93 //cerr << "split 1: '" << s << "'\n";
96 while (getline(is, t, delim))
98 //cerr << "split 2\n";
102 string join(vector<string> const & input, char const * delim)
105 for (size_t i = 0; i < input.size(); ++i) {
114 char const * const * is_known(string const & str, char const * const * what)
116 for ( ; *what; ++what)
124 // current stack of nested environments
125 vector<string> active_environments;
128 string active_environment()
130 return active_environments.empty() ? string() : active_environments.back();
134 CommandMap known_commands;
135 CommandMap known_environments;
136 CommandMap known_math_environments;
139 void add_known_command(string const & command, string const & o1,
142 // We have to handle the following cases:
143 // definition o1 o2 invocation result
144 // \newcommand{\foo}{bar} "" false \foo bar
145 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
146 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
147 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
148 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
149 unsigned int nargs = 0;
150 vector<ArgumentType> arguments;
151 string const opt1 = rtrim(ltrim(o1, "["), "]");
152 if (isStrUnsignedInt(opt1)) {
153 // The command has arguments
154 nargs = convert<unsigned int>(opt1);
155 if (nargs > 0 && o2) {
156 // The first argument is optional
157 arguments.push_back(optional);
161 for (unsigned int i = 0; i < nargs; ++i)
162 arguments.push_back(required);
163 known_commands[command] = arguments;
167 bool noweb_mode = false;
174 * Read one command definition from the syntax file
176 void read_command(Parser & p, string command, CommandMap & commands) {
177 if (p.next_token().asInput() == "*") {
181 vector<ArgumentType> arguments;
182 while (p.next_token().cat() == catBegin ||
183 p.next_token().asInput() == "[") {
184 if (p.next_token().cat() == catBegin) {
185 string const arg = p.getArg('{', '}');
186 if (arg == "translate")
187 arguments.push_back(required);
189 arguments.push_back(verbatim);
192 arguments.push_back(optional);
195 commands[command] = arguments;
200 * Read a class of environments from the syntax file
202 void read_environment(Parser & p, string const & begin,
203 CommandMap & environments)
207 Token const & t = p.get_token();
208 if (t.cat() == catLetter)
209 environment += t.asInput();
210 else if (!environment.empty()) {
212 read_command(p, environment, environments);
215 if (t.cat() == catEscape && t.asInput() == "\\end") {
216 string const end = p.getArg('{', '}');
225 * Read a list of TeX commands from a reLyX compatible syntax file.
226 * Since this list is used after all commands that have a LyX counterpart
227 * are handled, it does not matter that the "syntax.default" file
228 * has almost all of them listed. For the same reason the reLyX-specific
229 * reLyXre environment is ignored.
231 void read_syntaxfile(string const & file_name)
233 ifstream is(file_name.c_str());
235 cerr << "Could not open syntax file \"" << file_name
236 << "\" for reading." << endl;
239 // We can use our TeX parser, since the syntax of the layout file is
240 // modeled after TeX.
241 // Unknown tokens are just silently ignored, this helps us to skip some
242 // reLyX specific things.
245 Token const & t = p.get_token();
246 if (t.cat() == catEscape) {
247 string const command = t.asInput();
248 if (command == "\\begin") {
249 string const name = p.getArg('{', '}');
250 if (name == "environments" || name == "reLyXre")
251 // We understand "reLyXre", but it is
252 // not as powerful as "environments".
253 read_environment(p, name,
255 else if (name == "mathenvironments")
256 read_environment(p, name,
257 known_math_environments);
259 read_command(p, command, known_commands);
266 string documentclass;
268 bool overwrite_files = false;
271 /// return the number of arguments consumed
272 typedef boost::function<int(string const &, string const &)> cmd_helper;
275 int parse_help(string const &, string const &)
277 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
278 "Command line switches (case sensitive):\n"
279 "\t-help summarize tex2lyx usage\n"
280 "\t-f Force creation of .lyx files even if they exist already\n"
281 "\t-userdir dir try to set user directory to dir\n"
282 "\t-sysdir dir try to set system directory to dir\n"
283 "\t-c textclass declare the textclass\n"
284 "\t-n translate a noweb (aka literate programming) file.\n"
285 "\t-s syntaxfile read additional syntax file" << endl;
290 int parse_class(string const & arg, string const &)
293 cerr << "Missing textclass string after -c switch" << endl;
301 int parse_syntaxfile(string const & arg, string const &)
304 cerr << "Missing syntaxfile string after -s switch" << endl;
312 // Filled with the command line arguments "foo" of "-sysdir foo" or
314 string cl_system_support;
315 string cl_user_support;
318 int parse_sysdir(string const & arg, string const &)
321 cerr << "Missing directory for -sysdir switch" << endl;
324 cl_system_support = arg;
329 int parse_userdir(string const & arg, string const &)
332 cerr << "Missing directory for -userdir switch" << endl;
335 cl_user_support = arg;
340 int parse_force(string const &, string const &)
342 overwrite_files = true;
347 int parse_noweb(string const &, string const &)
354 void easyParse(int & argc, char * argv[])
356 map<string, cmd_helper> cmdmap;
358 cmdmap["-c"] = parse_class;
359 cmdmap["-f"] = parse_force;
360 cmdmap["-s"] = parse_syntaxfile;
361 cmdmap["-help"] = parse_help;
362 cmdmap["--help"] = parse_help;
363 cmdmap["-n"] = parse_noweb;
364 cmdmap["-sysdir"] = parse_sysdir;
365 cmdmap["-userdir"] = parse_userdir;
367 for (int i = 1; i < argc; ++i) {
368 std::map<string, cmd_helper>::const_iterator it
369 = cmdmap.find(argv[i]);
371 // don't complain if not found - may be parsed later
372 if (it == cmdmap.end())
375 string arg((i + 1 < argc) ? argv[i + 1] : "");
376 string arg2((i + 2 < argc) ? argv[i + 2] : "");
378 int const remove = 1 + it->second(arg, arg2);
380 // Now, remove used arguments by shifting
381 // the following ones remove places down.
383 for (int j = i; j < argc; ++j)
384 argv[j] = argv[j + remove];
390 // path of the first parsed file
391 string masterFilePath;
392 // path of the currently parsed file
393 string parentFilePath;
395 } // anonymous namespace
398 string getMasterFilePath()
400 return masterFilePath;
403 string getParentFilePath()
405 return parentFilePath;
412 * Reads tex input from \a is and writes lyx output to \a os.
413 * Uses some common settings for the preamble, so this should only
414 * be used more than once for included documents.
415 * Caution: Overwrites the existing preamble settings if the new document
416 * contains a preamble.
417 * You must ensure that \p parentFilePath is properly set before calling
420 void tex2lyx(std::istream &is, std::ostream &os)
426 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
428 active_environments.push_back("document");
429 Context context(true, textclass);
430 parse_text(p, ss, FLAG_END, true, context);
432 // Empty document body. LyX needs at least one paragraph.
433 context.check_layout(ss);
434 context.check_end_layout(ss);
435 ss << "\n\\end_body\n\\end_document\n";
436 active_environments.pop_back();
441 ofstream parsertest("parsertest.tex");
443 parsertest << p.get_token().asInput();
444 // <origfile> and parsertest.tex should now have identical content
449 /// convert TeX from \p infilename to LyX and write it to \p os
450 bool tex2lyx(string const &infilename, std::ostream &os)
452 BOOST_ASSERT(lyx::support::absolutePath(infilename));
453 ifstream is(infilename.c_str());
455 cerr << "Could not open input file \"" << infilename
456 << "\" for reading." << endl;
459 string const oldParentFilePath = parentFilePath;
460 parentFilePath = onlyPath(infilename);
462 parentFilePath = oldParentFilePath;
466 } // anonymous namespace
469 bool tex2lyx(string const &infilename, string const &outfilename)
471 if (isFileReadable(outfilename)) {
472 if (overwrite_files) {
473 cerr << "Overwriting existing file "
474 << outfilename << endl;
476 cerr << "Not overwriting existing file "
477 << outfilename << endl;
481 cerr << "Creating file " << outfilename << endl;
483 ofstream os(outfilename.c_str());
485 cerr << "Could not open output file \"" << outfilename
486 << "\" for writing." << endl;
490 cerr << "Input file: " << infilename << "\n";
491 cerr << "Output file: " << outfilename << "\n";
493 return tex2lyx(infilename, os);
499 int main(int argc, char * argv[])
502 fs::path::default_name_check(fs::no_check);
504 easyParse(argc, argv);
507 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
508 "See tex2lyx -help." << endl;
512 lyx::support::os::init(argc, argv);
513 lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
514 lyx::support::top_build_dir_is_two_levels_up);
516 // Now every known option is parsed. Look for input and output
517 // file name (the latter is optional).
518 string const infilename = makeAbsPath(argv[1]);
521 outfilename = argv[2];
522 if (outfilename != "-")
523 outfilename = makeAbsPath(argv[2]);
525 outfilename = changeExtension(infilename, ".lyx");
527 string const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
528 if (system_syntaxfile.empty()) {
529 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
532 read_syntaxfile(system_syntaxfile);
533 if (!syntaxfile.empty())
534 read_syntaxfile(syntaxfile);
536 masterFilePath = onlyPath(infilename);
537 parentFilePath = masterFilePath;
539 if (outfilename == "-") {
540 if (tex2lyx(infilename, cout))
545 if (tex2lyx(infilename, outfilename))