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"
29 #include <boost/function.hpp>
30 #include <boost/filesystem/operations.hpp>
31 #include <boost/filesystem/path.hpp>
48 using std::istringstream;
49 using std::ostringstream;
50 using std::stringstream;
55 using lyx::support::isStrUnsignedInt;
56 using lyx::support::ltrim;
57 using lyx::support::rtrim;
58 using lyx::support::IsFileReadable;
60 namespace fs = boost::filesystem;
63 // Hacks to allow the thing to link in the lyxlayout stuff
64 LyXErr lyxerr(std::cerr.rdbuf());
67 string const trim(string const & a, char const * p)
74 string::size_type r = a.find_last_not_of(p);
75 string::size_type l = a.find_first_not_of(p);
77 // Is this the minimal test? (lgb)
78 if (r == string::npos && l == string::npos)
81 return a.substr(l, r - l + 1);
85 void split(string const & s, vector<string> & result, char delim)
87 //cerr << "split 1: '" << s << "'\n";
90 while (getline(is, t, delim))
92 //cerr << "split 2\n";
96 string join(vector<string> const & input, char const * delim)
99 for (size_t i = 0; i < input.size(); ++i) {
108 char const * const * is_known(string const & str, char const * const * what)
110 for ( ; *what; ++what)
118 // current stack of nested environments
119 vector<string> active_environments;
122 string active_environment()
124 return active_environments.empty() ? string() : active_environments.back();
128 map<string, vector<ArgumentType> > known_commands;
131 void add_known_command(string const & command, string const & o1,
134 // We have to handle the following cases:
135 // definition o1 o2 invocation result
136 // \newcommand{\foo}{bar} "" false \foo bar
137 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
138 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
139 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
140 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
141 unsigned int nargs = 0;
142 vector<ArgumentType> arguments;
143 string const opt1 = rtrim(ltrim(o1, "["), "]");
144 if (isStrUnsignedInt(opt1)) {
145 // The command has arguments
146 nargs = convert<unsigned int>(opt1);
147 if (nargs > 0 && o2) {
148 // The first argument is optional
149 arguments.push_back(optional);
153 for (unsigned int i = 0; i < nargs; ++i)
154 arguments.push_back(required);
155 known_commands[command] = arguments;
163 * Read a list of TeX commands from a reLyX compatible syntax file.
164 * Since this list is used after all commands that have a LyX counterpart
165 * are handled, it does not matter that the "syntax.default" file from reLyX
166 * has almost all of them listed. For the same reason the reLyX-specific
167 * reLyXre environment is ignored.
169 void read_syntaxfile(string const & file_name)
171 if (!IsFileReadable(file_name)) {
172 cerr << "Could not open syntax file \"" << file_name
173 << "\" for reading." << endl;
176 ifstream is(file_name.c_str());
177 // We can use our TeX parser, since the syntax of the layout file is
178 // modeled after TeX.
179 // Unknown tokens are just silently ignored, this helps us to skip some
180 // reLyX specific things.
183 Token const & t = p.get_token();
184 if (t.cat() == catEscape) {
185 string command = t.asInput();
186 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 known_commands[command] = arguments;
211 string documentclass;
213 bool overwrite_files = false;
216 /// return the number of arguments consumed
217 typedef boost::function<int(string const &, string const &)> cmd_helper;
220 int parse_help(string const &, string const &)
222 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
223 "Command line switches (case sensitive):\n"
224 "\t-help summarize tex2lyx usage\n"
225 "\t-f Force creation of .lyx files even if they exist already\n"
226 "\t-userdir dir try to set user directory to dir\n"
227 "\t-sysdir dir try to set system directory to dir\n"
228 "\t-c textclass declare the textclass\n"
229 "\t-s syntaxfile read additional syntax file" << endl;
234 int parse_class(string const & arg, string const &)
237 cerr << "Missing textclass string after -c switch" << endl;
245 int parse_syntaxfile(string const & arg, string const &)
248 cerr << "Missing syntaxfile string after -s switch" << endl;
256 // Filled with the command line arguments "foo" of "-sysdir foo" or
258 string cl_system_support;
259 string cl_user_support;
262 int parse_sysdir(string const & arg, string const &)
265 cerr << "Missing directory for -sysdir switch" << endl;
268 cl_system_support = arg;
273 int parse_userdir(string const & arg, string const &)
276 cerr << "Missing directory for -userdir switch" << endl;
279 cl_user_support = arg;
284 int parse_force(string const &, string const &)
286 overwrite_files = true;
291 void easyParse(int & argc, char * argv[])
293 map<string, cmd_helper> cmdmap;
295 cmdmap["-c"] = parse_class;
296 cmdmap["-f"] = parse_force;
297 cmdmap["-s"] = parse_syntaxfile;
298 cmdmap["-help"] = parse_help;
299 cmdmap["--help"] = parse_help;
300 cmdmap["-sysdir"] = parse_sysdir;
301 cmdmap["-userdir"] = parse_userdir;
303 for (int i = 1; i < argc; ++i) {
304 std::map<string, cmd_helper>::const_iterator it
305 = cmdmap.find(argv[i]);
307 // don't complain if not found - may be parsed later
308 if (it == cmdmap.end())
311 string arg((i + 1 < argc) ? argv[i + 1] : "");
312 string arg2((i + 2 < argc) ? argv[i + 2] : "");
314 int const remove = 1 + it->second(arg, arg2);
316 // Now, remove used arguments by shifting
317 // the following ones remove places down.
319 for (int j = i; j < argc; ++j)
320 argv[j] = argv[j + remove];
326 // path of the parsed file
327 string masterFilePath;
329 } // anonymous namespace
332 string getMasterFilePath()
334 return masterFilePath;
338 void tex2lyx(std::istream &is, std::ostream &os)
344 LyXTextClass textclass = parse_preamble(p, ss, documentclass);
346 active_environments.push_back("document");
347 Context context(true, textclass);
348 parse_text(p, ss, FLAG_END, true, context);
349 context.check_end_layout(ss);
350 ss << "\n\\end_body\n\\end_document\n";
351 active_environments.pop_back();
356 ofstream parsertest("parsertest.tex");
358 parsertest << p.get_token().asInput();
359 // <origfile> and parsertest.tex should now have identical content
364 bool tex2lyx(string const &infilename, string const &outfilename)
366 if (!(IsFileReadable(infilename) && fs::is_writable(outfilename))) {
369 if (!overwrite_files && IsFileReadable(outfilename)) {
370 cerr << "Not overwriting existing file " << outfilename << "\n";
373 ifstream is(infilename.c_str());
374 ofstream os(outfilename.c_str());
376 cerr << "File: " << infilename << "\n";
383 int main(int argc, char * argv[])
385 fs::path::default_name_check(fs::no_check);
387 easyParse(argc, argv);
390 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex>\n"
391 "See tex2lyx -help." << endl;
395 lyx::support::os::init(argc, argv);
396 lyx::support::init_package(argv[0], cl_system_support, cl_user_support,
397 lyx::support::top_build_dir_is_two_levels_up);
399 string const system_syntaxfile = lyx::support::LibFileSearch("reLyX", "syntax.default");
400 if (system_syntaxfile.empty()) {
401 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
404 read_syntaxfile(system_syntaxfile);
405 if (!syntaxfile.empty())
406 read_syntaxfile(syntaxfile);
408 if (!IsFileReadable(argv[1])) {
409 cerr << "Could not open input file \"" << argv[1]
410 << "\" for reading." << endl;
414 if (lyx::support::AbsolutePath(argv[1]))
415 masterFilePath = lyx::support::OnlyPath(argv[1]);
417 masterFilePath = lyx::support::getcwd();
419 ifstream is(argv[1]);