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"
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/ExceptionMessage.h"
27 #include "support/os.h"
28 #include "support/Package.h"
29 #include "support/unicode.h"
31 #include <boost/function.hpp>
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/filesystem/path.hpp>
52 using std::istringstream;
53 using std::ostringstream;
54 using std::stringstream;
59 using support::changeExtension;
60 using support::FileName;
61 using support::isStrUnsignedInt;
63 using support::makeAbsPath;
64 using support::onlyPath;
65 using support::os::internal_path;
67 using support::isFileReadable;
69 namespace fs = boost::filesystem;
71 Layout_ptr captionlayout;
73 // Hacks to allow the thing to link in the lyxlayout stuff
74 LyXErr lyxerr(std::cerr.rdbuf());
77 string const trim(string const & a, char const * p)
84 string::size_type r = a.find_last_not_of(p);
85 string::size_type l = a.find_first_not_of(p);
87 // Is this the minimal test? (lgb)
88 if (r == string::npos && l == string::npos)
91 return a.substr(l, r - l + 1);
95 void split(string const & s, vector<string> & result, char delim)
97 //cerr << "split 1: '" << s << "'\n";
100 while (getline(is, t, delim))
102 //cerr << "split 2\n";
106 string join(vector<string> const & input, char const * delim)
109 for (size_t i = 0; i < input.size(); ++i) {
118 char const * const * is_known(string const & str, char const * const * what)
120 for ( ; *what; ++what)
128 // current stack of nested environments
129 vector<string> active_environments;
132 string active_environment()
134 return active_environments.empty() ? string() : active_environments.back();
138 CommandMap known_commands;
139 CommandMap known_environments;
140 CommandMap known_math_environments;
143 void add_known_command(string const & command, string const & o1,
146 // We have to handle the following cases:
147 // definition o1 o2 invocation result
148 // \newcommand{\foo}{bar} "" false \foo bar
149 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
150 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
151 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
152 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
153 unsigned int nargs = 0;
154 vector<ArgumentType> arguments;
155 string const opt1 = rtrim(ltrim(o1, "["), "]");
156 if (isStrUnsignedInt(opt1)) {
157 // The command has arguments
158 nargs = convert<unsigned int>(opt1);
159 if (nargs > 0 && o2) {
160 // The first argument is optional
161 arguments.push_back(optional);
165 for (unsigned int i = 0; i < nargs; ++i)
166 arguments.push_back(required);
167 known_commands[command] = arguments;
171 bool noweb_mode = false;
178 * Read one command definition from the syntax file
180 void read_command(Parser & p, string command, CommandMap & commands) {
181 if (p.next_token().asInput() == "*") {
185 vector<ArgumentType> arguments;
186 while (p.next_token().cat() == catBegin ||
187 p.next_token().asInput() == "[") {
188 if (p.next_token().cat() == catBegin) {
189 string const arg = p.getArg('{', '}');
190 if (arg == "translate")
191 arguments.push_back(required);
193 arguments.push_back(verbatim);
196 arguments.push_back(optional);
199 commands[command] = arguments;
204 * Read a class of environments from the syntax file
206 void read_environment(Parser & p, string const & begin,
207 CommandMap & environments)
211 Token const & t = p.get_token();
212 if (t.cat() == catLetter)
213 environment += t.asInput();
214 else if (!environment.empty()) {
216 read_command(p, environment, environments);
219 if (t.cat() == catEscape && t.asInput() == "\\end") {
220 string const end = p.getArg('{', '}');
229 * Read a list of TeX commands from a reLyX compatible syntax file.
230 * Since this list is used after all commands that have a LyX counterpart
231 * are handled, it does not matter that the "syntax.default" file
232 * has almost all of them listed. For the same reason the reLyX-specific
233 * reLyXre environment is ignored.
235 void read_syntaxfile(FileName const & file_name)
237 ifstream is(file_name.toFilesystemEncoding().c_str());
239 cerr << "Could not open syntax file \"" << file_name
240 << "\" for reading." << endl;
243 // We can use our TeX parser, since the syntax of the layout file is
244 // modeled after TeX.
245 // Unknown tokens are just silently ignored, this helps us to skip some
246 // reLyX specific things.
249 Token const & t = p.get_token();
250 if (t.cat() == catEscape) {
251 string const command = t.asInput();
252 if (command == "\\begin") {
253 string const name = p.getArg('{', '}');
254 if (name == "environments" || name == "reLyXre")
255 // We understand "reLyXre", but it is
256 // not as powerful as "environments".
257 read_environment(p, name,
259 else if (name == "mathenvironments")
260 read_environment(p, name,
261 known_math_environments);
263 read_command(p, command, known_commands);
270 string documentclass;
272 bool overwrite_files = false;
275 /// return the number of arguments consumed
276 typedef boost::function<int(string const &, string const &)> cmd_helper;
279 int parse_help(string const &, string const &)
281 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
282 "Command line switches (case sensitive):\n"
283 "\t-help summarize tex2lyx usage\n"
284 "\t-f Force creation of .lyx files even if they exist already\n"
285 "\t-userdir dir try to set user directory to dir\n"
286 "\t-sysdir dir try to set system directory to dir\n"
287 "\t-c textclass declare the textclass\n"
288 "\t-n translate a noweb (aka literate programming) file.\n"
289 "\t-s syntaxfile read additional syntax file" << endl;
294 int parse_class(string const & arg, string const &)
297 cerr << "Missing textclass string after -c switch" << endl;
305 int parse_syntaxfile(string const & arg, string const &)
308 cerr << "Missing syntaxfile string after -s switch" << endl;
311 syntaxfile = internal_path(arg);
316 // Filled with the command line arguments "foo" of "-sysdir foo" or
318 string cl_system_support;
319 string cl_user_support;
322 int parse_sysdir(string const & arg, string const &)
325 cerr << "Missing directory for -sysdir switch" << endl;
328 cl_system_support = internal_path(arg);
333 int parse_userdir(string const & arg, string const &)
336 cerr << "Missing directory for -userdir switch" << endl;
339 cl_user_support = internal_path(arg);
344 int parse_force(string const &, string const &)
346 overwrite_files = true;
351 int parse_noweb(string const &, string const &)
358 void easyParse(int & argc, char * argv[])
360 map<string, cmd_helper> cmdmap;
362 cmdmap["-c"] = parse_class;
363 cmdmap["-f"] = parse_force;
364 cmdmap["-s"] = parse_syntaxfile;
365 cmdmap["-help"] = parse_help;
366 cmdmap["--help"] = parse_help;
367 cmdmap["-n"] = parse_noweb;
368 cmdmap["-sysdir"] = parse_sysdir;
369 cmdmap["-userdir"] = parse_userdir;
371 for (int i = 1; i < argc; ++i) {
372 std::map<string, cmd_helper>::const_iterator it
373 = cmdmap.find(argv[i]);
375 // don't complain if not found - may be parsed later
376 if (it == cmdmap.end())
379 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
380 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
382 int const remove = 1 + it->second(arg, arg2);
384 // Now, remove used arguments by shifting
385 // the following ones remove places down.
387 for (int j = i; j < argc; ++j)
388 argv[j] = argv[j + remove];
394 // path of the first parsed file
395 string masterFilePath;
396 // path of the currently parsed file
397 string parentFilePath;
399 } // anonymous namespace
402 string getMasterFilePath()
404 return masterFilePath;
407 string getParentFilePath()
409 return parentFilePath;
416 * Reads tex input from \a is and writes lyx output to \a os.
417 * Uses some common settings for the preamble, so this should only
418 * be used more than once for included documents.
419 * Caution: Overwrites the existing preamble settings if the new document
420 * contains a preamble.
421 * You must ensure that \p parentFilePath is properly set before calling
424 void tex2lyx(std::istream &is, std::ostream &os)
430 TextClass textclass = parse_preamble(p, ss, documentclass);
431 captionlayout = Layout_ptr(Layout::forCaption());
433 active_environments.push_back("document");
434 Context context(true, textclass);
435 parse_text(p, ss, FLAG_END, true, context);
437 // Empty document body. LyX needs at least one paragraph.
438 context.check_layout(ss);
439 context.check_end_layout(ss);
440 ss << "\n\\end_body\n\\end_document\n";
441 active_environments.pop_back();
446 ofstream parsertest("parsertest.tex");
448 parsertest << p.get_token().asInput();
449 // <origfile> and parsertest.tex should now have identical content
454 /// convert TeX from \p infilename to LyX and write it to \p os
455 bool tex2lyx(FileName const & infilename, std::ostream &os)
457 ifstream is(infilename.toFilesystemEncoding().c_str());
459 cerr << "Could not open input file \"" << infilename
460 << "\" for reading." << endl;
463 string const oldParentFilePath = parentFilePath;
464 parentFilePath = onlyPath(infilename.absFilename());
466 parentFilePath = oldParentFilePath;
470 } // anonymous namespace
473 bool tex2lyx(string const &infilename, FileName const &outfilename)
475 if (isFileReadable(outfilename)) {
476 if (overwrite_files) {
477 cerr << "Overwriting existing file "
478 << outfilename << endl;
480 cerr << "Not overwriting existing file "
481 << outfilename << endl;
485 cerr << "Creating file " << outfilename << endl;
487 ofstream os(outfilename.toFilesystemEncoding().c_str());
489 cerr << "Could not open output file \"" << outfilename
490 << "\" for writing." << endl;
494 cerr << "Input file: " << infilename << "\n";
495 cerr << "Output file: " << outfilename << "\n";
497 return tex2lyx(FileName(infilename), os);
503 int main(int argc, char * argv[])
506 fs::path::default_name_check(fs::no_check);
508 easyParse(argc, argv);
511 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
512 "See tex2lyx -help." << endl;
516 lyx::support::os::init(argc, argv);
518 try { support::init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
519 cl_system_support, cl_user_support,
520 support::top_build_dir_is_two_levels_up);
521 } catch (support::ExceptionMessage const & message) {
522 cerr << to_utf8(message.title_) << ":\n"
523 << to_utf8(message.details_) << endl;
524 if (message.type_ == support::ErrorException)
528 // Now every known option is parsed. Look for input and output
529 // file name (the latter is optional).
530 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
531 infilename = makeAbsPath(infilename).absFilename();
535 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
536 if (outfilename != "-")
537 outfilename = makeAbsPath(outfilename).absFilename();
539 outfilename = changeExtension(infilename, ".lyx");
541 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
542 if (system_syntaxfile.empty()) {
543 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
546 read_syntaxfile(system_syntaxfile);
547 if (!syntaxfile.empty())
548 read_syntaxfile(makeAbsPath(syntaxfile));
550 masterFilePath = onlyPath(infilename);
551 parentFilePath = masterFilePath;
553 if (outfilename == "-") {
554 if (tex2lyx(FileName(infilename), cout))
559 if (tex2lyx(infilename, FileName(outfilename)))