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,
114 unsigned optionalsNum)
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 for (unsigned int i = 0; i < optionalsNum; ++i) {
131 arguments.push_back(optional);
135 for (unsigned int i = 0; i < nargs; ++i)
136 arguments.push_back(required);
137 known_commands[command] = arguments;
141 bool noweb_mode = false;
148 * Read one command definition from the syntax file
150 void read_command(Parser & p, string command, CommandMap & commands)
152 if (p.next_token().asInput() == "*") {
156 vector<ArgumentType> arguments;
157 while (p.next_token().cat() == catBegin ||
158 p.next_token().asInput() == "[") {
159 if (p.next_token().cat() == catBegin) {
160 string const arg = p.getArg('{', '}');
161 if (arg == "translate")
162 arguments.push_back(required);
164 arguments.push_back(verbatim);
167 arguments.push_back(optional);
170 commands[command] = arguments;
175 * Read a class of environments from the syntax file
177 void read_environment(Parser & p, string const & begin,
178 CommandMap & environments)
182 Token const & t = p.get_token();
183 if (t.cat() == catLetter)
184 environment += t.asInput();
185 else if (!environment.empty()) {
187 read_command(p, environment, environments);
190 if (t.cat() == catEscape && t.asInput() == "\\end") {
191 string const end = p.getArg('{', '}');
200 * Read a list of TeX commands from a reLyX compatible syntax file.
201 * Since this list is used after all commands that have a LyX counterpart
202 * are handled, it does not matter that the "syntax.default" file
203 * has almost all of them listed. For the same reason the reLyX-specific
204 * reLyXre environment is ignored.
206 void read_syntaxfile(FileName const & file_name)
208 ifstream is(file_name.toFilesystemEncoding().c_str());
210 cerr << "Could not open syntax file \"" << file_name
211 << "\" for reading." << endl;
214 // We can use our TeX parser, since the syntax of the layout file is
215 // modeled after TeX.
216 // Unknown tokens are just silently ignored, this helps us to skip some
217 // reLyX specific things.
220 Token const & t = p.get_token();
221 if (t.cat() == catEscape) {
222 string const command = t.asInput();
223 if (command == "\\begin") {
224 string const name = p.getArg('{', '}');
225 if (name == "environments" || name == "reLyXre")
226 // We understand "reLyXre", but it is
227 // not as powerful as "environments".
228 read_environment(p, name,
230 else if (name == "mathenvironments")
231 read_environment(p, name,
232 known_math_environments);
234 read_command(p, command, known_commands);
241 string documentclass;
243 bool overwrite_files = false;
246 /// return the number of arguments consumed
247 typedef int (*cmd_helper)(string const &, string const &);
250 int parse_help(string const &, string const &)
252 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
253 "Command line switches (case sensitive):\n"
254 "\t-help summarize tex2lyx usage\n"
255 "\t-f Force creation of .lyx files even if they exist already\n"
256 "\t-userdir dir try to set user directory to dir\n"
257 "\t-sysdir dir try to set system directory to dir\n"
258 "\t-c textclass declare the textclass\n"
259 "\t-n translate a noweb (aka literate programming) file.\n"
260 "\t-s syntaxfile read additional syntax file" << endl;
265 int parse_class(string const & arg, string const &)
268 cerr << "Missing textclass string after -c switch" << endl;
276 int parse_syntaxfile(string const & arg, string const &)
279 cerr << "Missing syntaxfile string after -s switch" << endl;
282 syntaxfile = internal_path(arg);
287 // Filled with the command line arguments "foo" of "-sysdir foo" or
289 string cl_system_support;
290 string cl_user_support;
293 int parse_sysdir(string const & arg, string const &)
296 cerr << "Missing directory for -sysdir switch" << endl;
299 cl_system_support = internal_path(arg);
304 int parse_userdir(string const & arg, string const &)
307 cerr << "Missing directory for -userdir switch" << endl;
310 cl_user_support = internal_path(arg);
315 int parse_force(string const &, string const &)
317 overwrite_files = true;
322 int parse_noweb(string const &, string const &)
329 void easyParse(int & argc, char * argv[])
331 map<string, cmd_helper> cmdmap;
333 cmdmap["-c"] = parse_class;
334 cmdmap["-f"] = parse_force;
335 cmdmap["-s"] = parse_syntaxfile;
336 cmdmap["-help"] = parse_help;
337 cmdmap["--help"] = parse_help;
338 cmdmap["-n"] = parse_noweb;
339 cmdmap["-sysdir"] = parse_sysdir;
340 cmdmap["-userdir"] = parse_userdir;
342 for (int i = 1; i < argc; ++i) {
343 map<string, cmd_helper>::const_iterator it
344 = cmdmap.find(argv[i]);
346 // don't complain if not found - may be parsed later
347 if (it == cmdmap.end())
350 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
351 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
353 int const remove = 1 + it->second(arg, arg2);
355 // Now, remove used arguments by shifting
356 // the following ones remove places down.
358 for (int j = i; j < argc; ++j)
359 argv[j] = argv[j + remove];
365 // path of the first parsed file
366 string masterFilePath;
367 // path of the currently parsed file
368 string parentFilePath;
370 } // anonymous namespace
373 string getMasterFilePath()
375 return masterFilePath;
378 string getParentFilePath()
380 return parentFilePath;
387 * Reads tex input from \a is and writes lyx output to \a os.
388 * Uses some common settings for the preamble, so this should only
389 * be used more than once for included documents.
390 * Caution: Overwrites the existing preamble settings if the new document
391 * contains a preamble.
392 * You must ensure that \p parentFilePath is properly set before calling
395 void tex2lyx(istream & is, ostream & os)
401 TextClass textclass = parse_preamble(p, ss, documentclass);
402 captionlayout = LayoutPtr(Layout::forCaption());
404 active_environments.push_back("document");
405 Context context(true, textclass);
406 parse_text(p, ss, FLAG_END, true, context);
408 // Empty document body. LyX needs at least one paragraph.
409 context.check_layout(ss);
410 context.check_end_layout(ss);
411 ss << "\n\\end_body\n\\end_document\n";
412 active_environments.pop_back();
417 ofstream parsertest("parsertest.tex");
419 parsertest << p.get_token().asInput();
420 // <origfile> and parsertest.tex should now have identical content
425 /// convert TeX from \p infilename to LyX and write it to \p os
426 bool tex2lyx(FileName const & infilename, ostream & os)
428 ifstream is(infilename.toFilesystemEncoding().c_str());
430 cerr << "Could not open input file \"" << infilename
431 << "\" for reading." << endl;
434 string const oldParentFilePath = parentFilePath;
435 parentFilePath = onlyPath(infilename.absFilename());
437 parentFilePath = oldParentFilePath;
441 } // anonymous namespace
444 bool tex2lyx(string const & infilename, FileName const & outfilename)
446 if (outfilename.isReadableFile()) {
447 if (overwrite_files) {
448 cerr << "Overwriting existing file "
449 << outfilename << endl;
451 cerr << "Not overwriting existing file "
452 << outfilename << endl;
456 cerr << "Creating file " << outfilename << endl;
458 ofstream os(outfilename.toFilesystemEncoding().c_str());
460 cerr << "Could not open output file \"" << outfilename
461 << "\" for writing." << endl;
465 cerr << "Input file: " << infilename << "\n";
466 cerr << "Output file: " << outfilename << "\n";
468 return tex2lyx(FileName(infilename), os);
474 int main(int argc, char * argv[])
478 lyxerr.setStream(cerr);
480 easyParse(argc, argv);
483 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
484 "See tex2lyx -help." << endl;
488 os::init(argc, argv);
490 try { init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
491 cl_system_support, cl_user_support,
492 top_build_dir_is_two_levels_up);
493 } catch (ExceptionMessage const & message) {
494 cerr << to_utf8(message.title_) << ":\n"
495 << to_utf8(message.details_) << endl;
496 if (message.type_ == ErrorException)
500 // Now every known option is parsed. Look for input and output
501 // file name (the latter is optional).
502 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
503 infilename = makeAbsPath(infilename).absFilename();
507 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
508 if (outfilename != "-")
509 outfilename = makeAbsPath(outfilename).absFilename();
511 outfilename = changeExtension(infilename, ".lyx");
513 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
514 if (system_syntaxfile.empty()) {
515 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
518 read_syntaxfile(system_syntaxfile);
519 if (!syntaxfile.empty())
520 read_syntaxfile(makeAbsPath(syntaxfile));
522 masterFilePath = onlyPath(infilename);
523 parentFilePath = masterFilePath;
525 if (outfilename == "-") {
526 if (tex2lyx(FileName(infilename), cout))
531 if (tex2lyx(infilename, FileName(outfilename)))