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"
37 using namespace lyx::support;
38 using namespace lyx::support::os;
42 // Hacks to allow the thing to link in the lyxlayout stuff
43 LayoutPtr captionlayout;
46 string const trim(string const & a, char const * p)
53 size_t r = a.find_last_not_of(p);
54 size_t l = a.find_first_not_of(p);
56 // Is this the minimal test? (lgb)
57 if (r == string::npos && l == string::npos)
60 return a.substr(l, r - l + 1);
64 void split(string const & s, vector<string> & result, char delim)
66 //cerr << "split 1: '" << s << "'\n";
69 while (getline(is, t, delim))
71 //cerr << "split 2\n";
75 string join(vector<string> const & input, char const * delim)
78 for (size_t i = 0; i != input.size(); ++i) {
87 char const * const * is_known(string const & str, char const * const * what)
89 for ( ; *what; ++what)
97 // current stack of nested environments
98 vector<string> active_environments;
101 string active_environment()
103 return active_environments.empty() ? string() : active_environments.back();
107 CommandMap known_commands;
108 CommandMap known_environments;
109 CommandMap known_math_environments;
112 void add_known_command(string const & command, string const & o1,
113 unsigned optionalsNum)
115 // We have to handle the following cases:
116 // definition o1 o2 invocation result
117 // \newcommand{\foo}{bar} "" false \foo bar
118 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
119 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
120 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
121 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
122 // and the same with \newlyxcommand
123 unsigned int nargs = 0;
124 vector<ArgumentType> arguments;
125 string const opt1 = rtrim(ltrim(o1, "["), "]");
126 if (isStrUnsignedInt(opt1)) {
127 // The command has arguments
128 nargs = convert<unsigned int>(opt1);
129 for (unsigned int i = 0; i < optionalsNum; ++i) {
130 arguments.push_back(optional);
134 for (unsigned int i = 0; i < nargs; ++i)
135 arguments.push_back(required);
136 known_commands[command] = arguments;
140 bool noweb_mode = false;
147 * Read one command definition from the syntax file
149 void read_command(Parser & p, string command, CommandMap & commands)
151 if (p.next_token().asInput() == "*") {
155 vector<ArgumentType> arguments;
156 while (p.next_token().cat() == catBegin ||
157 p.next_token().asInput() == "[") {
158 if (p.next_token().cat() == catBegin) {
159 string const arg = p.getArg('{', '}');
160 if (arg == "translate")
161 arguments.push_back(required);
163 arguments.push_back(verbatim);
166 arguments.push_back(optional);
169 commands[command] = arguments;
174 * Read a class of environments from the syntax file
176 void read_environment(Parser & p, string const & begin,
177 CommandMap & environments)
181 Token const & t = p.get_token();
182 if (t.cat() == catLetter)
183 environment += t.asInput();
184 else if (!environment.empty()) {
186 read_command(p, environment, environments);
189 if (t.cat() == catEscape && t.asInput() == "\\end") {
190 string const end = p.getArg('{', '}');
199 * Read a list of TeX commands from a reLyX compatible syntax file.
200 * Since this list is used after all commands that have a LyX counterpart
201 * are handled, it does not matter that the "syntax.default" file
202 * has almost all of them listed. For the same reason the reLyX-specific
203 * reLyXre environment is ignored.
205 void read_syntaxfile(FileName const & file_name)
207 ifstream is(file_name.toFilesystemEncoding().c_str());
209 cerr << "Could not open syntax file \"" << file_name
210 << "\" for reading." << endl;
213 // We can use our TeX parser, since the syntax of the layout file is
214 // modeled after TeX.
215 // Unknown tokens are just silently ignored, this helps us to skip some
216 // reLyX specific things.
219 Token const & t = p.get_token();
220 if (t.cat() == catEscape) {
221 string const command = t.asInput();
222 if (command == "\\begin") {
223 string const name = p.getArg('{', '}');
224 if (name == "environments" || name == "reLyXre")
225 // We understand "reLyXre", but it is
226 // not as powerful as "environments".
227 read_environment(p, name,
229 else if (name == "mathenvironments")
230 read_environment(p, name,
231 known_math_environments);
233 read_command(p, command, known_commands);
240 string documentclass;
242 bool overwrite_files = false;
245 /// return the number of arguments consumed
246 typedef int (*cmd_helper)(string const &, string const &);
249 int parse_help(string const &, string const &)
251 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
252 "Command line switches (case sensitive):\n"
253 "\t-help summarize tex2lyx usage\n"
254 "\t-f Force creation of .lyx files even if they exist already\n"
255 "\t-userdir dir try to set user directory to dir\n"
256 "\t-sysdir dir try to set system directory to dir\n"
257 "\t-c textclass declare the textclass\n"
258 "\t-n translate a noweb (aka literate programming) file.\n"
259 "\t-s syntaxfile read additional syntax file" << endl;
264 int parse_class(string const & arg, string const &)
267 cerr << "Missing textclass string after -c switch" << endl;
275 int parse_syntaxfile(string const & arg, string const &)
278 cerr << "Missing syntaxfile string after -s switch" << endl;
281 syntaxfile = internal_path(arg);
286 // Filled with the command line arguments "foo" of "-sysdir foo" or
288 string cl_system_support;
289 string cl_user_support;
292 int parse_sysdir(string const & arg, string const &)
295 cerr << "Missing directory for -sysdir switch" << endl;
298 cl_system_support = internal_path(arg);
303 int parse_userdir(string const & arg, string const &)
306 cerr << "Missing directory for -userdir switch" << endl;
309 cl_user_support = internal_path(arg);
314 int parse_force(string const &, string const &)
316 overwrite_files = true;
321 int parse_noweb(string const &, string const &)
328 void easyParse(int & argc, char * argv[])
330 map<string, cmd_helper> cmdmap;
332 cmdmap["-c"] = parse_class;
333 cmdmap["-f"] = parse_force;
334 cmdmap["-s"] = parse_syntaxfile;
335 cmdmap["-help"] = parse_help;
336 cmdmap["--help"] = parse_help;
337 cmdmap["-n"] = parse_noweb;
338 cmdmap["-sysdir"] = parse_sysdir;
339 cmdmap["-userdir"] = parse_userdir;
341 for (int i = 1; i < argc; ++i) {
342 map<string, cmd_helper>::const_iterator it
343 = cmdmap.find(argv[i]);
345 // don't complain if not found - may be parsed later
346 if (it == cmdmap.end())
349 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
350 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
352 int const remove = 1 + it->second(arg, arg2);
354 // Now, remove used arguments by shifting
355 // the following ones remove places down.
357 for (int j = i; j < argc; ++j)
358 argv[j] = argv[j + remove];
364 // path of the first parsed file
365 string masterFilePath;
366 // path of the currently parsed file
367 string parentFilePath;
369 } // anonymous namespace
372 string getMasterFilePath()
374 return masterFilePath;
377 string getParentFilePath()
379 return parentFilePath;
386 * Reads tex input from \a is and writes lyx output to \a os.
387 * Uses some common settings for the preamble, so this should only
388 * be used more than once for included documents.
389 * Caution: Overwrites the existing preamble settings if the new document
390 * contains a preamble.
391 * You must ensure that \p parentFilePath is properly set before calling
394 void tex2lyx(istream & is, ostream & os)
400 TextClass textclass = parse_preamble(p, ss, documentclass);
401 captionlayout = LayoutPtr(Layout::forCaption());
403 active_environments.push_back("document");
404 Context context(true, textclass);
405 parse_text(p, ss, FLAG_END, true, context);
407 // Empty document body. LyX needs at least one paragraph.
408 context.check_layout(ss);
409 context.check_end_layout(ss);
410 ss << "\n\\end_body\n\\end_document\n";
411 active_environments.pop_back();
416 ofstream parsertest("parsertest.tex");
418 parsertest << p.get_token().asInput();
419 // <origfile> and parsertest.tex should now have identical content
424 /// convert TeX from \p infilename to LyX and write it to \p os
425 bool tex2lyx(FileName const & infilename, ostream & os)
427 ifstream is(infilename.toFilesystemEncoding().c_str());
429 cerr << "Could not open input file \"" << infilename
430 << "\" for reading." << endl;
433 string const oldParentFilePath = parentFilePath;
434 parentFilePath = onlyPath(infilename.absFilename());
436 parentFilePath = oldParentFilePath;
440 } // anonymous namespace
443 bool tex2lyx(string const & infilename, FileName const & outfilename)
445 if (outfilename.isReadableFile()) {
446 if (overwrite_files) {
447 cerr << "Overwriting existing file "
448 << outfilename << endl;
450 cerr << "Not overwriting existing file "
451 << outfilename << endl;
455 cerr << "Creating file " << outfilename << endl;
457 ofstream os(outfilename.toFilesystemEncoding().c_str());
459 cerr << "Could not open output file \"" << outfilename
460 << "\" for writing." << endl;
464 cerr << "Input file: " << infilename << "\n";
465 cerr << "Output file: " << outfilename << "\n";
467 return tex2lyx(FileName(infilename), os);
473 int main(int argc, char * argv[])
477 lyxerr.setStream(cerr);
479 easyParse(argc, argv);
482 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
483 "See tex2lyx -help." << endl;
487 os::init(argc, argv);
489 try { init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
490 cl_system_support, cl_user_support,
491 top_build_dir_is_two_levels_up);
492 } catch (ExceptionMessage const & message) {
493 cerr << to_utf8(message.title_) << ":\n"
494 << to_utf8(message.details_) << endl;
495 if (message.type_ == ErrorException)
499 // Now every known option is parsed. Look for input and output
500 // file name (the latter is optional).
501 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
502 infilename = makeAbsPath(infilename).absFilename();
506 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
507 if (outfilename != "-")
508 outfilename = makeAbsPath(outfilename).absFilename();
510 outfilename = changeExtension(infilename, ".lyx");
512 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
513 if (system_syntaxfile.empty()) {
514 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
517 read_syntaxfile(system_syntaxfile);
518 if (!syntaxfile.empty())
519 read_syntaxfile(makeAbsPath(syntaxfile));
521 masterFilePath = onlyPath(infilename);
522 parentFilePath = masterFilePath;
524 if (outfilename == "-") {
525 if (tex2lyx(FileName(infilename), cout))
530 if (tex2lyx(infilename, FileName(outfilename)))