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.
18 #include "TextClass.h"
21 #include "support/convert.h"
22 #include "support/debug.h"
23 #include "support/ExceptionMessage.h"
24 #include "support/filetools.h"
25 #include "support/lstrings.h"
26 #include "support/os.h"
27 #include "support/Package.h"
38 using namespace lyx::support;
39 using namespace lyx::support::os;
43 string const trim(string const & a, char const * p)
50 size_t r = a.find_last_not_of(p);
51 size_t l = a.find_first_not_of(p);
53 // Is this the minimal test? (lgb)
54 if (r == string::npos && l == string::npos)
57 return a.substr(l, r - l + 1);
61 void split(string const & s, vector<string> & result, char delim)
63 //cerr << "split 1: '" << s << "'\n";
66 while (getline(is, t, delim))
68 //cerr << "split 2\n";
72 string join(vector<string> const & input, char const * delim)
75 for (size_t i = 0; i != input.size(); ++i) {
84 char const * const * is_known(string const & str, char const * const * what)
86 for ( ; *what; ++what)
94 // current stack of nested environments
95 vector<string> active_environments;
98 string active_environment()
100 return active_environments.empty() ? string() : active_environments.back();
104 CommandMap known_commands;
105 CommandMap known_environments;
106 CommandMap known_math_environments;
109 void add_known_command(string const & command, string const & o1,
110 unsigned optionalsNum)
112 // We have to handle the following cases:
113 // definition o1 o2 invocation result
114 // \newcommand{\foo}{bar} "" false \foo bar
115 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
116 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
117 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
118 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
119 // and the same with \newlyxcommand
120 unsigned int nargs = 0;
121 vector<ArgumentType> arguments;
122 string const opt1 = rtrim(ltrim(o1, "["), "]");
123 if (isStrUnsignedInt(opt1)) {
124 // The command has arguments
125 nargs = convert<unsigned int>(opt1);
126 for (unsigned int i = 0; i < optionalsNum; ++i) {
127 arguments.push_back(optional);
131 for (unsigned int i = 0; i < nargs; ++i)
132 arguments.push_back(required);
133 known_commands[command] = arguments;
137 bool noweb_mode = false;
144 * Read one command definition from the syntax file
146 void read_command(Parser & p, string command, CommandMap & commands)
148 if (p.next_token().asInput() == "*") {
152 vector<ArgumentType> arguments;
153 while (p.next_token().cat() == catBegin ||
154 p.next_token().asInput() == "[") {
155 if (p.next_token().cat() == catBegin) {
156 string const arg = p.getArg('{', '}');
157 if (arg == "translate")
158 arguments.push_back(required);
160 arguments.push_back(verbatim);
163 arguments.push_back(optional);
166 commands[command] = arguments;
171 * Read a class of environments from the syntax file
173 void read_environment(Parser & p, string const & begin,
174 CommandMap & environments)
178 Token const & t = p.get_token();
179 if (t.cat() == catLetter)
180 environment += t.asInput();
181 else if (!environment.empty()) {
183 read_command(p, environment, environments);
186 if (t.cat() == catEscape && t.asInput() == "\\end") {
187 string const end = p.getArg('{', '}');
196 * Read a list of TeX commands from a reLyX compatible syntax file.
197 * Since this list is used after all commands that have a LyX counterpart
198 * are handled, it does not matter that the "syntax.default" file
199 * has almost all of them listed. For the same reason the reLyX-specific
200 * reLyXre environment is ignored.
202 void read_syntaxfile(FileName const & file_name)
204 ifstream is(file_name.toFilesystemEncoding().c_str());
206 cerr << "Could not open syntax file \"" << file_name
207 << "\" for reading." << endl;
210 // We can use our TeX parser, since the syntax of the layout file is
211 // modeled after TeX.
212 // Unknown tokens are just silently ignored, this helps us to skip some
213 // reLyX specific things.
216 Token const & t = p.get_token();
217 if (t.cat() == catEscape) {
218 string const command = t.asInput();
219 if (command == "\\begin") {
220 string const name = p.getArg('{', '}');
221 if (name == "environments" || name == "reLyXre")
222 // We understand "reLyXre", but it is
223 // not as powerful as "environments".
224 read_environment(p, name,
226 else if (name == "mathenvironments")
227 read_environment(p, name,
228 known_math_environments);
230 read_command(p, command, known_commands);
237 string documentclass;
239 bool overwrite_files = false;
242 /// return the number of arguments consumed
243 typedef int (*cmd_helper)(string const &, string const &);
246 int parse_help(string const &, string const &)
248 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
249 "Command line switches (case sensitive):\n"
250 "\t-help summarize tex2lyx usage\n"
251 "\t-f Force creation of .lyx files even if they exist already\n"
252 "\t-userdir dir try to set user directory to dir\n"
253 "\t-sysdir dir try to set system directory to dir\n"
254 "\t-c textclass declare the textclass\n"
255 "\t-n translate a noweb (aka literate programming) file.\n"
256 "\t-s syntaxfile read additional syntax file" << endl;
261 int parse_class(string const & arg, string const &)
264 cerr << "Missing textclass string after -c switch" << endl;
272 int parse_syntaxfile(string const & arg, string const &)
275 cerr << "Missing syntaxfile string after -s switch" << endl;
278 syntaxfile = internal_path(arg);
283 // Filled with the command line arguments "foo" of "-sysdir foo" or
285 string cl_system_support;
286 string cl_user_support;
289 int parse_sysdir(string const & arg, string const &)
292 cerr << "Missing directory for -sysdir switch" << endl;
295 cl_system_support = internal_path(arg);
300 int parse_userdir(string const & arg, string const &)
303 cerr << "Missing directory for -userdir switch" << endl;
306 cl_user_support = internal_path(arg);
311 int parse_force(string const &, string const &)
313 overwrite_files = true;
318 int parse_noweb(string const &, string const &)
325 void easyParse(int & argc, char * argv[])
327 map<string, cmd_helper> cmdmap;
329 cmdmap["-c"] = parse_class;
330 cmdmap["-f"] = parse_force;
331 cmdmap["-s"] = parse_syntaxfile;
332 cmdmap["-help"] = parse_help;
333 cmdmap["--help"] = parse_help;
334 cmdmap["-n"] = parse_noweb;
335 cmdmap["-sysdir"] = parse_sysdir;
336 cmdmap["-userdir"] = parse_userdir;
338 for (int i = 1; i < argc; ++i) {
339 map<string, cmd_helper>::const_iterator it
340 = cmdmap.find(argv[i]);
342 // don't complain if not found - may be parsed later
343 if (it == cmdmap.end())
346 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
347 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
349 int const remove = 1 + it->second(arg, arg2);
351 // Now, remove used arguments by shifting
352 // the following ones remove places down.
354 for (int j = i; j < argc; ++j)
355 argv[j] = argv[j + remove];
361 // path of the first parsed file
362 string masterFilePath;
363 // path of the currently parsed file
364 string parentFilePath;
366 } // anonymous namespace
369 string getMasterFilePath()
371 return masterFilePath;
374 string getParentFilePath()
376 return parentFilePath;
383 * Reads tex input from \a is and writes lyx output to \a os.
384 * Uses some common settings for the preamble, so this should only
385 * be used more than once for included documents.
386 * Caution: Overwrites the existing preamble settings if the new document
387 * contains a preamble.
388 * You must ensure that \p parentFilePath is properly set before calling
391 void tex2lyx(istream & is, ostream & os)
397 TeX2LyXDocClass textclass;
398 parse_preamble(p, ss, documentclass, textclass);
400 active_environments.push_back("document");
401 Context context(true, textclass);
402 parse_text(p, ss, FLAG_END, true, context);
404 // Empty document body. LyX needs at least one paragraph.
405 context.check_layout(ss);
406 context.check_end_layout(ss);
407 ss << "\n\\end_body\n\\end_document\n";
408 active_environments.pop_back();
413 ofstream parsertest("parsertest.tex");
415 parsertest << p.get_token().asInput();
416 // <origfile> and parsertest.tex should now have identical content
421 /// convert TeX from \p infilename to LyX and write it to \p os
422 bool tex2lyx(FileName const & infilename, ostream & os)
424 ifstream is(infilename.toFilesystemEncoding().c_str());
426 cerr << "Could not open input file \"" << infilename
427 << "\" for reading." << endl;
430 string const oldParentFilePath = parentFilePath;
431 parentFilePath = onlyPath(infilename.absFilename());
433 parentFilePath = oldParentFilePath;
437 } // anonymous namespace
440 bool tex2lyx(string const & infilename, FileName const & outfilename)
442 if (outfilename.isReadableFile()) {
443 if (overwrite_files) {
444 cerr << "Overwriting existing file "
445 << outfilename << endl;
447 cerr << "Not overwriting existing file "
448 << outfilename << endl;
452 cerr << "Creating file " << outfilename << endl;
454 ofstream os(outfilename.toFilesystemEncoding().c_str());
456 cerr << "Could not open output file \"" << outfilename
457 << "\" for writing." << endl;
461 cerr << "Input file: " << infilename << "\n";
462 cerr << "Output file: " << outfilename << "\n";
464 return tex2lyx(FileName(infilename), os);
470 int main(int argc, char * argv[])
474 lyxerr.setStream(cerr);
476 easyParse(argc, argv);
479 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
480 "See tex2lyx -help." << endl;
484 os::init(argc, argv);
486 try { init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
487 cl_system_support, cl_user_support,
488 top_build_dir_is_two_levels_up);
489 } catch (ExceptionMessage const & message) {
490 cerr << to_utf8(message.title_) << ":\n"
491 << to_utf8(message.details_) << endl;
492 if (message.type_ == ErrorException)
496 // Now every known option is parsed. Look for input and output
497 // file name (the latter is optional).
498 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
499 infilename = makeAbsPath(infilename).absFilename();
503 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
504 if (outfilename != "-")
505 outfilename = makeAbsPath(outfilename).absFilename();
507 outfilename = changeExtension(infilename, ".lyx");
509 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
510 if (system_syntaxfile.empty()) {
511 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
514 read_syntaxfile(system_syntaxfile);
515 if (!syntaxfile.empty())
516 read_syntaxfile(makeAbsPath(syntaxfile));
518 masterFilePath = onlyPath(infilename);
519 parentFilePath = masterFilePath;
521 if (outfilename == "-") {
522 if (tex2lyx(FileName(infilename), cout))
527 if (tex2lyx(infilename, FileName(outfilename)))