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/assert.h"
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/ExceptionMessage.h"
25 #include "support/filetools.h"
26 #include "support/lstrings.h"
27 #include "support/os.h"
28 #include "support/Package.h"
39 using namespace lyx::support;
40 using namespace lyx::support::os;
44 string const trim(string const & a, char const * p)
51 size_t r = a.find_last_not_of(p);
52 size_t l = a.find_first_not_of(p);
54 // Is this the minimal test? (lgb)
55 if (r == string::npos && l == string::npos)
58 return a.substr(l, r - l + 1);
62 void split(string const & s, vector<string> & result, char delim)
64 //cerr << "split 1: '" << s << "'\n";
67 while (getline(is, t, delim))
69 //cerr << "split 2\n";
73 string join(vector<string> const & input, char const * delim)
76 for (size_t i = 0; i != input.size(); ++i) {
85 char const * const * is_known(string const & str, char const * const * what)
87 for ( ; *what; ++what)
95 // current stack of nested environments
96 vector<string> active_environments;
99 string active_environment()
101 return active_environments.empty() ? string() : active_environments.back();
105 CommandMap known_commands;
106 CommandMap known_environments;
107 CommandMap known_math_environments;
110 void add_known_command(string const & command, string const & o1,
111 unsigned optionalsNum)
113 // We have to handle the following cases:
114 // definition o1 o2 invocation result
115 // \newcommand{\foo}{bar} "" false \foo bar
116 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
117 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
118 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
119 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
120 // and the same with \newlyxcommand
121 unsigned int nargs = 0;
122 vector<ArgumentType> arguments;
123 string const opt1 = rtrim(ltrim(o1, "["), "]");
124 if (isStrUnsignedInt(opt1)) {
125 // The command has arguments
126 nargs = convert<unsigned int>(opt1);
127 for (unsigned int i = 0; i < optionalsNum; ++i) {
128 arguments.push_back(optional);
132 for (unsigned int i = 0; i < nargs; ++i)
133 arguments.push_back(required);
134 known_commands[command] = arguments;
138 bool noweb_mode = false;
145 * Read one command definition from the syntax file
147 void read_command(Parser & p, string command, CommandMap & commands)
149 if (p.next_token().asInput() == "*") {
153 vector<ArgumentType> arguments;
154 while (p.next_token().cat() == catBegin ||
155 p.next_token().asInput() == "[") {
156 if (p.next_token().cat() == catBegin) {
157 string const arg = p.getArg('{', '}');
158 if (arg == "translate")
159 arguments.push_back(required);
161 arguments.push_back(verbatim);
164 arguments.push_back(optional);
167 commands[command] = arguments;
172 * Read a class of environments from the syntax file
174 void read_environment(Parser & p, string const & begin,
175 CommandMap & environments)
179 Token const & t = p.get_token();
180 if (t.cat() == catLetter)
181 environment += t.asInput();
182 else if (!environment.empty()) {
184 read_command(p, environment, environments);
187 if (t.cat() == catEscape && t.asInput() == "\\end") {
188 string const end = p.getArg('{', '}');
197 * Read a list of TeX commands from a reLyX compatible syntax file.
198 * Since this list is used after all commands that have a LyX counterpart
199 * are handled, it does not matter that the "syntax.default" file
200 * has almost all of them listed. For the same reason the reLyX-specific
201 * reLyXre environment is ignored.
203 void read_syntaxfile(FileName const & file_name)
205 ifstream is(file_name.toFilesystemEncoding().c_str());
207 cerr << "Could not open syntax file \"" << file_name
208 << "\" for reading." << endl;
211 // We can use our TeX parser, since the syntax of the layout file is
212 // modeled after TeX.
213 // Unknown tokens are just silently ignored, this helps us to skip some
214 // reLyX specific things.
217 Token const & t = p.get_token();
218 if (t.cat() == catEscape) {
219 string const command = t.asInput();
220 if (command == "\\begin") {
221 string const name = p.getArg('{', '}');
222 if (name == "environments" || name == "reLyXre")
223 // We understand "reLyXre", but it is
224 // not as powerful as "environments".
225 read_environment(p, name,
227 else if (name == "mathenvironments")
228 read_environment(p, name,
229 known_math_environments);
231 read_command(p, command, known_commands);
238 string documentclass;
240 bool overwrite_files = false;
243 /// return the number of arguments consumed
244 typedef int (*cmd_helper)(string const &, string const &);
247 int parse_help(string const &, string const &)
249 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
250 "Command line switches (case sensitive):\n"
251 "\t-help summarize tex2lyx usage\n"
252 "\t-f Force creation of .lyx files even if they exist already\n"
253 "\t-userdir dir try to set user directory to dir\n"
254 "\t-sysdir dir try to set system directory to dir\n"
255 "\t-c textclass declare the textclass\n"
256 "\t-n translate a noweb (aka literate programming) file.\n"
257 "\t-s syntaxfile read additional syntax file" << endl;
262 int parse_class(string const & arg, string const &)
265 cerr << "Missing textclass string after -c switch" << endl;
273 int parse_syntaxfile(string const & arg, string const &)
276 cerr << "Missing syntaxfile string after -s switch" << endl;
279 syntaxfile = internal_path(arg);
284 // Filled with the command line arguments "foo" of "-sysdir foo" or
286 string cl_system_support;
287 string cl_user_support;
290 int parse_sysdir(string const & arg, string const &)
293 cerr << "Missing directory for -sysdir switch" << endl;
296 cl_system_support = internal_path(arg);
301 int parse_userdir(string const & arg, string const &)
304 cerr << "Missing directory for -userdir switch" << endl;
307 cl_user_support = internal_path(arg);
312 int parse_force(string const &, string const &)
314 overwrite_files = true;
319 int parse_noweb(string const &, string const &)
326 void easyParse(int & argc, char * argv[])
328 map<string, cmd_helper> cmdmap;
330 cmdmap["-c"] = parse_class;
331 cmdmap["-f"] = parse_force;
332 cmdmap["-s"] = parse_syntaxfile;
333 cmdmap["-help"] = parse_help;
334 cmdmap["--help"] = parse_help;
335 cmdmap["-n"] = parse_noweb;
336 cmdmap["-sysdir"] = parse_sysdir;
337 cmdmap["-userdir"] = parse_userdir;
339 for (int i = 1; i < argc; ++i) {
340 map<string, cmd_helper>::const_iterator it
341 = cmdmap.find(argv[i]);
343 // don't complain if not found - may be parsed later
344 if (it == cmdmap.end())
347 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
348 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
350 int const remove = 1 + it->second(arg, arg2);
352 // Now, remove used arguments by shifting
353 // the following ones remove places down.
355 for (int j = i; j < argc; ++j)
356 argv[j] = argv[j + remove];
362 // path of the first parsed file
363 string masterFilePath;
364 // path of the currently parsed file
365 string parentFilePath;
367 } // anonymous namespace
370 string getMasterFilePath()
372 return masterFilePath;
375 string getParentFilePath()
377 return parentFilePath;
384 * Reads tex input from \a is and writes lyx output to \a os.
385 * Uses some common settings for the preamble, so this should only
386 * be used more than once for included documents.
387 * Caution: Overwrites the existing preamble settings if the new document
388 * contains a preamble.
389 * You must ensure that \p parentFilePath is properly set before calling
392 void tex2lyx(istream & is, ostream & os)
398 TeX2LyXDocClass textclass;
399 parse_preamble(p, ss, documentclass, textclass);
401 active_environments.push_back("document");
402 Context context(true, textclass);
403 parse_text(p, ss, FLAG_END, true, context);
405 // Empty document body. LyX needs at least one paragraph.
406 context.check_layout(ss);
407 context.check_end_layout(ss);
408 ss << "\n\\end_body\n\\end_document\n";
409 active_environments.pop_back();
414 ofstream parsertest("parsertest.tex");
416 parsertest << p.get_token().asInput();
417 // <origfile> and parsertest.tex should now have identical content
422 /// convert TeX from \p infilename to LyX and write it to \p os
423 bool tex2lyx(FileName const & infilename, ostream & os)
425 ifstream is(infilename.toFilesystemEncoding().c_str());
427 cerr << "Could not open input file \"" << infilename
428 << "\" for reading." << endl;
431 string const oldParentFilePath = parentFilePath;
432 parentFilePath = onlyPath(infilename.absFilename());
434 parentFilePath = oldParentFilePath;
438 } // anonymous namespace
441 bool tex2lyx(string const & infilename, FileName const & outfilename)
443 if (outfilename.isReadableFile()) {
444 if (overwrite_files) {
445 cerr << "Overwriting existing file "
446 << outfilename << endl;
448 cerr << "Not overwriting existing file "
449 << outfilename << endl;
453 cerr << "Creating file " << outfilename << endl;
455 ofstream os(outfilename.toFilesystemEncoding().c_str());
457 cerr << "Could not open output file \"" << outfilename
458 << "\" for writing." << endl;
462 cerr << "Input file: " << infilename << "\n";
463 cerr << "Output file: " << outfilename << "\n";
465 return tex2lyx(FileName(infilename), os);
471 int main(int argc, char * argv[])
475 lyxerr.setStream(cerr);
477 easyParse(argc, argv);
480 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
481 "See tex2lyx -help." << endl;
485 os::init(argc, argv);
487 try { init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
488 cl_system_support, cl_user_support,
489 top_build_dir_is_two_levels_up);
490 } catch (ExceptionMessage const & message) {
491 cerr << to_utf8(message.title_) << ":\n"
492 << to_utf8(message.details_) << endl;
493 if (message.type_ == ErrorException)
497 // Now every known option is parsed. Look for input and output
498 // file name (the latter is optional).
499 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
500 infilename = makeAbsPath(infilename).absFilename();
504 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
505 if (outfilename != "-")
506 outfilename = makeAbsPath(outfilename).absFilename();
508 outfilename = changeExtension(infilename, ".lyx");
510 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
511 if (system_syntaxfile.empty()) {
512 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
515 read_syntaxfile(system_syntaxfile);
516 if (!syntaxfile.empty())
517 read_syntaxfile(makeAbsPath(syntaxfile));
519 masterFilePath = onlyPath(infilename);
520 parentFilePath = masterFilePath;
522 if (outfilename == "-") {
523 if (tex2lyx(FileName(infilename), cout))
528 if (tex2lyx(infilename, FileName(outfilename)))