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/os.h"
27 #include "support/package.h"
28 #include "support/unicode.h"
30 #include <boost/function.hpp>
31 #include <boost/filesystem/operations.hpp>
32 #include <boost/filesystem/path.hpp>
52 using std::istringstream;
53 using std::ostringstream;
54 using std::stringstream;
59 using support::changeExtension;
60 using support::FileName;
61 using support::isStrUnsignedInt;
63 using support::makeAbsPath;
64 using support::onlyPath;
66 using support::isFileReadable;
68 namespace fs = boost::filesystem;
71 IconvProcessor & utf8ToUcs4()
73 static IconvProcessor iconv(ucs4_codeset, "UTF-8");
78 // Hacks to allow the thing to link in the lyxlayout stuff
79 LyXErr lyxerr(std::cerr.rdbuf());
82 string const trim(string const & a, char const * p)
89 string::size_type r = a.find_last_not_of(p);
90 string::size_type l = a.find_first_not_of(p);
92 // Is this the minimal test? (lgb)
93 if (r == string::npos && l == string::npos)
96 return a.substr(l, r - l + 1);
100 void split(string const & s, vector<string> & result, char delim)
102 //cerr << "split 1: '" << s << "'\n";
105 while (getline(is, t, delim))
107 //cerr << "split 2\n";
111 string join(vector<string> const & input, char const * delim)
114 for (size_t i = 0; i < input.size(); ++i) {
123 char const * const * is_known(string const & str, char const * const * what)
125 for ( ; *what; ++what)
133 // current stack of nested environments
134 vector<string> active_environments;
137 string active_environment()
139 return active_environments.empty() ? string() : active_environments.back();
143 CommandMap known_commands;
144 CommandMap known_environments;
145 CommandMap known_math_environments;
148 void add_known_command(string const & command, string const & o1,
151 // We have to handle the following cases:
152 // definition o1 o2 invocation result
153 // \newcommand{\foo}{bar} "" false \foo bar
154 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
155 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
156 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
157 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
158 unsigned int nargs = 0;
159 vector<ArgumentType> arguments;
160 string const opt1 = rtrim(ltrim(o1, "["), "]");
161 if (isStrUnsignedInt(opt1)) {
162 // The command has arguments
163 nargs = convert<unsigned int>(opt1);
164 if (nargs > 0 && o2) {
165 // The first argument is optional
166 arguments.push_back(optional);
170 for (unsigned int i = 0; i < nargs; ++i)
171 arguments.push_back(required);
172 known_commands[command] = arguments;
176 bool noweb_mode = false;
183 * Read one command definition from the syntax file
185 void read_command(Parser & p, string command, CommandMap & commands) {
186 if (p.next_token().asInput() == "*") {
190 vector<ArgumentType> arguments;
191 while (p.next_token().cat() == catBegin ||
192 p.next_token().asInput() == "[") {
193 if (p.next_token().cat() == catBegin) {
194 string const arg = p.getArg('{', '}');
195 if (arg == "translate")
196 arguments.push_back(required);
198 arguments.push_back(verbatim);
201 arguments.push_back(optional);
204 commands[command] = arguments;
209 * Read a class of environments from the syntax file
211 void read_environment(Parser & p, string const & begin,
212 CommandMap & environments)
216 Token const & t = p.get_token();
217 if (t.cat() == catLetter)
218 environment += t.asInput();
219 else if (!environment.empty()) {
221 read_command(p, environment, environments);
224 if (t.cat() == catEscape && t.asInput() == "\\end") {
225 string const end = p.getArg('{', '}');
234 * Read a list of TeX commands from a reLyX compatible syntax file.
235 * Since this list is used after all commands that have a LyX counterpart
236 * are handled, it does not matter that the "syntax.default" file
237 * has almost all of them listed. For the same reason the reLyX-specific
238 * reLyXre environment is ignored.
240 void read_syntaxfile(FileName const & file_name)
242 ifstream is(file_name.toFilesystemEncoding().c_str());
244 cerr << "Could not open syntax file \"" << file_name
245 << "\" for reading." << endl;
248 // We can use our TeX parser, since the syntax of the layout file is
249 // modeled after TeX.
250 // Unknown tokens are just silently ignored, this helps us to skip some
251 // reLyX specific things.
254 Token const & t = p.get_token();
255 if (t.cat() == catEscape) {
256 string const command = t.asInput();
257 if (command == "\\begin") {
258 string const name = p.getArg('{', '}');
259 if (name == "environments" || name == "reLyXre")
260 // We understand "reLyXre", but it is
261 // not as powerful as "environments".
262 read_environment(p, name,
264 else if (name == "mathenvironments")
265 read_environment(p, name,
266 known_math_environments);
268 read_command(p, command, known_commands);
275 string documentclass;
277 bool overwrite_files = false;
280 /// return the number of arguments consumed
281 typedef boost::function<int(string const &, string const &)> cmd_helper;
284 int parse_help(string const &, string const &)
286 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
287 "Command line switches (case sensitive):\n"
288 "\t-help summarize tex2lyx usage\n"
289 "\t-f Force creation of .lyx files even if they exist already\n"
290 "\t-userdir dir try to set user directory to dir\n"
291 "\t-sysdir dir try to set system directory to dir\n"
292 "\t-c textclass declare the textclass\n"
293 "\t-n translate a noweb (aka literate programming) file.\n"
294 "\t-s syntaxfile read additional syntax file" << endl;
299 int parse_class(string const & arg, string const &)
302 cerr << "Missing textclass string after -c switch" << endl;
310 int parse_syntaxfile(string const & arg, string const &)
313 cerr << "Missing syntaxfile string after -s switch" << endl;
321 // Filled with the command line arguments "foo" of "-sysdir foo" or
323 string cl_system_support;
324 string cl_user_support;
327 int parse_sysdir(string const & arg, string const &)
330 cerr << "Missing directory for -sysdir switch" << endl;
333 cl_system_support = arg;
338 int parse_userdir(string const & arg, string const &)
341 cerr << "Missing directory for -userdir switch" << endl;
344 cl_user_support = arg;
349 int parse_force(string const &, string const &)
351 overwrite_files = true;
356 int parse_noweb(string const &, string const &)
363 void easyParse(int & argc, char * argv[])
365 map<string, cmd_helper> cmdmap;
367 cmdmap["-c"] = parse_class;
368 cmdmap["-f"] = parse_force;
369 cmdmap["-s"] = parse_syntaxfile;
370 cmdmap["-help"] = parse_help;
371 cmdmap["--help"] = parse_help;
372 cmdmap["-n"] = parse_noweb;
373 cmdmap["-sysdir"] = parse_sysdir;
374 cmdmap["-userdir"] = parse_userdir;
376 for (int i = 1; i < argc; ++i) {
377 std::map<string, cmd_helper>::const_iterator it
378 = cmdmap.find(argv[i]);
380 // don't complain if not found - may be parsed later
381 if (it == cmdmap.end())
384 string arg((i + 1 < argc) ? argv[i + 1] : "");
385 string arg2((i + 2 < argc) ? argv[i + 2] : "");
387 int const remove = 1 + it->second(arg, arg2);
389 // Now, remove used arguments by shifting
390 // the following ones remove places down.
392 for (int j = i; j < argc; ++j)
393 argv[j] = argv[j + remove];
399 // path of the first parsed file
400 string masterFilePath;
401 // path of the currently parsed file
402 string parentFilePath;
404 } // anonymous namespace
407 string getMasterFilePath()
409 return masterFilePath;
412 string getParentFilePath()
414 return parentFilePath;
421 * Reads tex input from \a is and writes lyx output to \a os.
422 * Uses some common settings for the preamble, so this should only
423 * be used more than once for included documents.
424 * Caution: Overwrites the existing preamble settings if the new document
425 * contains a preamble.
426 * You must ensure that \p parentFilePath is properly set before calling
429 void tex2lyx(std::istream &is, std::ostream &os)
435 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
437 active_environments.push_back("document");
438 Context context(true, textclass);
439 parse_text(p, ss, FLAG_END, true, context);
441 // Empty document body. LyX needs at least one paragraph.
442 context.check_layout(ss);
443 context.check_end_layout(ss);
444 ss << "\n\\end_body\n\\end_document\n";
445 active_environments.pop_back();
450 ofstream parsertest("parsertest.tex");
452 parsertest << p.get_token().asInput();
453 // <origfile> and parsertest.tex should now have identical content
458 /// convert TeX from \p infilename to LyX and write it to \p os
459 bool tex2lyx(FileName const & infilename, std::ostream &os)
461 ifstream is(infilename.toFilesystemEncoding().c_str());
463 cerr << "Could not open input file \"" << infilename
464 << "\" for reading." << endl;
467 string const oldParentFilePath = parentFilePath;
468 parentFilePath = onlyPath(infilename.absFilename());
470 parentFilePath = oldParentFilePath;
474 } // anonymous namespace
477 bool tex2lyx(string const &infilename, FileName const &outfilename)
479 if (isFileReadable(outfilename)) {
480 if (overwrite_files) {
481 cerr << "Overwriting existing file "
482 << outfilename << endl;
484 cerr << "Not overwriting existing file "
485 << outfilename << endl;
489 cerr << "Creating file " << outfilename << endl;
491 ofstream os(outfilename.toFilesystemEncoding().c_str());
493 cerr << "Could not open output file \"" << outfilename
494 << "\" for writing." << endl;
498 cerr << "Input file: " << infilename << "\n";
499 cerr << "Output file: " << outfilename << "\n";
501 return tex2lyx(FileName(infilename), os);
507 int main(int argc, char * argv[])
510 fs::path::default_name_check(fs::no_check);
512 easyParse(argc, argv);
515 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
516 "See tex2lyx -help." << endl;
520 lyx::support::os::init(argc, argv);
521 lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
522 lyx::support::top_build_dir_is_two_levels_up);
524 // Now every known option is parsed. Look for input and output
525 // file name (the latter is optional).
526 string const infilename = makeAbsPath(argv[1]);
529 outfilename = argv[2];
530 if (outfilename != "-")
531 outfilename = makeAbsPath(argv[2]);
533 outfilename = changeExtension(infilename, ".lyx");
535 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
536 if (system_syntaxfile.empty()) {
537 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
540 read_syntaxfile(system_syntaxfile);
541 if (!syntaxfile.empty())
542 read_syntaxfile(FileName(makeAbsPath(syntaxfile)));
544 masterFilePath = onlyPath(infilename);
545 parentFilePath = masterFilePath;
547 if (outfilename == "-") {
548 if (tex2lyx(FileName(infilename), cout))
553 if (tex2lyx(infilename, FileName(outfilename)))