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/fs_extras.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/ExceptionMessage.h"
28 #include "support/os.h"
29 #include "support/Package.h"
30 #include "support/unicode.h"
32 #include <boost/function.hpp>
33 #include <boost/filesystem/operations.hpp>
34 #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;
66 using support::os::internal_path;
68 using support::isFileReadable;
70 namespace fs = boost::filesystem;
72 LayoutPtr captionlayout;
74 // Hacks to allow the thing to link in the lyxlayout stuff
75 LyXErr lyxerr(std::cerr.rdbuf());
78 string const trim(string const & a, char const * p)
85 string::size_type r = a.find_last_not_of(p);
86 string::size_type l = a.find_first_not_of(p);
88 // Is this the minimal test? (lgb)
89 if (r == string::npos && l == string::npos)
92 return a.substr(l, r - l + 1);
96 void split(string const & s, vector<string> & result, char delim)
98 //cerr << "split 1: '" << s << "'\n";
101 while (getline(is, t, delim))
103 //cerr << "split 2\n";
107 string join(vector<string> const & input, char const * delim)
110 for (size_t i = 0; i < input.size(); ++i) {
119 char const * const * is_known(string const & str, char const * const * what)
121 for ( ; *what; ++what)
129 // current stack of nested environments
130 vector<string> active_environments;
133 string active_environment()
135 return active_environments.empty() ? string() : active_environments.back();
139 CommandMap known_commands;
140 CommandMap known_environments;
141 CommandMap known_math_environments;
144 void add_known_command(string const & command, string const & o1,
147 // We have to handle the following cases:
148 // definition o1 o2 invocation result
149 // \newcommand{\foo}{bar} "" false \foo bar
150 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
151 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
152 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
153 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
154 unsigned int nargs = 0;
155 vector<ArgumentType> arguments;
156 string const opt1 = rtrim(ltrim(o1, "["), "]");
157 if (isStrUnsignedInt(opt1)) {
158 // The command has arguments
159 nargs = convert<unsigned int>(opt1);
160 if (nargs > 0 && o2) {
161 // The first argument is optional
162 arguments.push_back(optional);
166 for (unsigned int i = 0; i < nargs; ++i)
167 arguments.push_back(required);
168 known_commands[command] = arguments;
172 bool noweb_mode = false;
179 * Read one command definition from the syntax file
181 void read_command(Parser & p, string command, CommandMap & commands) {
182 if (p.next_token().asInput() == "*") {
186 vector<ArgumentType> arguments;
187 while (p.next_token().cat() == catBegin ||
188 p.next_token().asInput() == "[") {
189 if (p.next_token().cat() == catBegin) {
190 string const arg = p.getArg('{', '}');
191 if (arg == "translate")
192 arguments.push_back(required);
194 arguments.push_back(verbatim);
197 arguments.push_back(optional);
200 commands[command] = arguments;
205 * Read a class of environments from the syntax file
207 void read_environment(Parser & p, string const & begin,
208 CommandMap & environments)
212 Token const & t = p.get_token();
213 if (t.cat() == catLetter)
214 environment += t.asInput();
215 else if (!environment.empty()) {
217 read_command(p, environment, environments);
220 if (t.cat() == catEscape && t.asInput() == "\\end") {
221 string const end = p.getArg('{', '}');
230 * Read a list of TeX commands from a reLyX compatible syntax file.
231 * Since this list is used after all commands that have a LyX counterpart
232 * are handled, it does not matter that the "syntax.default" file
233 * has almost all of them listed. For the same reason the reLyX-specific
234 * reLyXre environment is ignored.
236 void read_syntaxfile(FileName const & file_name)
238 ifstream is(file_name.toFilesystemEncoding().c_str());
240 cerr << "Could not open syntax file \"" << file_name
241 << "\" for reading." << endl;
244 // We can use our TeX parser, since the syntax of the layout file is
245 // modeled after TeX.
246 // Unknown tokens are just silently ignored, this helps us to skip some
247 // reLyX specific things.
250 Token const & t = p.get_token();
251 if (t.cat() == catEscape) {
252 string const command = t.asInput();
253 if (command == "\\begin") {
254 string const name = p.getArg('{', '}');
255 if (name == "environments" || name == "reLyXre")
256 // We understand "reLyXre", but it is
257 // not as powerful as "environments".
258 read_environment(p, name,
260 else if (name == "mathenvironments")
261 read_environment(p, name,
262 known_math_environments);
264 read_command(p, command, known_commands);
271 string documentclass;
273 bool overwrite_files = false;
276 /// return the number of arguments consumed
277 typedef boost::function<int(string const &, string const &)> cmd_helper;
280 int parse_help(string const &, string const &)
282 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
283 "Command line switches (case sensitive):\n"
284 "\t-help summarize tex2lyx usage\n"
285 "\t-f Force creation of .lyx files even if they exist already\n"
286 "\t-userdir dir try to set user directory to dir\n"
287 "\t-sysdir dir try to set system directory to dir\n"
288 "\t-c textclass declare the textclass\n"
289 "\t-n translate a noweb (aka literate programming) file.\n"
290 "\t-s syntaxfile read additional syntax file" << endl;
295 int parse_class(string const & arg, string const &)
298 cerr << "Missing textclass string after -c switch" << endl;
306 int parse_syntaxfile(string const & arg, string const &)
309 cerr << "Missing syntaxfile string after -s switch" << endl;
312 syntaxfile = internal_path(arg);
317 // Filled with the command line arguments "foo" of "-sysdir foo" or
319 string cl_system_support;
320 string cl_user_support;
323 int parse_sysdir(string const & arg, string const &)
326 cerr << "Missing directory for -sysdir switch" << endl;
329 cl_system_support = internal_path(arg);
334 int parse_userdir(string const & arg, string const &)
337 cerr << "Missing directory for -userdir switch" << endl;
340 cl_user_support = internal_path(arg);
345 int parse_force(string const &, string const &)
347 overwrite_files = true;
352 int parse_noweb(string const &, string const &)
359 void easyParse(int & argc, char * argv[])
361 map<string, cmd_helper> cmdmap;
363 cmdmap["-c"] = parse_class;
364 cmdmap["-f"] = parse_force;
365 cmdmap["-s"] = parse_syntaxfile;
366 cmdmap["-help"] = parse_help;
367 cmdmap["--help"] = parse_help;
368 cmdmap["-n"] = parse_noweb;
369 cmdmap["-sysdir"] = parse_sysdir;
370 cmdmap["-userdir"] = parse_userdir;
372 for (int i = 1; i < argc; ++i) {
373 std::map<string, cmd_helper>::const_iterator it
374 = cmdmap.find(argv[i]);
376 // don't complain if not found - may be parsed later
377 if (it == cmdmap.end())
380 string arg(to_utf8(from_local8bit((i + 1 < argc) ? argv[i + 1] : "")));
381 string arg2(to_utf8(from_local8bit((i + 2 < argc) ? argv[i + 2] : "")));
383 int const remove = 1 + it->second(arg, arg2);
385 // Now, remove used arguments by shifting
386 // the following ones remove places down.
388 for (int j = i; j < argc; ++j)
389 argv[j] = argv[j + remove];
395 // path of the first parsed file
396 string masterFilePath;
397 // path of the currently parsed file
398 string parentFilePath;
400 } // anonymous namespace
403 string getMasterFilePath()
405 return masterFilePath;
408 string getParentFilePath()
410 return parentFilePath;
417 * Reads tex input from \a is and writes lyx output to \a os.
418 * Uses some common settings for the preamble, so this should only
419 * be used more than once for included documents.
420 * Caution: Overwrites the existing preamble settings if the new document
421 * contains a preamble.
422 * You must ensure that \p parentFilePath is properly set before calling
425 void tex2lyx(std::istream &is, std::ostream &os)
431 TextClass textclass = parse_preamble(p, ss, documentclass);
432 captionlayout = LayoutPtr(Layout::forCaption());
434 active_environments.push_back("document");
435 Context context(true, textclass);
436 parse_text(p, ss, FLAG_END, true, context);
438 // Empty document body. LyX needs at least one paragraph.
439 context.check_layout(ss);
440 context.check_end_layout(ss);
441 ss << "\n\\end_body\n\\end_document\n";
442 active_environments.pop_back();
447 ofstream parsertest("parsertest.tex");
449 parsertest << p.get_token().asInput();
450 // <origfile> and parsertest.tex should now have identical content
455 /// convert TeX from \p infilename to LyX and write it to \p os
456 bool tex2lyx(FileName const & infilename, std::ostream &os)
458 ifstream is(infilename.toFilesystemEncoding().c_str());
460 cerr << "Could not open input file \"" << infilename
461 << "\" for reading." << endl;
464 string const oldParentFilePath = parentFilePath;
465 parentFilePath = onlyPath(infilename.absFilename());
467 parentFilePath = oldParentFilePath;
471 } // anonymous namespace
474 bool tex2lyx(string const &infilename, FileName const &outfilename)
476 if (isFileReadable(outfilename)) {
477 if (overwrite_files) {
478 cerr << "Overwriting existing file "
479 << outfilename << endl;
481 cerr << "Not overwriting existing file "
482 << outfilename << endl;
486 cerr << "Creating file " << outfilename << endl;
488 ofstream os(outfilename.toFilesystemEncoding().c_str());
490 cerr << "Could not open output file \"" << outfilename
491 << "\" for writing." << endl;
495 cerr << "Input file: " << infilename << "\n";
496 cerr << "Output file: " << outfilename << "\n";
498 return tex2lyx(FileName(infilename), os);
504 int main(int argc, char * argv[])
507 fs::path::default_name_check(fs::no_check);
509 easyParse(argc, argv);
512 cerr << "Usage: tex2lyx [ command line switches ] <infile.tex> [<outfile.lyx>]\n"
513 "See tex2lyx -help." << endl;
517 lyx::support::os::init(argc, argv);
519 try { support::init_package(internal_path(to_utf8(from_local8bit(argv[0]))),
520 cl_system_support, cl_user_support,
521 support::top_build_dir_is_two_levels_up);
522 } catch (support::ExceptionMessage const & message) {
523 cerr << to_utf8(message.title_) << ":\n"
524 << to_utf8(message.details_) << endl;
525 if (message.type_ == support::ErrorException)
529 // Now every known option is parsed. Look for input and output
530 // file name (the latter is optional).
531 string infilename = internal_path(to_utf8(from_local8bit(argv[1])));
532 infilename = makeAbsPath(infilename).absFilename();
536 outfilename = internal_path(to_utf8(from_local8bit(argv[2])));
537 if (outfilename != "-")
538 outfilename = makeAbsPath(outfilename).absFilename();
540 outfilename = changeExtension(infilename, ".lyx");
542 FileName const system_syntaxfile = lyx::support::libFileSearch("", "syntax.default");
543 if (system_syntaxfile.empty()) {
544 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
547 read_syntaxfile(system_syntaxfile);
548 if (!syntaxfile.empty())
549 read_syntaxfile(makeAbsPath(syntaxfile));
551 masterFilePath = onlyPath(infilename);
552 parentFilePath = masterFilePath;
554 if (outfilename == "-") {
555 if (tex2lyx(FileName(infilename), cout))
560 if (tex2lyx(infilename, FileName(outfilename)))