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.
19 #include "TextClass.h"
22 #include "support/convert.h"
23 #include "support/filetools.h"
24 #include "support/lstrings.h"
25 #include "support/lyxlib.h"
26 #include "support/ExceptionMessage.h"
27 #include "support/os.h"
28 #include "support/Package.h"
29 #include "support/unicode.h"
48 using std::istringstream;
49 using std::ostringstream;
50 using std::stringstream;
55 using support::changeExtension;
56 using support::FileName;
57 using support::isStrUnsignedInt;
59 using support::makeAbsPath;
60 using support::onlyPath;
61 using support::os::internal_path;
64 LayoutPtr captionlayout;
66 // Hacks to allow the thing to link in the lyxlayout stuff
67 LyXErr lyxerr(std::cerr.rdbuf());
70 string const trim(string const & a, char const * p)
77 size_t r = a.find_last_not_of(p);
78 size_t l = a.find_first_not_of(p);
80 // Is this the minimal test? (lgb)
81 if (r == string::npos && l == string::npos)
84 return a.substr(l, r - l + 1);
88 void split(string const & s, vector<string> & result, char delim)
90 //cerr << "split 1: '" << s << "'\n";
93 while (getline(is, t, delim))
95 //cerr << "split 2\n";
99 string join(vector<string> const & input, char const * delim)
102 for (size_t i = 0; i < input.size(); ++i) {
111 char const * const * is_known(string const & str, char const * const * what)
113 for ( ; *what; ++what)
121 // current stack of nested environments
122 vector<string> active_environments;
125 string active_environment()
127 return active_environments.empty() ? string() : active_environments.back();
131 CommandMap known_commands;
132 CommandMap known_environments;
133 CommandMap known_math_environments;
136 void add_known_command(string const & command, string const & o1,
139 // We have to handle the following cases:
140 // definition o1 o2 invocation result
141 // \newcommand{\foo}{bar} "" false \foo bar
142 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
143 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
144 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
145 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
146 unsigned int nargs = 0;
147 vector<ArgumentType> arguments;
148 string const opt1 = rtrim(ltrim(o1, "["), "]");
149 if (isStrUnsignedInt(opt1)) {
150 // The command has arguments
151 nargs = convert<unsigned int>(opt1);
152 if (nargs > 0 && o2) {
153 // The first argument is optional
154 arguments.push_back(optional);
158 for (unsigned int i = 0; i < nargs; ++i)
159 arguments.push_back(required);
160 known_commands[command] = arguments;
164 bool noweb_mode = false;
171 * Read one command definition from the syntax file
173 void read_command(Parser & p, string command, CommandMap & commands) {
174 if (p.next_token().asInput() == "*") {
178 vector<ArgumentType> arguments;
179 while (p.next_token().cat() == catBegin ||
180 p.next_token().asInput() == "[") {
181 if (p.next_token().cat() == catBegin) {
182 string const arg = p.getArg('{', '}');
183 if (arg == "translate")
184 arguments.push_back(required);
186 arguments.push_back(verbatim);
189 arguments.push_back(optional);
192 commands[command] = arguments;
197 * Read a class of environments from the syntax file
199 void read_environment(Parser & p, string const & begin,
200 CommandMap & environments)
204 Token const & t = p.get_token();
205 if (t.cat() == catLetter)
206 environment += t.asInput();
207 else if (!environment.empty()) {
209 read_command(p, environment, environments);
212 if (t.cat() == catEscape && t.asInput() == "\\end") {
213 string const end = p.getArg('{', '}');
222 * Read a list of TeX commands from a reLyX compatible syntax file.
223 * Since this list is used after all commands that have a LyX counterpart
224 * are handled, it does not matter that the "syntax.default" file
225 * has almost all of them listed. For the same reason the reLyX-specific
226 * reLyXre environment is ignored.
228 void read_syntaxfile(FileName const & file_name)
230 ifstream is(file_name.toFilesystemEncoding().c_str());
232 cerr << "Could not open syntax file \"" << file_name
233 << "\" for reading." << endl;
236 // We can use our TeX parser, since the syntax of the layout file is
237 // modeled after TeX.
238 // Unknown tokens are just silently ignored, this helps us to skip some
239 // reLyX specific things.
242 Token const & t = p.get_token();
243 if (t.cat() == catEscape) {
244 string const command = t.asInput();
245 if (command == "\\begin") {
246 string const name = p.getArg('{', '}');
247 if (name == "environments" || name == "reLyXre")
248 // We understand "reLyXre", but it is
249 // not as powerful as "environments".
250 read_environment(p, name,
252 else if (name == "mathenvironments")
253 read_environment(p, name,
254 known_math_environments);
256 read_command(p, command, known_commands);
263 string documentclass;
265 bool overwrite_files = false;
268 /// return the number of arguments consumed
269 typedef int (*cmd_helper)(string const &, string const &);
272 int parse_help(string const &, string const &)
274 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
275 "Command line switches (case sensitive):\n"
276 "\t-help summarize tex2lyx usage\n"
277 "\t-f Force creation of .lyx files even if they exist already\n"
278 "\t-userdir dir try to set user directory to dir\n"
279 "\t-sysdir dir try to set system directory to dir\n"
280 "\t-c textclass declare the textclass\n"
281 "\t-n translate a noweb (aka literate programming) file.\n"
282 "\t-s syntaxfile read additional syntax file" << endl;
287 int parse_class(string const & arg, string const &)
290 cerr << "Missing textclass string after -c switch" << endl;
298 int parse_syntaxfile(string const & arg, string const &)
301 cerr << "Missing syntaxfile string after -s switch" << endl;
304 syntaxfile = internal_path(arg);
309 // Filled with the command line arguments "foo" of "-sysdir foo" or
311 string cl_system_support;
312 string cl_user_support;
315 int parse_sysdir(string const & arg, string const &)
318 cerr << "Missing directory for -sysdir switch" << endl;
321 cl_system_support = internal_path(arg);
326 int parse_userdir(string const & arg, string const &)
329 cerr << "Missing directory for -userdir switch" << endl;
332 cl_user_support = internal_path(arg);
337 int parse_force(string const &, string const &)
339 overwrite_files = true;
344 int parse_noweb(string const &, string const &)
351 void easyParse(int & argc, char * argv[])
353 map<string, cmd_helper> cmdmap;
355 cmdmap["-c"] = parse_class;
356 cmdmap["-f"] = parse_force;
357 cmdmap["-s"] = parse_syntaxfile;
358 cmdmap["-help"] = parse_help;
359 cmdmap["--help"] = parse_help;
360 cmdmap["-n"] = parse_noweb;
361 cmdmap["-sysdir"] = parse_sysdir;
362 cmdmap["-userdir"] = parse_userdir;
364 for (int i = 1; i < argc; ++i) {
365 std::map<string, cmd_helper>::const_iterator it
366 = cmdmap.find(argv[i]);
368 // don't complain if not found - may be parsed later
369 if (it == cmdmap.end())
372 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
373 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
375 int const remove = 1 + it->second(arg, arg2);
377 // Now, remove used arguments by shifting
378 // the following ones remove places down.
380 for (int j = i; j < argc; ++j)
381 argv[j] = argv[j + remove];
387 // path of the first parsed file
388 string masterFilePath;
389 // path of the currently parsed file
390 string parentFilePath;
392 } // anonymous namespace
395 string getMasterFilePath()
397 return masterFilePath;
400 string getParentFilePath()
402 return parentFilePath;
409 * Reads tex input from \a is and writes lyx output to \a os.
410 * Uses some common settings for the preamble, so this should only
411 * be used more than once for included documents.
412 * Caution: Overwrites the existing preamble settings if the new document
413 * contains a preamble.
414 * You must ensure that \p parentFilePath is properly set before calling
417 void tex2lyx(std::istream & is, std::ostream & os)
423 TextClass textclass = parse_preamble(p, ss, documentclass);
424 captionlayout = LayoutPtr(Layout::forCaption());
426 active_environments.push_back("document");
427 Context context(true, textclass);
428 parse_text(p, ss, FLAG_END, true, context);
430 // Empty document body. LyX needs at least one paragraph.
431 context.check_layout(ss);
432 context.check_end_layout(ss);
433 ss << "\n\\end_body\n\\end_document\n";
434 active_environments.pop_back();
439 ofstream parsertest("parsertest.tex");
441 parsertest << p.get_token().asInput();
442 // <origfile> and parsertest.tex should now have identical content
447 /// convert TeX from \p infilename to LyX and write it to \p os
448 bool tex2lyx(FileName const & infilename, std::ostream & os)
450 ifstream is(infilename.toFilesystemEncoding().c_str());
452 cerr << "Could not open input file \"" << infilename
453 << "\" for reading." << endl;
456 string const oldParentFilePath = parentFilePath;
457 parentFilePath = onlyPath(infilename.absFilename());
459 parentFilePath = oldParentFilePath;
463 } // anonymous namespace
466 bool tex2lyx(string const & infilename, FileName const & outfilename)
468 if (outfilename.isReadableFile()) {
469 if (overwrite_files) {
470 cerr << "Overwriting existing file "
471 << outfilename << endl;
473 cerr << "Not overwriting existing file "
474 << outfilename << endl;
478 cerr << "Creating file " << outfilename << endl;
480 ofstream os(outfilename.toFilesystemEncoding().c_str());
482 cerr << "Could not open output file \"" << outfilename
483 << "\" for writing." << endl;
487 cerr << "Input file: " << infilename << "\n";
488 cerr << "Output file: " << outfilename << "\n";
490 return tex2lyx(FileName(infilename), os);
496 int main(int argc, char * argv[])
500 easyParse(argc, argv);
503 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
504 "See tex2lyx -help." << endl;
508 lyx::support::os::init(argc, argv);
510 try { support::init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
511 cl_system_support, cl_user_support,
512 support::top_build_dir_is_two_levels_up);
513 } catch (support::ExceptionMessage const & message) {
514 cerr << to_utf8(message.title_) << ":\n"
515 << to_utf8(message.details_) << endl;
516 if (message.type_ == support::ErrorException)
520 // Now every known option is parsed. Look for input and output
521 // file name (the latter is optional).
522 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
523 infilename = makeAbsPath(infilename).absFilename();
527 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
528 if (outfilename != "-")
529 outfilename = makeAbsPath(outfilename).absFilename();
531 outfilename = changeExtension(infilename, ".lyx");
533 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
534 if (system_syntaxfile.empty()) {
535 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
538 read_syntaxfile(system_syntaxfile);
539 if (!syntaxfile.empty())
540 read_syntaxfile(makeAbsPath(syntaxfile));
542 masterFilePath = onlyPath(infilename);
543 parentFilePath = masterFilePath;
545 if (outfilename == "-") {
546 if (tex2lyx(FileName(infilename), cout))
551 if (tex2lyx(infilename, FileName(outfilename)))