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>
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;
68 namespace fs = boost::filesystem;
70 LayoutPtr captionlayout;
72 // Hacks to allow the thing to link in the lyxlayout stuff
73 LyXErr lyxerr(std::cerr.rdbuf());
76 string const trim(string const & a, char const * p)
83 string::size_type r = a.find_last_not_of(p);
84 string::size_type l = a.find_first_not_of(p);
86 // Is this the minimal test? (lgb)
87 if (r == string::npos && l == string::npos)
90 return a.substr(l, r - l + 1);
94 void split(string const & s, vector<string> & result, char delim)
96 //cerr << "split 1: '" << s << "'\n";
99 while (getline(is, t, delim))
101 //cerr << "split 2\n";
105 string join(vector<string> const & input, char const * delim)
108 for (size_t i = 0; i < input.size(); ++i) {
117 char const * const * is_known(string const & str, char const * const * what)
119 for ( ; *what; ++what)
127 // current stack of nested environments
128 vector<string> active_environments;
131 string active_environment()
133 return active_environments.empty() ? string() : active_environments.back();
137 CommandMap known_commands;
138 CommandMap known_environments;
139 CommandMap known_math_environments;
142 void add_known_command(string const & command, string const & o1,
145 // We have to handle the following cases:
146 // definition o1 o2 invocation result
147 // \newcommand{\foo}{bar} "" false \foo bar
148 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
149 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
150 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
151 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
152 unsigned int nargs = 0;
153 vector<ArgumentType> arguments;
154 string const opt1 = rtrim(ltrim(o1, "["), "]");
155 if (isStrUnsignedInt(opt1)) {
156 // The command has arguments
157 nargs = convert<unsigned int>(opt1);
158 if (nargs > 0 && o2) {
159 // The first argument is optional
160 arguments.push_back(optional);
164 for (unsigned int i = 0; i < nargs; ++i)
165 arguments.push_back(required);
166 known_commands[command] = arguments;
170 bool noweb_mode = false;
177 * Read one command definition from the syntax file
179 void read_command(Parser & p, string command, CommandMap & commands) {
180 if (p.next_token().asInput() == "*") {
184 vector<ArgumentType> arguments;
185 while (p.next_token().cat() == catBegin ||
186 p.next_token().asInput() == "[") {
187 if (p.next_token().cat() == catBegin) {
188 string const arg = p.getArg('{', '}');
189 if (arg == "translate")
190 arguments.push_back(required);
192 arguments.push_back(verbatim);
195 arguments.push_back(optional);
198 commands[command] = arguments;
203 * Read a class of environments from the syntax file
205 void read_environment(Parser & p, string const & begin,
206 CommandMap & environments)
210 Token const & t = p.get_token();
211 if (t.cat() == catLetter)
212 environment += t.asInput();
213 else if (!environment.empty()) {
215 read_command(p, environment, environments);
218 if (t.cat() == catEscape && t.asInput() == "\\end") {
219 string const end = p.getArg('{', '}');
228 * Read a list of TeX commands from a reLyX compatible syntax file.
229 * Since this list is used after all commands that have a LyX counterpart
230 * are handled, it does not matter that the "syntax.default" file
231 * has almost all of them listed. For the same reason the reLyX-specific
232 * reLyXre environment is ignored.
234 void read_syntaxfile(FileName const & file_name)
236 ifstream is(file_name.toFilesystemEncoding().c_str());
238 cerr << "Could not open syntax file \"" << file_name
239 << "\" for reading." << endl;
242 // We can use our TeX parser, since the syntax of the layout file is
243 // modeled after TeX.
244 // Unknown tokens are just silently ignored, this helps us to skip some
245 // reLyX specific things.
248 Token const & t = p.get_token();
249 if (t.cat() == catEscape) {
250 string const command = t.asInput();
251 if (command == "\\begin") {
252 string const name = p.getArg('{', '}');
253 if (name == "environments" || name == "reLyXre")
254 // We understand "reLyXre", but it is
255 // not as powerful as "environments".
256 read_environment(p, name,
258 else if (name == "mathenvironments")
259 read_environment(p, name,
260 known_math_environments);
262 read_command(p, command, known_commands);
269 string documentclass;
271 bool overwrite_files = false;
274 /// return the number of arguments consumed
275 typedef boost::function<int(string const &, string const &)> cmd_helper;
278 int parse_help(string const &, string const &)
280 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
281 "Command line switches (case sensitive):\n"
282 "\t-help summarize tex2lyx usage\n"
283 "\t-f Force creation of .lyx files even if they exist already\n"
284 "\t-userdir dir try to set user directory to dir\n"
285 "\t-sysdir dir try to set system directory to dir\n"
286 "\t-c textclass declare the textclass\n"
287 "\t-n translate a noweb (aka literate programming) file.\n"
288 "\t-s syntaxfile read additional syntax file" << endl;
293 int parse_class(string const & arg, string const &)
296 cerr << "Missing textclass string after -c switch" << endl;
304 int parse_syntaxfile(string const & arg, string const &)
307 cerr << "Missing syntaxfile string after -s switch" << endl;
310 syntaxfile = internal_path(arg);
315 // Filled with the command line arguments "foo" of "-sysdir foo" or
317 string cl_system_support;
318 string cl_user_support;
321 int parse_sysdir(string const & arg, string const &)
324 cerr << "Missing directory for -sysdir switch" << endl;
327 cl_system_support = internal_path(arg);
332 int parse_userdir(string const & arg, string const &)
335 cerr << "Missing directory for -userdir switch" << endl;
338 cl_user_support = internal_path(arg);
343 int parse_force(string const &, string const &)
345 overwrite_files = true;
350 int parse_noweb(string const &, string const &)
357 void easyParse(int & argc, char * argv[])
359 map<string, cmd_helper> cmdmap;
361 cmdmap["-c"] = parse_class;
362 cmdmap["-f"] = parse_force;
363 cmdmap["-s"] = parse_syntaxfile;
364 cmdmap["-help"] = parse_help;
365 cmdmap["--help"] = parse_help;
366 cmdmap["-n"] = parse_noweb;
367 cmdmap["-sysdir"] = parse_sysdir;
368 cmdmap["-userdir"] = parse_userdir;
370 for (int i = 1; i < argc; ++i) {
371 std::map<string, cmd_helper>::const_iterator it
372 = cmdmap.find(argv[i]);
374 // don't complain if not found - may be parsed later
375 if (it == cmdmap.end())
378 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
379 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
381 int const remove = 1 + it->second(arg, arg2);
383 // Now, remove used arguments by shifting
384 // the following ones remove places down.
386 for (int j = i; j < argc; ++j)
387 argv[j] = argv[j + remove];
393 // path of the first parsed file
394 string masterFilePath;
395 // path of the currently parsed file
396 string parentFilePath;
398 } // anonymous namespace
401 string getMasterFilePath()
403 return masterFilePath;
406 string getParentFilePath()
408 return parentFilePath;
415 * Reads tex input from \a is and writes lyx output to \a os.
416 * Uses some common settings for the preamble, so this should only
417 * be used more than once for included documents.
418 * Caution: Overwrites the existing preamble settings if the new document
419 * contains a preamble.
420 * You must ensure that \p parentFilePath is properly set before calling
423 void tex2lyx(std::istream &is, std::ostream &os)
429 TextClass textclass = parse_preamble(p, ss, documentclass);
430 captionlayout = LayoutPtr(Layout::forCaption());
432 active_environments.push_back("document");
433 Context context(true, textclass);
434 parse_text(p, ss, FLAG_END, true, context);
436 // Empty document body. LyX needs at least one paragraph.
437 context.check_layout(ss);
438 context.check_end_layout(ss);
439 ss << "\n\\end_body\n\\end_document\n";
440 active_environments.pop_back();
445 ofstream parsertest("parsertest.tex");
447 parsertest << p.get_token().asInput();
448 // <origfile> and parsertest.tex should now have identical content
453 /// convert TeX from \p infilename to LyX and write it to \p os
454 bool tex2lyx(FileName const & infilename, std::ostream &os)
456 ifstream is(infilename.toFilesystemEncoding().c_str());
458 cerr << "Could not open input file \"" << infilename
459 << "\" for reading." << endl;
462 string const oldParentFilePath = parentFilePath;
463 parentFilePath = onlyPath(infilename.absFilename());
465 parentFilePath = oldParentFilePath;
469 } // anonymous namespace
472 bool tex2lyx(string const &infilename, FileName const &outfilename)
474 if (outfilename.isFileReadable()) {
475 if (overwrite_files) {
476 cerr << "Overwriting existing file "
477 << outfilename << endl;
479 cerr << "Not overwriting existing file "
480 << outfilename << endl;
484 cerr << "Creating file " << outfilename << endl;
486 ofstream os(outfilename.toFilesystemEncoding().c_str());
488 cerr << "Could not open output file \"" << outfilename
489 << "\" for writing." << endl;
493 cerr << "Input file: " << infilename << "\n";
494 cerr << "Output file: " << outfilename << "\n";
496 return tex2lyx(FileName(infilename), os);
502 int main(int argc, char * argv[])
505 fs::path::default_name_check(fs::no_check);
507 easyParse(argc, argv);
510 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
511 "See tex2lyx -help." << endl;
515 lyx::support::os::init(argc, argv);
517 try { support::init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
518 cl_system_support, cl_user_support,
519 support::top_build_dir_is_two_levels_up);
520 } catch (support::ExceptionMessage const & message) {
521 cerr << to_utf8(message.title_) << ":\n"
522 << to_utf8(message.details_) << endl;
523 if (message.type_ == support::ErrorException)
527 // Now every known option is parsed. Look for input and output
528 // file name (the latter is optional).
529 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
530 infilename = makeAbsPath(infilename).absFilename();
534 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
535 if (outfilename != "-")
536 outfilename = makeAbsPath(outfilename).absFilename();
538 outfilename = changeExtension(infilename, ".lyx");
540 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
541 if (system_syntaxfile.empty()) {
542 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
545 read_syntaxfile(system_syntaxfile);
546 if (!syntaxfile.empty())
547 read_syntaxfile(makeAbsPath(syntaxfile));
549 masterFilePath = onlyPath(infilename);
550 parentFilePath = masterFilePath;
552 if (outfilename == "-") {
553 if (tex2lyx(FileName(infilename), cout))
558 if (tex2lyx(infilename, FileName(outfilename)))