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;
66 using support::isFileReadable;
68 namespace fs = boost::filesystem;
71 // Hacks to allow the thing to link in the lyxlayout stuff
72 LyXErr lyxerr(std::cerr.rdbuf());
75 string const trim(string const & a, char const * p)
82 string::size_type r = a.find_last_not_of(p);
83 string::size_type l = a.find_first_not_of(p);
85 // Is this the minimal test? (lgb)
86 if (r == string::npos && l == string::npos)
89 return a.substr(l, r - l + 1);
93 void split(string const & s, vector<string> & result, char delim)
95 //cerr << "split 1: '" << s << "'\n";
98 while (getline(is, t, delim))
100 //cerr << "split 2\n";
104 string join(vector<string> const & input, char const * delim)
107 for (size_t i = 0; i < input.size(); ++i) {
116 char const * const * is_known(string const & str, char const * const * what)
118 for ( ; *what; ++what)
126 // current stack of nested environments
127 vector<string> active_environments;
130 string active_environment()
132 return active_environments.empty() ? string() : active_environments.back();
136 CommandMap known_commands;
137 CommandMap known_environments;
138 CommandMap known_math_environments;
141 void add_known_command(string const & command, string const & o1,
144 // We have to handle the following cases:
145 // definition o1 o2 invocation result
146 // \newcommand{\foo}{bar} "" false \foo bar
147 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
148 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
149 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
150 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
151 unsigned int nargs = 0;
152 vector<ArgumentType> arguments;
153 string const opt1 = rtrim(ltrim(o1, "["), "]");
154 if (isStrUnsignedInt(opt1)) {
155 // The command has arguments
156 nargs = convert<unsigned int>(opt1);
157 if (nargs > 0 && o2) {
158 // The first argument is optional
159 arguments.push_back(optional);
163 for (unsigned int i = 0; i < nargs; ++i)
164 arguments.push_back(required);
165 known_commands[command] = arguments;
169 bool noweb_mode = false;
176 * Read one command definition from the syntax file
178 void read_command(Parser & p, string command, CommandMap & commands) {
179 if (p.next_token().asInput() == "*") {
183 vector<ArgumentType> arguments;
184 while (p.next_token().cat() == catBegin ||
185 p.next_token().asInput() == "[") {
186 if (p.next_token().cat() == catBegin) {
187 string const arg = p.getArg('{', '}');
188 if (arg == "translate")
189 arguments.push_back(required);
191 arguments.push_back(verbatim);
194 arguments.push_back(optional);
197 commands[command] = arguments;
202 * Read a class of environments from the syntax file
204 void read_environment(Parser & p, string const & begin,
205 CommandMap & environments)
209 Token const & t = p.get_token();
210 if (t.cat() == catLetter)
211 environment += t.asInput();
212 else if (!environment.empty()) {
214 read_command(p, environment, environments);
217 if (t.cat() == catEscape && t.asInput() == "\\end") {
218 string const end = p.getArg('{', '}');
227 * Read a list of TeX commands from a reLyX compatible syntax file.
228 * Since this list is used after all commands that have a LyX counterpart
229 * are handled, it does not matter that the "syntax.default" file
230 * has almost all of them listed. For the same reason the reLyX-specific
231 * reLyXre environment is ignored.
233 void read_syntaxfile(FileName const & file_name)
235 ifstream is(file_name.toFilesystemEncoding().c_str());
237 cerr << "Could not open syntax file \"" << file_name
238 << "\" for reading." << endl;
241 // We can use our TeX parser, since the syntax of the layout file is
242 // modeled after TeX.
243 // Unknown tokens are just silently ignored, this helps us to skip some
244 // reLyX specific things.
247 Token const & t = p.get_token();
248 if (t.cat() == catEscape) {
249 string const command = t.asInput();
250 if (command == "\\begin") {
251 string const name = p.getArg('{', '}');
252 if (name == "environments" || name == "reLyXre")
253 // We understand "reLyXre", but it is
254 // not as powerful as "environments".
255 read_environment(p, name,
257 else if (name == "mathenvironments")
258 read_environment(p, name,
259 known_math_environments);
261 read_command(p, command, known_commands);
268 string documentclass;
270 bool overwrite_files = false;
273 /// return the number of arguments consumed
274 typedef boost::function<int(string const &, string const &)> cmd_helper;
277 int parse_help(string const &, string const &)
279 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
280 "Command line switches (case sensitive):\n"
281 "\t-help summarize tex2lyx usage\n"
282 "\t-f Force creation of .lyx files even if they exist already\n"
283 "\t-userdir dir try to set user directory to dir\n"
284 "\t-sysdir dir try to set system directory to dir\n"
285 "\t-c textclass declare the textclass\n"
286 "\t-n translate a noweb (aka literate programming) file.\n"
287 "\t-s syntaxfile read additional syntax file" << endl;
292 int parse_class(string const & arg, string const &)
295 cerr << "Missing textclass string after -c switch" << endl;
303 int parse_syntaxfile(string const & arg, string const &)
306 cerr << "Missing syntaxfile string after -s switch" << endl;
314 // Filled with the command line arguments "foo" of "-sysdir foo" or
316 string cl_system_support;
317 string cl_user_support;
320 int parse_sysdir(string const & arg, string const &)
323 cerr << "Missing directory for -sysdir switch" << endl;
326 cl_system_support = arg;
331 int parse_userdir(string const & arg, string const &)
334 cerr << "Missing directory for -userdir switch" << endl;
337 cl_user_support = arg;
342 int parse_force(string const &, string const &)
344 overwrite_files = true;
349 int parse_noweb(string const &, string const &)
356 void easyParse(int & argc, char * argv[])
358 map<string, cmd_helper> cmdmap;
360 cmdmap["-c"] = parse_class;
361 cmdmap["-f"] = parse_force;
362 cmdmap["-s"] = parse_syntaxfile;
363 cmdmap["-help"] = parse_help;
364 cmdmap["--help"] = parse_help;
365 cmdmap["-n"] = parse_noweb;
366 cmdmap["-sysdir"] = parse_sysdir;
367 cmdmap["-userdir"] = parse_userdir;
369 for (int i = 1; i < argc; ++i) {
370 std::map<string, cmd_helper>::const_iterator it
371 = cmdmap.find(argv[i]);
373 // don't complain if not found - may be parsed later
374 if (it == cmdmap.end())
377 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
378 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
380 int const remove = 1 + it->second(arg, arg2);
382 // Now, remove used arguments by shifting
383 // the following ones remove places down.
385 for (int j = i; j < argc; ++j)
386 argv[j] = argv[j + remove];
392 // path of the first parsed file
393 string masterFilePath;
394 // path of the currently parsed file
395 string parentFilePath;
397 } // anonymous namespace
400 string getMasterFilePath()
402 return masterFilePath;
405 string getParentFilePath()
407 return parentFilePath;
414 * Reads tex input from \a is and writes lyx output to \a os.
415 * Uses some common settings for the preamble, so this should only
416 * be used more than once for included documents.
417 * Caution: Overwrites the existing preamble settings if the new document
418 * contains a preamble.
419 * You must ensure that \p parentFilePath is properly set before calling
422 void tex2lyx(std::istream &is, std::ostream &os)
428 TextClass textclass = parse_preamble(p, ss, documentclass);
430 active_environments.push_back("document");
431 Context context(true, textclass);
432 parse_text(p, ss, FLAG_END, true, context);
434 // Empty document body. LyX needs at least one paragraph.
435 context.check_layout(ss);
436 context.check_end_layout(ss);
437 ss << "\n\\end_body\n\\end_document\n";
438 active_environments.pop_back();
443 ofstream parsertest("parsertest.tex");
445 parsertest << p.get_token().asInput();
446 // <origfile> and parsertest.tex should now have identical content
451 /// convert TeX from \p infilename to LyX and write it to \p os
452 bool tex2lyx(FileName const & infilename, std::ostream &os)
454 ifstream is(infilename.toFilesystemEncoding().c_str());
456 cerr << "Could not open input file \"" << infilename
457 << "\" for reading." << endl;
460 string const oldParentFilePath = parentFilePath;
461 parentFilePath = onlyPath(infilename.absFilename());
463 parentFilePath = oldParentFilePath;
467 } // anonymous namespace
470 bool tex2lyx(string const &infilename, FileName const &outfilename)
472 if (isFileReadable(outfilename)) {
473 if (overwrite_files) {
474 cerr << "Overwriting existing file "
475 << outfilename << endl;
477 cerr << "Not overwriting existing file "
478 << outfilename << endl;
482 cerr << "Creating file " << outfilename << endl;
484 ofstream os(outfilename.toFilesystemEncoding().c_str());
486 cerr << "Could not open output file \"" << outfilename
487 << "\" for writing." << endl;
491 cerr << "Input file: " << infilename << "\n";
492 cerr << "Output file: " << outfilename << "\n";
494 return tex2lyx(FileName(infilename), os);
500 int main(int argc, char * argv[])
503 fs::path::default_name_check(fs::no_check);
505 easyParse(argc, argv);
508 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
509 "See tex2lyx -help." << endl;
513 lyx::support::os::init(argc, argv);
515 try { support::init_package(to_utf8(from_local8bit(argv[0])),
516 cl_system_support, cl_user_support,
517 support::top_build_dir_is_two_levels_up);
518 } catch (support::ExceptionMessage const & message) {
519 cerr << to_utf8(message.title_) << ":\n"
520 << to_utf8(message.details_) << endl;
521 if (message.type_ == support::ErrorException)
525 // Now every known option is parsed. Look for input and output
526 // file name (the latter is optional).
527 string const infilename = makeAbsPath(to_utf8(from_local8bit(argv[1]))).absFilename();
530 outfilename = to_utf8(from_local8bit(argv[2]));
531 if (outfilename != "-")
532 outfilename = makeAbsPath(to_utf8(from_local8bit(argv[2]))).absFilename();
534 outfilename = changeExtension(infilename, ".lyx");
536 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
537 if (system_syntaxfile.empty()) {
538 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
541 read_syntaxfile(system_syntaxfile);
542 if (!syntaxfile.empty())
543 read_syntaxfile(makeAbsPath(syntaxfile));
545 masterFilePath = onlyPath(infilename);
546 parentFilePath = masterFilePath;
548 if (outfilename == "-") {
549 if (tex2lyx(FileName(infilename), cout))
554 if (tex2lyx(infilename, FileName(outfilename)))