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"
28 #include "support/unicode.h"
38 using namespace lyx::support;
39 using namespace lyx::support::os;
43 // Hacks to allow the thing to link in the lyxlayout stuff
44 LayoutPtr captionlayout;
47 string const trim(string const & a, char const * p)
54 size_t r = a.find_last_not_of(p);
55 size_t l = a.find_first_not_of(p);
57 // Is this the minimal test? (lgb)
58 if (r == string::npos && l == string::npos)
61 return a.substr(l, r - l + 1);
65 void split(string const & s, vector<string> & result, char delim)
67 //cerr << "split 1: '" << s << "'\n";
70 while (getline(is, t, delim))
72 //cerr << "split 2\n";
76 string join(vector<string> const & input, char const * delim)
79 for (size_t i = 0; i != input.size(); ++i) {
88 char const * const * is_known(string const & str, char const * const * what)
90 for ( ; *what; ++what)
98 // current stack of nested environments
99 vector<string> active_environments;
102 string active_environment()
104 return active_environments.empty() ? string() : active_environments.back();
108 CommandMap known_commands;
109 CommandMap known_environments;
110 CommandMap known_math_environments;
113 void add_known_command(string const & command, string const & o1,
116 // We have to handle the following cases:
117 // definition o1 o2 invocation result
118 // \newcommand{\foo}{bar} "" false \foo bar
119 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
120 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
121 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
122 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
123 // and the same with \newlyxcommand
124 unsigned int nargs = 0;
125 vector<ArgumentType> arguments;
126 string const opt1 = rtrim(ltrim(o1, "["), "]");
127 if (isStrUnsignedInt(opt1)) {
128 // The command has arguments
129 nargs = convert<unsigned int>(opt1);
130 if (nargs > 0 && o2) {
131 // The first argument is optional
132 arguments.push_back(optional);
136 for (unsigned int i = 0; i < nargs; ++i)
137 arguments.push_back(required);
138 known_commands[command] = arguments;
142 bool noweb_mode = false;
149 * Read one command definition from the syntax file
151 void read_command(Parser & p, string command, CommandMap & commands)
153 if (p.next_token().asInput() == "*") {
157 vector<ArgumentType> arguments;
158 while (p.next_token().cat() == catBegin ||
159 p.next_token().asInput() == "[") {
160 if (p.next_token().cat() == catBegin) {
161 string const arg = p.getArg('{', '}');
162 if (arg == "translate")
163 arguments.push_back(required);
165 arguments.push_back(verbatim);
168 arguments.push_back(optional);
171 commands[command] = arguments;
176 * Read a class of environments from the syntax file
178 void read_environment(Parser & p, string const & begin,
179 CommandMap & environments)
183 Token const & t = p.get_token();
184 if (t.cat() == catLetter)
185 environment += t.asInput();
186 else if (!environment.empty()) {
188 read_command(p, environment, environments);
191 if (t.cat() == catEscape && t.asInput() == "\\end") {
192 string const end = p.getArg('{', '}');
201 * Read a list of TeX commands from a reLyX compatible syntax file.
202 * Since this list is used after all commands that have a LyX counterpart
203 * are handled, it does not matter that the "syntax.default" file
204 * has almost all of them listed. For the same reason the reLyX-specific
205 * reLyXre environment is ignored.
207 void read_syntaxfile(FileName const & file_name)
209 ifstream is(file_name.toFilesystemEncoding().c_str());
211 cerr << "Could not open syntax file \"" << file_name
212 << "\" for reading." << endl;
215 // We can use our TeX parser, since the syntax of the layout file is
216 // modeled after TeX.
217 // Unknown tokens are just silently ignored, this helps us to skip some
218 // reLyX specific things.
221 Token const & t = p.get_token();
222 if (t.cat() == catEscape) {
223 string const command = t.asInput();
224 if (command == "\\begin") {
225 string const name = p.getArg('{', '}');
226 if (name == "environments" || name == "reLyXre")
227 // We understand "reLyXre", but it is
228 // not as powerful as "environments".
229 read_environment(p, name,
231 else if (name == "mathenvironments")
232 read_environment(p, name,
233 known_math_environments);
235 read_command(p, command, known_commands);
242 string documentclass;
244 bool overwrite_files = false;
247 /// return the number of arguments consumed
248 typedef int (*cmd_helper)(string const &, string const &);
251 int parse_help(string const &, string const &)
253 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
254 "Command line switches (case sensitive):\n"
255 "\t-help summarize tex2lyx usage\n"
256 "\t-f Force creation of .lyx files even if they exist already\n"
257 "\t-userdir dir try to set user directory to dir\n"
258 "\t-sysdir dir try to set system directory to dir\n"
259 "\t-c textclass declare the textclass\n"
260 "\t-n translate a noweb (aka literate programming) file.\n"
261 "\t-s syntaxfile read additional syntax file" << endl;
266 int parse_class(string const & arg, string const &)
269 cerr << "Missing textclass string after -c switch" << endl;
277 int parse_syntaxfile(string const & arg, string const &)
280 cerr << "Missing syntaxfile string after -s switch" << endl;
283 syntaxfile = internal_path(arg);
288 // Filled with the command line arguments "foo" of "-sysdir foo" or
290 string cl_system_support;
291 string cl_user_support;
294 int parse_sysdir(string const & arg, string const &)
297 cerr << "Missing directory for -sysdir switch" << endl;
300 cl_system_support = internal_path(arg);
305 int parse_userdir(string const & arg, string const &)
308 cerr << "Missing directory for -userdir switch" << endl;
311 cl_user_support = internal_path(arg);
316 int parse_force(string const &, string const &)
318 overwrite_files = true;
323 int parse_noweb(string const &, string const &)
330 void easyParse(int & argc, char * argv[])
332 map<string, cmd_helper> cmdmap;
334 cmdmap["-c"] = parse_class;
335 cmdmap["-f"] = parse_force;
336 cmdmap["-s"] = parse_syntaxfile;
337 cmdmap["-help"] = parse_help;
338 cmdmap["--help"] = parse_help;
339 cmdmap["-n"] = parse_noweb;
340 cmdmap["-sysdir"] = parse_sysdir;
341 cmdmap["-userdir"] = parse_userdir;
343 for (int i = 1; i < argc; ++i) {
344 map<string, cmd_helper>::const_iterator it
345 = cmdmap.find(argv[i]);
347 // don't complain if not found - may be parsed later
348 if (it == cmdmap.end())
351 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
352 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
354 int const remove = 1 + it->second(arg, arg2);
356 // Now, remove used arguments by shifting
357 // the following ones remove places down.
359 for (int j = i; j < argc; ++j)
360 argv[j] = argv[j + remove];
366 // path of the first parsed file
367 string masterFilePath;
368 // path of the currently parsed file
369 string parentFilePath;
371 } // anonymous namespace
374 string getMasterFilePath()
376 return masterFilePath;
379 string getParentFilePath()
381 return parentFilePath;
388 * Reads tex input from \a is and writes lyx output to \a os.
389 * Uses some common settings for the preamble, so this should only
390 * be used more than once for included documents.
391 * Caution: Overwrites the existing preamble settings if the new document
392 * contains a preamble.
393 * You must ensure that \p parentFilePath is properly set before calling
396 void tex2lyx(istream & is, ostream & os)
402 TextClass textclass = parse_preamble(p, ss, documentclass);
403 captionlayout = LayoutPtr(Layout::forCaption());
405 active_environments.push_back("document");
406 Context context(true, textclass);
407 parse_text(p, ss, FLAG_END, true, context);
409 // Empty document body. LyX needs at least one paragraph.
410 context.check_layout(ss);
411 context.check_end_layout(ss);
412 ss << "\n\\end_body\n\\end_document\n";
413 active_environments.pop_back();
418 ofstream parsertest("parsertest.tex");
420 parsertest << p.get_token().asInput();
421 // <origfile> and parsertest.tex should now have identical content
426 /// convert TeX from \p infilename to LyX and write it to \p os
427 bool tex2lyx(FileName const & infilename, ostream & os)
429 ifstream is(infilename.toFilesystemEncoding().c_str());
431 cerr << "Could not open input file \"" << infilename
432 << "\" for reading." << endl;
435 string const oldParentFilePath = parentFilePath;
436 parentFilePath = onlyPath(infilename.absFilename());
438 parentFilePath = oldParentFilePath;
442 } // anonymous namespace
445 bool tex2lyx(string const & infilename, FileName const & outfilename)
447 if (outfilename.isReadableFile()) {
448 if (overwrite_files) {
449 cerr << "Overwriting existing file "
450 << outfilename << endl;
452 cerr << "Not overwriting existing file "
453 << outfilename << endl;
457 cerr << "Creating file " << outfilename << endl;
459 ofstream os(outfilename.toFilesystemEncoding().c_str());
461 cerr << "Could not open output file \"" << outfilename
462 << "\" for writing." << endl;
466 cerr << "Input file: " << infilename << "\n";
467 cerr << "Output file: " << outfilename << "\n";
469 return tex2lyx(FileName(infilename), os);
475 int main(int argc, char * argv[])
479 lyxerr.setStream(cerr);
481 easyParse(argc, argv);
484 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
485 "See tex2lyx -help." << endl;
489 os::init(argc, argv);
491 try { init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
492 cl_system_support, cl_user_support,
493 top_build_dir_is_two_levels_up);
494 } catch (ExceptionMessage const & message) {
495 cerr << to_utf8(message.title_) << ":\n"
496 << to_utf8(message.details_) << endl;
497 if (message.type_ == ErrorException)
501 // Now every known option is parsed. Look for input and output
502 // file name (the latter is optional).
503 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
504 infilename = makeAbsPath(infilename).absFilename();
508 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
509 if (outfilename != "-")
510 outfilename = makeAbsPath(outfilename).absFilename();
512 outfilename = changeExtension(infilename, ".lyx");
514 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
515 if (system_syntaxfile.empty()) {
516 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
519 read_syntaxfile(system_syntaxfile);
520 if (!syntaxfile.empty())
521 read_syntaxfile(makeAbsPath(syntaxfile));
523 masterFilePath = onlyPath(infilename);
524 parentFilePath = masterFilePath;
526 if (outfilename == "-") {
527 if (tex2lyx(FileName(infilename), cout))
532 if (tex2lyx(infilename, FileName(outfilename)))