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 "TextClass.h"
22 #include "support/convert.h"
23 #include "support/filetools.h"
24 #include "support/lstrings.h"
25 #include "support/lyxlib.h"
26 #include "support/ExceptionMessage.h"
27 #include "support/os.h"
28 #include "support/Package.h"
29 #include "support/unicode.h"
31 #include <boost/function.hpp>
50 using std::istringstream;
51 using std::ostringstream;
52 using std::stringstream;
57 using support::changeExtension;
58 using support::FileName;
59 using support::isStrUnsignedInt;
61 using support::makeAbsPath;
62 using support::onlyPath;
63 using support::os::internal_path;
66 LayoutPtr captionlayout;
68 // Hacks to allow the thing to link in the lyxlayout stuff
69 LyXErr lyxerr(std::cerr.rdbuf());
72 string const trim(string const & a, char const * p)
79 string::size_type r = a.find_last_not_of(p);
80 string::size_type l = a.find_first_not_of(p);
82 // Is this the minimal test? (lgb)
83 if (r == string::npos && l == string::npos)
86 return a.substr(l, r - l + 1);
90 void split(string const & s, vector<string> & result, char delim)
92 //cerr << "split 1: '" << s << "'\n";
95 while (getline(is, t, delim))
97 //cerr << "split 2\n";
101 string join(vector<string> const & input, char const * delim)
104 for (size_t i = 0; i < input.size(); ++i) {
113 char const * const * is_known(string const & str, char const * const * what)
115 for ( ; *what; ++what)
123 // current stack of nested environments
124 vector<string> active_environments;
127 string active_environment()
129 return active_environments.empty() ? string() : active_environments.back();
133 CommandMap known_commands;
134 CommandMap known_environments;
135 CommandMap known_math_environments;
138 void add_known_command(string const & command, string const & o1,
141 // We have to handle the following cases:
142 // definition o1 o2 invocation result
143 // \newcommand{\foo}{bar} "" false \foo bar
144 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
145 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
146 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
147 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
148 unsigned int nargs = 0;
149 vector<ArgumentType> arguments;
150 string const opt1 = rtrim(ltrim(o1, "["), "]");
151 if (isStrUnsignedInt(opt1)) {
152 // The command has arguments
153 nargs = convert<unsigned int>(opt1);
154 if (nargs > 0 && o2) {
155 // The first argument is optional
156 arguments.push_back(optional);
160 for (unsigned int i = 0; i < nargs; ++i)
161 arguments.push_back(required);
162 known_commands[command] = arguments;
166 bool noweb_mode = false;
173 * Read one command definition from the syntax file
175 void read_command(Parser & p, string command, CommandMap & commands) {
176 if (p.next_token().asInput() == "*") {
180 vector<ArgumentType> arguments;
181 while (p.next_token().cat() == catBegin ||
182 p.next_token().asInput() == "[") {
183 if (p.next_token().cat() == catBegin) {
184 string const arg = p.getArg('{', '}');
185 if (arg == "translate")
186 arguments.push_back(required);
188 arguments.push_back(verbatim);
191 arguments.push_back(optional);
194 commands[command] = arguments;
199 * Read a class of environments from the syntax file
201 void read_environment(Parser & p, string const & begin,
202 CommandMap & environments)
206 Token const & t = p.get_token();
207 if (t.cat() == catLetter)
208 environment += t.asInput();
209 else if (!environment.empty()) {
211 read_command(p, environment, environments);
214 if (t.cat() == catEscape && t.asInput() == "\\end") {
215 string const end = p.getArg('{', '}');
224 * Read a list of TeX commands from a reLyX compatible syntax file.
225 * Since this list is used after all commands that have a LyX counterpart
226 * are handled, it does not matter that the "syntax.default" file
227 * has almost all of them listed. For the same reason the reLyX-specific
228 * reLyXre environment is ignored.
230 void read_syntaxfile(FileName const & file_name)
232 ifstream is(file_name.toFilesystemEncoding().c_str());
234 cerr << "Could not open syntax file \"" << file_name
235 << "\" for reading." << endl;
238 // We can use our TeX parser, since the syntax of the layout file is
239 // modeled after TeX.
240 // Unknown tokens are just silently ignored, this helps us to skip some
241 // reLyX specific things.
244 Token const & t = p.get_token();
245 if (t.cat() == catEscape) {
246 string const command = t.asInput();
247 if (command == "\\begin") {
248 string const name = p.getArg('{', '}');
249 if (name == "environments" || name == "reLyXre")
250 // We understand "reLyXre", but it is
251 // not as powerful as "environments".
252 read_environment(p, name,
254 else if (name == "mathenvironments")
255 read_environment(p, name,
256 known_math_environments);
258 read_command(p, command, known_commands);
265 string documentclass;
267 bool overwrite_files = false;
270 /// return the number of arguments consumed
271 typedef boost::function<int(string const &, string const &)> cmd_helper;
274 int parse_help(string const &, string const &)
276 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
277 "Command line switches (case sensitive):\n"
278 "\t-help summarize tex2lyx usage\n"
279 "\t-f Force creation of .lyx files even if they exist already\n"
280 "\t-userdir dir try to set user directory to dir\n"
281 "\t-sysdir dir try to set system directory to dir\n"
282 "\t-c textclass declare the textclass\n"
283 "\t-n translate a noweb (aka literate programming) file.\n"
284 "\t-s syntaxfile read additional syntax file" << endl;
289 int parse_class(string const & arg, string const &)
292 cerr << "Missing textclass string after -c switch" << endl;
300 int parse_syntaxfile(string const & arg, string const &)
303 cerr << "Missing syntaxfile string after -s switch" << endl;
306 syntaxfile = internal_path(arg);
311 // Filled with the command line arguments "foo" of "-sysdir foo" or
313 string cl_system_support;
314 string cl_user_support;
317 int parse_sysdir(string const & arg, string const &)
320 cerr << "Missing directory for -sysdir switch" << endl;
323 cl_system_support = internal_path(arg);
328 int parse_userdir(string const & arg, string const &)
331 cerr << "Missing directory for -userdir switch" << endl;
334 cl_user_support = internal_path(arg);
339 int parse_force(string const &, string const &)
341 overwrite_files = true;
346 int parse_noweb(string const &, string const &)
353 void easyParse(int & argc, char * argv[])
355 map<string, cmd_helper> cmdmap;
357 cmdmap["-c"] = parse_class;
358 cmdmap["-f"] = parse_force;
359 cmdmap["-s"] = parse_syntaxfile;
360 cmdmap["-help"] = parse_help;
361 cmdmap["--help"] = parse_help;
362 cmdmap["-n"] = parse_noweb;
363 cmdmap["-sysdir"] = parse_sysdir;
364 cmdmap["-userdir"] = parse_userdir;
366 for (int i = 1; i < argc; ++i) {
367 std::map<string, cmd_helper>::const_iterator it
368 = cmdmap.find(argv[i]);
370 // don't complain if not found - may be parsed later
371 if (it == cmdmap.end())
374 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
375 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
377 int const remove = 1 + it->second(arg, arg2);
379 // Now, remove used arguments by shifting
380 // the following ones remove places down.
382 for (int j = i; j < argc; ++j)
383 argv[j] = argv[j + remove];
389 // path of the first parsed file
390 string masterFilePath;
391 // path of the currently parsed file
392 string parentFilePath;
394 } // anonymous namespace
397 string getMasterFilePath()
399 return masterFilePath;
402 string getParentFilePath()
404 return parentFilePath;
411 * Reads tex input from \a is and writes lyx output to \a os.
412 * Uses some common settings for the preamble, so this should only
413 * be used more than once for included documents.
414 * Caution: Overwrites the existing preamble settings if the new document
415 * contains a preamble.
416 * You must ensure that \p parentFilePath is properly set before calling
419 void tex2lyx(std::istream & is, std::ostream & os)
425 TextClass textclass = parse_preamble(p, ss, documentclass);
426 captionlayout = LayoutPtr(Layout::forCaption());
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(FileName const & infilename, std::ostream & os)
452 ifstream is(infilename.toFilesystemEncoding().c_str());
454 cerr << "Could not open input file \"" << infilename
455 << "\" for reading." << endl;
458 string const oldParentFilePath = parentFilePath;
459 parentFilePath = onlyPath(infilename.absFilename());
461 parentFilePath = oldParentFilePath;
465 } // anonymous namespace
468 bool tex2lyx(string const & infilename, FileName const & outfilename)
470 if (outfilename.isReadableFile()) {
471 if (overwrite_files) {
472 cerr << "Overwriting existing file "
473 << outfilename << endl;
475 cerr << "Not overwriting existing file "
476 << outfilename << endl;
480 cerr << "Creating file " << outfilename << endl;
482 ofstream os(outfilename.toFilesystemEncoding().c_str());
484 cerr << "Could not open output file \"" << outfilename
485 << "\" for writing." << endl;
489 cerr << "Input file: " << infilename << "\n";
490 cerr << "Output file: " << outfilename << "\n";
492 return tex2lyx(FileName(infilename), os);
498 int main(int argc, char * argv[])
502 easyParse(argc, argv);
505 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
506 "See tex2lyx -help." << endl;
510 lyx::support::os::init(argc, argv);
512 try { support::init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
513 cl_system_support, cl_user_support,
514 support::top_build_dir_is_two_levels_up);
515 } catch (support::ExceptionMessage const & message) {
516 cerr << to_utf8(message.title_) << ":\n"
517 << to_utf8(message.details_) << endl;
518 if (message.type_ == support::ErrorException)
522 // Now every known option is parsed. Look for input and output
523 // file name (the latter is optional).
524 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
525 infilename = makeAbsPath(infilename).absFilename();
529 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
530 if (outfilename != "-")
531 outfilename = makeAbsPath(outfilename).absFilename();
533 outfilename = changeExtension(infilename, ".lyx");
535 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
536 if (system_syntaxfile.empty()) {
537 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
540 read_syntaxfile(system_syntaxfile);
541 if (!syntaxfile.empty())
542 read_syntaxfile(makeAbsPath(syntaxfile));
544 masterFilePath = onlyPath(infilename);
545 parentFilePath = masterFilePath;
547 if (outfilename == "-") {
548 if (tex2lyx(FileName(infilename), cout))
553 if (tex2lyx(infilename, FileName(outfilename)))