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 "lyxtextclass.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
23 #include "support/fs_extras.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"
31 #include <boost/function.hpp>
32 #include <boost/filesystem/operations.hpp>
33 #include <boost/filesystem/path.hpp>
53 using std::istringstream;
54 using std::ostringstream;
55 using std::stringstream;
60 using support::changeExtension;
61 using support::FileName;
62 using support::isStrUnsignedInt;
64 using support::makeAbsPath;
65 using support::onlyPath;
67 using support::isFileReadable;
69 namespace fs = boost::filesystem;
72 IconvProcessor & utf8ToUcs4()
74 static IconvProcessor iconv(ucs4_codeset, "UTF-8");
79 // Hacks to allow the thing to link in the lyxlayout stuff
80 LyXErr lyxerr(std::cerr.rdbuf());
83 string const trim(string const & a, char const * p)
90 string::size_type r = a.find_last_not_of(p);
91 string::size_type l = a.find_first_not_of(p);
93 // Is this the minimal test? (lgb)
94 if (r == string::npos && l == string::npos)
97 return a.substr(l, r - l + 1);
101 void split(string const & s, vector<string> & result, char delim)
103 //cerr << "split 1: '" << s << "'\n";
106 while (getline(is, t, delim))
108 //cerr << "split 2\n";
112 string join(vector<string> const & input, char const * delim)
115 for (size_t i = 0; i < input.size(); ++i) {
124 char const * const * is_known(string const & str, char const * const * what)
126 for ( ; *what; ++what)
134 // current stack of nested environments
135 vector<string> active_environments;
138 string active_environment()
140 return active_environments.empty() ? string() : active_environments.back();
144 CommandMap known_commands;
145 CommandMap known_environments;
146 CommandMap known_math_environments;
149 void add_known_command(string const & command, string const & o1,
152 // We have to handle the following cases:
153 // definition o1 o2 invocation result
154 // \newcommand{\foo}{bar} "" false \foo bar
155 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
156 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
157 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
158 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
159 unsigned int nargs = 0;
160 vector<ArgumentType> arguments;
161 string const opt1 = rtrim(ltrim(o1, "["), "]");
162 if (isStrUnsignedInt(opt1)) {
163 // The command has arguments
164 nargs = convert<unsigned int>(opt1);
165 if (nargs > 0 && o2) {
166 // The first argument is optional
167 arguments.push_back(optional);
171 for (unsigned int i = 0; i < nargs; ++i)
172 arguments.push_back(required);
173 known_commands[command] = arguments;
177 bool noweb_mode = false;
184 * Read one command definition from the syntax file
186 void read_command(Parser & p, string command, CommandMap & commands) {
187 if (p.next_token().asInput() == "*") {
191 vector<ArgumentType> arguments;
192 while (p.next_token().cat() == catBegin ||
193 p.next_token().asInput() == "[") {
194 if (p.next_token().cat() == catBegin) {
195 string const arg = p.getArg('{', '}');
196 if (arg == "translate")
197 arguments.push_back(required);
199 arguments.push_back(verbatim);
202 arguments.push_back(optional);
205 commands[command] = arguments;
210 * Read a class of environments from the syntax file
212 void read_environment(Parser & p, string const & begin,
213 CommandMap & environments)
217 Token const & t = p.get_token();
218 if (t.cat() == catLetter)
219 environment += t.asInput();
220 else if (!environment.empty()) {
222 read_command(p, environment, environments);
225 if (t.cat() == catEscape && t.asInput() == "\\end") {
226 string const end = p.getArg('{', '}');
235 * Read a list of TeX commands from a reLyX compatible syntax file.
236 * Since this list is used after all commands that have a LyX counterpart
237 * are handled, it does not matter that the "syntax.default" file
238 * has almost all of them listed. For the same reason the reLyX-specific
239 * reLyXre environment is ignored.
241 void read_syntaxfile(FileName const & file_name)
243 ifstream is(file_name.toFilesystemEncoding().c_str());
245 cerr << "Could not open syntax file \"" << file_name
246 << "\" for reading." << endl;
249 // We can use our TeX parser, since the syntax of the layout file is
250 // modeled after TeX.
251 // Unknown tokens are just silently ignored, this helps us to skip some
252 // reLyX specific things.
255 Token const & t = p.get_token();
256 if (t.cat() == catEscape) {
257 string const command = t.asInput();
258 if (command == "\\begin") {
259 string const name = p.getArg('{', '}');
260 if (name == "environments" || name == "reLyXre")
261 // We understand "reLyXre", but it is
262 // not as powerful as "environments".
263 read_environment(p, name,
265 else if (name == "mathenvironments")
266 read_environment(p, name,
267 known_math_environments);
269 read_command(p, command, known_commands);
276 string documentclass;
278 bool overwrite_files = false;
281 /// return the number of arguments consumed
282 typedef boost::function<int(string const &, string const &)> cmd_helper;
285 int parse_help(string const &, string const &)
287 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
288 "Command line switches (case sensitive):\n"
289 "\t-help summarize tex2lyx usage\n"
290 "\t-f Force creation of .lyx files even if they exist already\n"
291 "\t-userdir dir try to set user directory to dir\n"
292 "\t-sysdir dir try to set system directory to dir\n"
293 "\t-c textclass declare the textclass\n"
294 "\t-n translate a noweb (aka literate programming) file.\n"
295 "\t-s syntaxfile read additional syntax file" << endl;
300 int parse_class(string const & arg, string const &)
303 cerr << "Missing textclass string after -c switch" << endl;
311 int parse_syntaxfile(string const & arg, string const &)
314 cerr << "Missing syntaxfile string after -s switch" << endl;
322 // Filled with the command line arguments "foo" of "-sysdir foo" or
324 string cl_system_support;
325 string cl_user_support;
328 int parse_sysdir(string const & arg, string const &)
331 cerr << "Missing directory for -sysdir switch" << endl;
334 cl_system_support = arg;
339 int parse_userdir(string const & arg, string const &)
342 cerr << "Missing directory for -userdir switch" << endl;
345 cl_user_support = arg;
350 int parse_force(string const &, string const &)
352 overwrite_files = true;
357 int parse_noweb(string const &, string const &)
364 void easyParse(int & argc, char * argv[])
366 map<string, cmd_helper> cmdmap;
368 cmdmap["-c"] = parse_class;
369 cmdmap["-f"] = parse_force;
370 cmdmap["-s"] = parse_syntaxfile;
371 cmdmap["-help"] = parse_help;
372 cmdmap["--help"] = parse_help;
373 cmdmap["-n"] = parse_noweb;
374 cmdmap["-sysdir"] = parse_sysdir;
375 cmdmap["-userdir"] = parse_userdir;
377 for (int i = 1; i < argc; ++i) {
378 std::map<string, cmd_helper>::const_iterator it
379 = cmdmap.find(argv[i]);
381 // don't complain if not found - may be parsed later
382 if (it == cmdmap.end())
385 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
386 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
388 int const remove = 1 + it->second(arg, arg2);
390 // Now, remove used arguments by shifting
391 // the following ones remove places down.
393 for (int j = i; j < argc; ++j)
394 argv[j] = argv[j + remove];
400 // path of the first parsed file
401 string masterFilePath;
402 // path of the currently parsed file
403 string parentFilePath;
405 } // anonymous namespace
408 string getMasterFilePath()
410 return masterFilePath;
413 string getParentFilePath()
415 return parentFilePath;
422 * Reads tex input from \a is and writes lyx output to \a os.
423 * Uses some common settings for the preamble, so this should only
424 * be used more than once for included documents.
425 * Caution: Overwrites the existing preamble settings if the new document
426 * contains a preamble.
427 * You must ensure that \p parentFilePath is properly set before calling
430 void tex2lyx(std::istream &is, std::ostream &os)
436 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
438 active_environments.push_back("document");
439 Context context(true, textclass);
440 parse_text(p, ss, FLAG_END, true, context);
442 // Empty document body. LyX needs at least one paragraph.
443 context.check_layout(ss);
444 context.check_end_layout(ss);
445 ss << "\n\\end_body\n\\end_document\n";
446 active_environments.pop_back();
451 ofstream parsertest("parsertest.tex");
453 parsertest << p.get_token().asInput();
454 // <origfile> and parsertest.tex should now have identical content
459 /// convert TeX from \p infilename to LyX and write it to \p os
460 bool tex2lyx(FileName const & infilename, std::ostream &os)
462 ifstream is(infilename.toFilesystemEncoding().c_str());
464 cerr << "Could not open input file \"" << infilename
465 << "\" for reading." << endl;
468 string const oldParentFilePath = parentFilePath;
469 parentFilePath = onlyPath(infilename.absFilename());
471 parentFilePath = oldParentFilePath;
475 } // anonymous namespace
478 bool tex2lyx(string const &infilename, FileName const &outfilename)
480 if (isFileReadable(outfilename)) {
481 if (overwrite_files) {
482 cerr << "Overwriting existing file "
483 << outfilename << endl;
485 cerr << "Not overwriting existing file "
486 << outfilename << endl;
490 cerr << "Creating file " << outfilename << endl;
492 ofstream os(outfilename.toFilesystemEncoding().c_str());
494 cerr << "Could not open output file \"" << outfilename
495 << "\" for writing." << endl;
499 cerr << "Input file: " << infilename << "\n";
500 cerr << "Output file: " << outfilename << "\n";
502 return tex2lyx(FileName(infilename), os);
508 int main(int argc, char * argv[])
511 fs::path::default_name_check(fs::no_check);
513 easyParse(argc, argv);
516 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
517 "See tex2lyx -help." << endl;
521 lyx::support::os::init(argc, argv);
523 try { support::init_package(to_utf8(from_local8bit(argv[0])),
524 cl_system_support, cl_user_support,
525 support::top_build_dir_is_two_levels_up);
526 } catch (support::ExceptionMessage const & message) {
527 cerr << to_utf8(message.title_) << ":\n"
528 << to_utf8(message.details_) << endl;
529 if (message.type_ == support::ErrorException)
533 // Now every known option is parsed. Look for input and output
534 // file name (the latter is optional).
535 string const infilename = makeAbsPath(to_utf8(from_local8bit(argv[1]))).absFilename();
538 outfilename = to_utf8(from_local8bit(argv[2]));
539 if (outfilename != "-")
540 outfilename = makeAbsPath(to_utf8(from_local8bit(argv[2]))).absFilename();
542 outfilename = changeExtension(infilename, ".lyx");
544 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
545 if (system_syntaxfile.empty()) {
546 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
549 read_syntaxfile(system_syntaxfile);
550 if (!syntaxfile.empty())
551 read_syntaxfile(makeAbsPath(syntaxfile));
553 masterFilePath = onlyPath(infilename);
554 parentFilePath = masterFilePath;
556 if (outfilename == "-") {
557 if (tex2lyx(FileName(infilename), cout))
562 if (tex2lyx(infilename, FileName(outfilename)))